1 \input texinfo @c -*-texinfo-*-
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c GNAT DOCUMENTATION o
10 @c Copyright (C) 1992-2002 Ada Core Technologies, Inc. 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
23 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
25 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
27 @c GNAT_UG Style Guide
29 @c 1. Always put a @noindent on the line before the first paragraph
30 @c after any of these commands:
42 @c 2. DO NOT use @example. Use @smallexample instead.
44 @c 3. Each @chapter, @section, @subsection, @subsubsection, etc.
45 @c command must be preceded by two empty lines
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.
50 @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
53 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
56 @setfilename gnat_ug_vms.info
57 @settitle GNAT User's Guide for OpenVMS Alpha
58 @dircategory GNU Ada tools
60 * GNAT User's Guide (gnat_ug_vms). GNAT User's Guide for OpenVMS Alpha.
65 @setfilename gnat_ug_wnt.info
66 @settitle GNAT User's Guide for Windows NT
67 @dircategory GNU Ada tools
69 * GNAT User's Guide (gnat_ug_wnt). GNAT User's Guide for Windows NT.
74 @setfilename gnat_ug_unx.info
75 @settitle GNAT User's Guide for Unix Platforms
76 @dircategory GNU Ada tools
78 * GNAT User's Guide (gnat_ug_unx). GNAT User's Guide for Unix Platforms.
83 @setfilename gnat_ug_vxw.info
84 @settitle GNAT User's Guide for Cross Platforms
85 @dircategory GNU Ada tools
87 * GNAT User's Guide (gnat_ug_vxw). GNAT User's Guide for Cross Platforms.
91 @include gcc-common.texi
93 @setchapternewpage odd
98 Copyright @copyright{} 1995-2003, Free Software Foundation
100 Permission is granted to copy, distribute and/or modify this document
101 under the terms of the GNU Free Documentation License, Version 1.2
102 or any later version published by the Free Software Foundation;
103 with the Invariant Sections being ``GNU Free Documentation License'', with the
104 Front-Cover Texts being
106 ``GNAT User's Guide for OpenVMS Alpha'',
109 ``GNAT User's Guide for Windows NT'',
112 ``GNAT User's Guide for Unix Platforms'',
115 ``GNAT User's Guide for Cross Platforms'',
117 and with no Back-Cover Texts.
118 A copy of the license is included in the section entitled ``GNU
119 Free Documentation License''.
125 @title GNAT User's Guide
126 @center @titlefont{for OpenVMS Alpha}
130 @title GNAT User's Guide
131 @center @titlefont{for Windows NT}
135 @title GNAT User's Guide
136 @center @titlefont{for Unix Platforms}
140 @title GNAT User's Guide
141 @center @titlefont{for Cross Platforms}
144 @subtitle GNAT, The GNU Ada 95 Compiler
145 @subtitle GNAT Version for GCC @value{version-GCC}
147 @author Ada Core Technologies, Inc.
150 @vskip 0pt plus 1filll
157 @node Top, About This Guide, (dir), (dir)
158 @top GNAT User's Guide
161 GNAT User's Guide for OpenVMS Alpha
165 GNAT User's Guide for Windows NT
169 GNAT User's Guide for Unix Platforms
173 GNAT User's Guide for Cross Platforms
176 GNAT, The GNU Ada 95 Compiler
178 GNAT Version for GCC @value{version-GCC}
180 Ada Core Technologies, Inc.
187 * Preliminary Note for Cross Platform Users::
189 * Getting Started with GNAT::
190 * The GNAT Compilation Model::
191 * Compiling Using gcc::
192 * Binding Using gnatbind::
193 * Linking Using gnatlink::
194 * The GNAT Make Program gnatmake::
195 * Renaming Files Using gnatchop::
196 * Configuration Pragmas::
197 * Handling Arbitrary File Naming Conventions Using gnatname::
198 * GNAT Project Manager::
199 * Elaboration Order Handling in GNAT::
200 * The Cross-Referencing Tools gnatxref and gnatfind::
201 * File Name Krunching Using gnatkr::
202 * Preprocessing Using gnatprep::
204 * The GNAT Run-Time Library Builder gnatlbr::
206 * The GNAT Library Browser gnatls::
208 * GNAT and Libraries::
209 * Using the GNU make Utility::
211 * Finding Memory Problems with gnatmem::
214 * Finding Memory Problems with GNAT Debug Pool::
215 * Creating Sample Bodies Using gnatstub::
216 * Reducing the Size of Ada Executables with gnatelim::
217 * Other Utility Programs::
219 * Compatibility with DEC Ada::
221 * Running and Debugging Ada Programs::
224 * Microsoft Windows Topics::
230 * Performance Considerations::
231 * GNU Free Documentation License::
234 --- The Detailed Node Listing ---
238 * What This Guide Contains::
239 * What You Should Know before Reading This Guide::
240 * Related Information::
244 Preliminary Note for Cross Platform Users::
247 Getting Started with GNAT
251 * Running a Simple Ada Program::
254 * Building a Simple Ada Program::
255 * Executing a Program on VxWorks::
257 * Running a Program with Multiple Units::
258 * Using the gnatmake Utility::
260 * Editing with Emacs::
263 The GNAT Compilation Model
265 * Source Representation::
266 * Foreign Language Representation::
267 * File Naming Rules::
268 * Using Other File Names::
269 * Alternative File Naming Schemes::
270 * Generating Object Files::
271 * Source Dependencies::
272 * The Ada Library Information Files::
273 * Binding an Ada Program::
274 * Mixed Language Programming::
275 * Building Mixed Ada & C++ Programs::
276 * Comparison between GNAT and C/C++ Compilation Models::
277 * Comparison between GNAT and Conventional Ada Library Models::
279 Foreign Language Representation
282 * Other 8-Bit Codes::
283 * Wide Character Encodings::
285 Compiling Ada Programs With gcc
287 * Compiling Programs::
289 * Search Paths and the Run-Time Library (RTL)::
290 * Order of Compilation Issues::
295 * Output and Error Message Control::
296 * Debugging and Assertion Control::
298 * Stack Overflow Checking::
300 * Validity Checking::
302 * Using gcc for Syntax Checking::
303 * Using gcc for Semantic Checking::
304 * Compiling Ada 83 Programs::
305 * Character Set Control::
306 * File Naming Control::
307 * Subprogram Inlining Control::
308 * Auxiliary Output Control::
309 * Debugging Control::
310 * Units to Sources Mapping Files::
312 Binding Ada Programs With gnatbind
315 * Generating the Binder Program in C::
316 * Consistency-Checking Modes::
317 * Binder Error Message Control::
318 * Elaboration Control::
320 * Binding with Non-Ada Main Programs::
321 * Binding Programs with No Main Subprogram::
322 * Summary of Binder Switches::
323 * Command-Line Access::
324 * Search Paths for gnatbind::
325 * Examples of gnatbind Usage::
327 Linking Using gnatlink
330 * Switches for gnatlink::
331 * Setting Stack Size from gnatlink::
332 * Setting Heap Size from gnatlink::
334 The GNAT Make Program gnatmake
337 * Switches for gnatmake::
338 * Mode Switches for gnatmake::
339 * Notes on the Command Line::
340 * How gnatmake Works::
341 * Examples of gnatmake Usage::
343 Renaming Files Using gnatchop
345 * Handling Files with Multiple Units::
346 * Operating gnatchop in Compilation Mode::
347 * Command Line for gnatchop::
348 * Switches for gnatchop::
349 * Examples of gnatchop Usage::
351 Configuration Pragmas
353 * Handling of Configuration Pragmas::
354 * The Configuration Pragmas Files::
356 Handling Arbitrary File Naming Conventions Using gnatname
358 * Arbitrary File Naming Conventions::
360 * Switches for gnatname::
361 * Examples of gnatname Usage::
366 * Examples of Project Files::
367 * Project File Syntax::
368 * Objects and Sources in Project Files::
369 * Importing Projects::
370 * Project Extension::
371 * External References in Project Files::
372 * Packages in Project Files::
373 * Variables from Imported Projects::
376 * Switches Related to Project Files::
377 * Tools Supporting Project Files::
378 * An Extended Example::
379 * Project File Complete Syntax::
381 Elaboration Order Handling in GNAT
383 * Elaboration Code in Ada 95::
384 * Checking the Elaboration Order in Ada 95::
385 * Controlling the Elaboration Order in Ada 95::
386 * Controlling Elaboration in GNAT - Internal Calls::
387 * Controlling Elaboration in GNAT - External Calls::
388 * Default Behavior in GNAT - Ensuring Safety::
389 * Elaboration Issues for Library Tasks::
390 * Mixing Elaboration Models::
391 * What to Do If the Default Elaboration Behavior Fails::
392 * Elaboration for Access-to-Subprogram Values::
393 * Summary of Procedures for Elaboration Control::
394 * Other Elaboration Order Considerations::
396 The Cross-Referencing Tools gnatxref and gnatfind
398 * gnatxref Switches::
399 * gnatfind Switches::
400 * Project Files for gnatxref and gnatfind::
401 * Regular Expressions in gnatfind and gnatxref::
402 * Examples of gnatxref Usage::
403 * Examples of gnatfind Usage::
405 File Name Krunching Using gnatkr
410 * Examples of gnatkr Usage::
412 Preprocessing Using gnatprep
415 * Switches for gnatprep::
416 * Form of Definitions File::
417 * Form of Input Text for gnatprep::
420 The GNAT Run-Time Library Builder gnatlbr
423 * Switches for gnatlbr::
424 * Examples of gnatlbr Usage::
427 The GNAT Library Browser gnatls
430 * Switches for gnatls::
431 * Examples of gnatls Usage::
437 * Creating an Ada Library::
438 * Installing an Ada Library::
439 * Using an Ada Library::
440 * Creating an Ada Library to be Used in a Non-Ada Context::
441 * Rebuilding the GNAT Run-Time Library::
443 Using the GNU make Utility
445 * Using gnatmake in a Makefile::
446 * Automatically Creating a List of Directories::
447 * Generating the Command Line Switches::
448 * Overcoming Command Line Length Limits::
451 Finding Memory Problems with gnatmem
453 * Running gnatmem (GDB Mode)::
454 * Running gnatmem (GMEM Mode)::
455 * Switches for gnatmem::
456 * Examples of gnatmem Usage::
457 * GDB and GMEM Modes::
458 * Implementation Note::
463 Finding Memory Problems with GNAT Debug Pool
465 Creating Sample Bodies Using gnatstub
468 * Switches for gnatstub::
470 Reducing the Size of Ada Executables with gnatelim
475 * Preparing Tree and Bind Files for gnatelim::
477 * Correcting the List of Eliminate Pragmas::
478 * Making Your Executables Smaller::
479 * Summary of the gnatelim Usage Cycle::
481 Other Utility Programs
483 * Using Other Utility Programs with GNAT::
484 * The gnatpsta Utility Program::
485 * The External Symbol Naming Scheme of GNAT::
486 * Ada Mode for Glide::
487 * Converting Ada Files to html with gnathtml::
493 Compatibility with DEC Ada
495 * Ada 95 Compatibility::
496 * Differences in the Definition of Package System::
497 * Language-Related Features::
498 * The Package STANDARD::
499 * The Package SYSTEM::
500 * Tasking and Task-Related Features::
501 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
502 * Pragmas and Pragma-Related Features::
503 * Library of Predefined Units::
505 * Main Program Definition::
506 * Implementation-Defined Attributes::
507 * Compiler and Run-Time Interfacing::
508 * Program Compilation and Library Management::
510 * Implementation Limits::
513 Language-Related Features
515 * Integer Types and Representations::
516 * Floating-Point Types and Representations::
517 * Pragmas Float_Representation and Long_Float::
518 * Fixed-Point Types and Representations::
519 * Record and Array Component Alignment::
521 * Other Representation Clauses::
523 Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
525 * Assigning Task IDs::
526 * Task IDs and Delays::
527 * Task-Related Pragmas::
528 * Scheduling and Task Priority::
530 * External Interrupts::
532 Pragmas and Pragma-Related Features
534 * Restrictions on the Pragma INLINE::
535 * Restrictions on the Pragma INTERFACE::
536 * Restrictions on the Pragma SYSTEM_NAME::
538 Library of Predefined Units
540 * Changes to DECLIB::
544 * Shared Libraries and Options Files::
548 Running and Debugging Ada Programs
550 * The GNAT Debugger GDB::
552 * Introduction to GDB Commands::
553 * Using Ada Expressions::
554 * Calling User-Defined Subprograms::
555 * Using the Next Command in a Function::
558 * Debugging Generic Units::
559 * GNAT Abnormal Termination or Failure to Terminate::
560 * Naming Conventions for GNAT Source Files::
561 * Getting Internal Debugging Information::
566 * Basic Assembler Syntax::
567 * A Simple Example of Inline Assembler::
568 * Output Variables in Inline Assembler::
569 * Input Variables in Inline Assembler::
570 * Inlining Inline Assembler Code::
571 * Other Asm Functionality::
572 * A Complete Example::
575 Microsoft Windows Topics
577 * Using GNAT on Windows::
579 * CONSOLE and WINDOWS subsystems::
581 * Mixed-Language Programming on Windows::
582 * Windows Calling Conventions::
583 * Introduction to Dynamic Link Libraries (DLLs)::
584 * Using DLLs with GNAT::
585 * Building DLLs with GNAT::
586 * GNAT and Windows Resources::
587 * GNAT and COM/DCOM Objects::
593 * Kernel Configuration for VxWorks::
594 * Kernel Compilation Issues for VxWorks::
595 * Handling Relocation Issues for PowerPc Targets::
596 * Support for Software Floating Point on PowerPC Processors::
597 * Interrupt Handling for VxWorks::
598 * Simulating Command Line Arguments for VxWorks::
599 * Debugging Issues for VxWorks::
600 * Using GNAT from the Tornado 2 Project Facility::
601 * Frequently Asked Questions for VxWorks::
605 * Getting Started with GNAT on LynxOS::
606 * Kernel Configuration for LynxOS::
607 * Patch Level Issues for LynxOS::
608 * Debugging Issues for LynxOS::
609 * An Example Debugging Session for LynxOS::
612 Performance Considerations
614 * Controlling Run-Time Checks::
615 * Optimization Levels::
616 * Debugging Optimized Code::
617 * Inlining of Subprograms::
619 * Coverage Analysis::
626 @node About This Guide
627 @unnumbered About This Guide
631 This guide describes the use of of GNAT, a full language compiler for the Ada
632 95 programming language, implemented on DIGITAL OpenVMS Alpha Systems.
635 This guide describes the use of GNAT, a compiler and software development
636 toolset for the full Ada 95 programming language.
638 It describes the features of the compiler and tools, and details
639 how to use them to build Ada 95 applications.
642 * What This Guide Contains::
643 * What You Should Know before Reading This Guide::
644 * Related Information::
648 @node What This Guide Contains
649 @unnumberedsec What This Guide Contains
652 This guide contains the following chapters:
656 @ref{Preliminary Note for Cross Platform Users}, describes the basic
657 differences between the cross and native versions of GNAT.
660 @ref{Getting Started with GNAT}, describes how to get started compiling
661 and running Ada programs with the GNAT Ada programming environment.
663 @ref{The GNAT Compilation Model}, describes the compilation model used
666 @ref{Compiling Using gcc}, describes how to compile
667 Ada programs with @code{gcc}, the Ada compiler.
669 @ref{Binding Using gnatbind}, describes how to
670 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
673 @ref{Linking Using gnatlink},
674 describes @code{gnatlink}, a
675 program that provides for linking using the GNAT run-time library to
676 construct a program. @code{gnatlink} can also incorporate foreign language
677 object units into the executable.
679 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
680 utility that automatically determines the set of sources
681 needed by an Ada compilation unit, and executes the necessary compilations
684 @ref{Renaming Files Using gnatchop}, describes
685 @code{gnatchop}, a utility that allows you to preprocess a file that
686 contains Ada source code, and split it into one or more new files, one
687 for each compilation unit.
689 @ref{Configuration Pragmas}, describes the configuration pragmas handled by GNAT.
691 @ref{Handling Arbitrary File Naming Conventions Using gnatname}, shows how to override
692 the default GNAT file naming conventions, either for an individual unit or globally.
694 @ref{GNAT Project Manager}, describes how to use project files to organize large projects.
696 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps you deal with
697 elaboration order issues.
699 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
700 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
701 way to navigate through sources.
703 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
704 file name krunching utility, used to handle shortened
705 file names on operating systems with a limit on the length of names.
707 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
708 preprocessor utility that allows a single source file to be used to
709 generate multiple or parameterized source files, by means of macro
712 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
713 utility that displays information about compiled units, including dependences
714 on the corresponding sources files, and consistency of compilations.
717 @ref{GNAT and Libraries}, describes the process of creating and using
718 Libraries with GNAT. It also describes how to recompile the GNAT run-time
722 @ref{Using the GNU make Utility}, describes some techniques for using
723 the GNAT toolset in Makefiles.
727 @ref{Finding Memory Problems with gnatmem}, describes @code{gnatmem}, a
728 utility that monitors dynamic allocation and deallocation activity in a
729 program, and displays information about incorrect deallocations and sources
730 of possible memory leaks.
734 @ref{Finding Memory Problems with GNAT Debug Pool}, describes how to
735 use the GNAT-specific Debug Pool in order to detect as early as possible
736 the use of incorrect memory references.
739 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
740 a utility that generates empty but compilable bodies for library units.
743 @ref{Reducing the Size of Ada Executables with gnatelim}, describes
744 @code{gnatelim}, a tool which detects unused subprograms and helps
745 the compiler to create a smaller executable for the program.
748 @ref{Other Utility Programs}, discusses several other GNAT utilities,
749 including @code{gnatpsta}.
752 @ref{Running and Debugging Ada Programs}, describes how to run and debug
756 @ref{Inline Assembler}, shows how to use the inline assembly facility in an Ada program.
760 @ref{VxWorks Topics}, presents information relevant to the VxWorks target for cross-compilation
764 @ref{LynxOS Topics}, presents information relevant to the LynxOS target for cross-compilation
769 @ref{Performance Considerations}, reviews the trade offs between using
770 defaults or options in program development.
773 @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with
774 DEC Ada 83 for OpenVMS Alpha.
778 @node What You Should Know before Reading This Guide
779 @unnumberedsec What You Should Know before Reading This Guide
781 @cindex Ada 95 Language Reference Manual
783 This user's guide assumes that you are familiar with Ada 95 language, as
784 described in the International Standard ANSI/ISO/IEC-8652:1995, Jan
787 @node Related Information
788 @unnumberedsec Related Information
791 For further information about related tools, refer to the following
796 @cite{GNAT Reference Manual}, which contains all reference
797 material for the GNAT implementation of Ada 95.
800 @cite{Ada 95 Language Reference Manual}, which contains all reference
801 material for the Ada 95 programming language.
804 @cite{Debugging with GDB}
806 , located in the GNU:[DOCS] directory,
808 contains all details on the use of the GNU source-level debugger.
811 @cite{GNU Emacs Manual}
813 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
815 contains full information on the extensible editor and programming
821 @unnumberedsec Conventions
823 @cindex Typographical conventions
826 Following are examples of the typographical and graphic conventions used
831 @code{Functions}, @code{utility program names}, @code{standard names},
838 @file{File Names}, @file{button names}, and @file{field names}.
847 [optional information or parameters]
850 Examples are described by text
852 and then shown this way.
857 Commands that are entered by the user are preceded in this manual by the
858 characters @w{"@code{$ }"} (dollar sign followed by space). If your system
859 uses this sequence as a prompt, then the commands will appear exactly as
860 you see them in the manual. If your system uses some other prompt, then
861 the command will appear with the @code{$} replaced by whatever prompt
862 character you are using.
865 @node Preliminary Note for Cross Platform Users
866 @chapter Preliminary Note for Cross Platform Users
869 The use of GNAT in a cross environment is very similar to its use in a
870 native environment. Most of the tools described in this manual have
871 similar functions and options in both modes. The major
872 difference is that the name of the cross tools includes the target for
873 which the cross compiler is configured. For instance, the cross @command{gnatmake}
874 tool is called @command{@i{target}-gnatmake} where @code{@i{target}} stands for the name of
875 the cross target. Thus, in an environment configured for the
876 target @code{powerpc-wrs-vxworks}, the @command{gnatmake} command is
877 @code{powerpc-wrs-vxworks-gnatmake}. This convention allows the
878 installation of a native and one or several cross development
879 environments at the same location.
881 The tools that are most relevant in a cross environment are:
882 @code{@i{target}-gcc}, @code{@i{target}-gnatmake},
883 @code{@i{target}-gnatbind}, @code{@i{target}-gnatlink} to build cross
884 applications and @code{@i{target}-gnatls} for cross library
885 browsing. @code{@i{target}-gdb} is also usually available for cross
886 debugging in text mode. The graphical debugger interface
887 @code{gvd} is always a native tool but it can be configured to drive
888 the above mentioned cross debugger, thus allowing graphical cross debugging
889 sessions. Some other tools such as @code{@i{target}-gnatchop},
890 @code{@i{target}-gnatkr}, @code{@i{target}-gnatprep},
891 @code{@i{target}-gnatpsta}, @code{@i{target}-gnatxref}, @code{@i{target}-gnatfind}
892 and @code{@i{target}-gnatname} are also provided for completeness
893 even though they do not differ greatly from their native counterpart.
895 In the rest of this manual, the tools are sometimes designated with
896 their full cross name, and sometimes with their simplified native
901 @node Getting Started with GNAT
902 @chapter Getting Started with GNAT
906 This chapter describes some simple ways of using GNAT to build
907 executable Ada programs.
911 This introduction is a starting point for using GNAT to develop
912 and execute Ada 95 programs in a cross environment.
913 It provides some specifics
914 about the GNAT toolchain targeted to the Wind River Sytems' VxWorks/Tornado platform;
915 for other targets please refer to the corresponding chapter later in this manual.
917 Basic familiarity with use of GNAT in a native environment is
918 presumed. For the VxWorks specific part, a knowledge of how to start
919 Tornado's @code{windsh} tool is also presumed.
925 * Running a Simple Ada Program::
928 * Building a Simple Ada Program::
929 * Executing a Program on VxWorks::
932 * Running a Program with Multiple Units::
934 * Using the gnatmake Utility::
936 * Editing with Emacs::
939 * Introduction to Glide and GVD::
944 @section Running GNAT
947 Three steps are needed to create an executable file from an Ada source
952 The source file(s) must be compiled.
954 The file(s) must be bound using the GNAT binder.
957 All appropriate object files must be linked to produce an executable.
960 All appropriate object files must be linked to produce a loadable module.
965 All three steps are most commonly handled by using the @code{gnatmake}
966 utility program that, given the name of the main program, automatically
967 performs the necessary compilation, binding and linking steps.
970 @node Running a Simple Ada Program
971 @section Running a Simple Ada Program
974 @node Building a Simple Ada Program
975 @section Building a Simple Ada Program
979 Any text editor may be used to prepare an Ada program. If @code{Glide} is
980 used, the optional Ada mode may be helpful in laying out the program. The
981 program text is a normal text file. We will suppose in our initial
982 example that you have used your editor to prepare the following
983 standard format text file:
988 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
989 @b{procedure} Hello @b{is}
991 Put_Line ("Hello WORLD!");
998 This file should be named @file{hello.adb}.
999 With the normal default file naming conventions, GNAT requires
1001 contain a single compilation unit whose file name is the
1003 with periods replaced by hyphens; the
1004 extension is @file{ads} for a
1005 spec and @file{adb} for a body.
1006 You can override this default file naming convention by use of the
1007 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1008 Alternatively, if you want to rename your files according to this default
1009 convention, which is probably more convenient if you will be using GNAT
1010 for all your compilations, then the @code{gnatchop} utility
1011 can be used to generate correctly-named source files
1012 (@pxref{Renaming Files Using gnatchop}).
1014 You can compile the program using the following command (@code{$} is used
1015 as the command prompt in the examples in this document):
1025 $ @i{target}-gcc -c hello.adb
1030 @code{gcc} is the command used to run the compiler. This compiler is
1031 capable of compiling programs in several languages, including Ada 95 and
1032 C. It assumes that you have given it an Ada program if the file extension is
1033 either @file{.ads} or @file{.adb}, and it will then call the GNAT compiler to compile
1037 The @option{-c} switch is required. It tells @command{gcc} to only do a
1038 compilation. (For C programs, @command{gcc} can also do linking, but this
1039 capability is not used directly for Ada programs, so the @option{-c}
1040 switch must always be present.)
1043 This compile command generates a file
1044 @file{hello.o}, which is the object
1045 file corresponding to your Ada program. It also generates an "Ada Library Information" file
1047 which contains additional information used to check
1048 that an Ada program is consistent.
1050 To build an executable file,
1053 To build a downloadable module,
1055 use @code{gnatbind} to bind the program
1056 and @code{gnatlink} to link it. The
1057 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1058 @file{ali} file, but the default extension of @file{.ali} can
1059 be omitted. This means that in the most common case, the argument
1060 is simply the name of the main program:
1071 $ @i{target}-gnatbind hello
1072 $ @i{target}-gnatlink hello
1077 A simpler method of carrying out these steps is to use
1079 a master program that invokes all the required
1080 compilation, binding and linking tools in the correct order. In particular,
1081 @command{gnatmake} automatically recompiles any sources that have been modified
1082 since they were last compiled, or sources that depend
1083 on such modified sources, so that "version skew" is avoided.
1084 @cindex Version skew (avoided by @command{gnatmake})
1088 $ gnatmake hello.adb
1094 $ @i{target}-gnatmake hello.adb
1100 The result is an executable program called @file{hello}, which can be
1103 @c The following should be removed (BMB 2001-01-23)
1105 @c $ ^./hello^$ RUN HELLO^
1106 @c @end smallexample
1113 assuming that the current directory is on the search path for executable programs.
1116 and, if all has gone well, you will see
1123 appear in response to this command.
1129 The result is a relocatable object called @file{hello}.
1131 @emph{Technical note:} the result of the linking stage is a
1132 relocatable partially-linked object containing all the relevant GNAT
1133 run-time units, in contrast with the executable-format object file found in
1134 native environments.
1137 @node Executing a Program on VxWorks
1138 @section Executing a Program on VxWorks
1141 Getting a program to execute involves loading it onto the target, running it, and then (if re-execution is needed) unloading it.
1144 * Loading and Running the Program::
1145 * Unloading the Program::
1148 @node Loading and Running the Program
1149 @subsection Loading and Running the Program
1152 An Ada program is loaded and run in the same way as a C program.
1153 Details may be found in the @cite{Tornado User's Guide}.
1155 In order to load and run our simple "Hello World" example, we assume that
1156 the target has access to the disk of the host containing this object and
1157 that its working directory has been set to the directory containing this
1158 object. The commands are typed in Tornado's Windshell. The @code{windsh} prompt
1159 is the @code{->} sequence.
1162 -> vf0=open("/vio/0",2,0)
1163 new symbol "vf0" added to symbol table.
1164 vf0 = 0x2cab48: value = 12 = 0xc
1165 -> ioGlobalStdSet(1,vf0)
1168 value = 665408 = 0xa2740
1176 The first two commands redirect output to the shell window.
1177 They are only needed if the target server was started without the
1178 @code{-C} option. The third command loads the module, which is the file
1179 @file{hello} created previously by the @code{@i{target}-gnatmake} command.
1180 Note that for Tornado AE, the @command{ml} command replaces @command{ld}."
1182 The "Hello World" program comprises a procedure named @code{hello}, and this
1183 is the name entered for the procedure in the target server's symbol table
1184 when the module is loaded. To execute the procedure, type the symbol name @code{hello}
1185 into @code{windsh} as shown in the last command above.
1187 Note that by default the entry point of an Ada program is the name of the main
1188 Ada subprogram in a VxWorks environment. It is possible to use an alternative
1189 name; see the description of @code{gnatbind} options for details.
1191 @node Unloading the Program
1192 @subsection Unloading the Program
1195 It is important to remember that
1196 you must unload a program once you have run it. You
1197 cannot load it once and run it several times. If you don't follow
1198 this rule, your program's behavior can be unpredictable, and will most
1201 This effect is due to the implementation of Ada 95's @emph{elaboration} semantics.
1202 The unit elaboration phase comprises a @emph{static} elaboration and a
1203 @emph{dynamic} elaboration. On a native platform they both take place
1204 when the program is run. Thus rerunning the program will repeat the complete
1205 elaboration phase, and the program will run correctly.
1207 On VxWorks, the process is a bit different.
1208 The static elaboration phase is handled by
1209 the loader (typically when you type @code{ld < program_name} in
1210 @code{windsh}). The dynamic phase takes place when the program is run. If the
1211 program is run twice and has not been unloaded and then reloaded, the
1212 second time it is run, the static elaboration phase is skipped.
1213 Variables initialized during the static elaboration phase
1214 may have been modified during the first execution of the program. Thus the
1215 second execution isn't performed on a completely initialized environment.
1217 Note that in C programs, elaboration isn't systematic. Multiple runs without reload
1218 might work, but, even with C programs, if there is an elaboration
1219 phase, you will have to unload your program before re-running it.
1223 @node Running a Program with Multiple Units
1224 @section Running a Program with Multiple Units
1227 Consider a slightly more complicated example that has three files: a
1228 main program, and the spec and body of a package:
1233 @b{package} Greetings @b{is}
1234 @b{procedure} Hello;
1235 @b{procedure} Goodbye;
1238 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
1239 @b{package} @b{body} Greetings @b{is}
1240 @b{procedure} Hello @b{is}
1242 Put_Line ("Hello WORLD!");
1245 @b{procedure} Goodbye @b{is}
1247 Put_Line ("Goodbye WORLD!");
1254 @b{procedure} Gmain @b{is}
1264 Following the one-unit-per-file rule, place this program in the
1265 following three separate files:
1269 spec of package @code{Greetings}
1272 body of package @code{Greetings}
1275 body of main program
1279 To build an executable version of
1280 this program, we could use four separate steps to compile, bind, and link
1281 the program, as follows:
1286 $ gcc -c greetings.adb
1294 $ @i{target}-gcc -c gmain.adb
1295 $ @i{target}-gcc -c greetings.adb
1296 $ @i{target}-gnatbind gmain
1297 $ @i{target}-gnatlink gmain
1302 Note that there is no required order of compilation when using GNAT.
1303 In particular it is perfectly fine to compile the main program first.
1304 Also, it is not necessary to compile package specs in the case where
1305 there is an accompanying body; you only need to compile the body. If you want
1306 to submit these files to the compiler for semantic checking and not code generation,
1308 @option{-gnatc} switch:
1312 $ gcc -c greetings.ads -gnatc
1318 $ @i{target}-gcc -c greetings.ads -gnatc
1323 Although the compilation can be done in separate steps as in the
1324 above example, in practice it is almost always more convenient
1325 to use the @code{gnatmake} tool. All you need to know in this case
1326 is the name of the main program's source file. The effect of the above four
1327 commands can be achieved with a single one:
1331 $ gnatmake gmain.adb
1337 $ @i{target}-gnatmake gmain.adb
1342 In the next section we discuss the advantages of using @code{gnatmake} in
1345 @node Using the gnatmake Utility
1346 @section Using the @command{gnatmake} Utility
1349 If you work on a program by compiling single components at a time using
1350 @code{gcc}, you typically keep track of the units you modify. In order to
1351 build a consistent system, you compile not only these units, but also any
1352 units that depend on the units you have modified.
1353 For example, in the preceding case,
1354 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1355 you edit @file{greetings.ads}, you must recompile both
1356 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1357 units that depend on @file{greetings.ads}.
1359 @code{gnatbind} will warn you if you forget one of these compilation
1360 steps, so that it is impossible to generate an inconsistent program as a
1361 result of forgetting to do a compilation. Nevertheless it is tedious and
1362 error-prone to keep track of dependencies among units.
1363 One approach to handle the dependency-bookkeeping is to use a
1364 makefile. However, makefiles present maintenance problems of their own:
1365 if the dependencies change as you change the program, you must make
1366 sure that the makefile is kept up-to-date manually, which is also an
1367 error-prone process.
1369 The @code{gnatmake} utility takes care of these details automatically.
1370 Invoke it using either one of the following forms:
1374 $ gnatmake gmain.adb
1375 $ gnatmake ^gmain^GMAIN^
1381 $ @i{target}-gnatmake gmain.adb
1382 $ @i{target}-gnatmake gmain
1387 The argument is the name of the file containing the main program;
1388 you may omit the extension. @code{gnatmake}
1389 examines the environment, automatically recompiles any files that need
1390 recompiling, and binds and links the resulting set of object files,
1391 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1392 In a large program, it
1393 can be extremely helpful to use @code{gnatmake}, because working out by hand
1394 what needs to be recompiled can be difficult.
1396 Note that @code{gnatmake}
1397 takes into account all the Ada 95 rules that
1398 establish dependencies among units. These include dependencies that result
1399 from inlining subprogram bodies, and from
1400 generic instantiation. Unlike some other
1401 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1402 found by the compiler on a previous compilation, which may possibly
1403 be wrong when sources change. @code{gnatmake} determines the exact set of
1404 dependencies from scratch each time it is run.
1407 @node Editing with Emacs
1408 @section Editing with Emacs
1412 Emacs is an extensible self-documenting text editor that is available in a
1413 separate VMSINSTAL kit.
1415 Invoke Emacs by typing "Emacs" at the command prompt. To get started,
1416 click on the Emacs Help menu and run the Emacs Tutorial.
1417 In a character cell terminal, Emacs help is invoked with "Ctrl-h" (also written
1418 as "C-h"), and the tutorial by "C-h t".
1420 Documentation on Emacs and other tools is available in Emacs under the
1421 pull-down menu button: Help - Info. After selecting Info, use the middle
1422 mouse button to select a topic (e.g. Emacs).
1424 In a character cell terminal, do "C-h i" to invoke info, and then "m"
1425 (stands for menu) followed by the menu item desired, as in "m Emacs", to get
1426 to the Emacs manual.
1427 Help on Emacs is also available by typing "HELP EMACS" at the DCL command
1430 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1431 which is sufficiently extensible to provide for a complete programming
1432 environment and shell for the sophisticated user.
1436 @node Introduction to Glide and GVD
1437 @section Introduction to Glide and GVD
1441 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.
1444 * Building a New Program with Glide::
1445 * Simple Debugging with GVD::
1446 * Other Glide Features::
1449 @node Building a New Program with Glide
1450 @subsection Building a New Program with Glide
1452 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:
1459 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
1461 @item @code{Buffers}
1472 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.
1474 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.
1476 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:
1478 with Ada.Text_IO; use Ada.Text_IO;
1484 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.
1486 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.
1488 Next enter the statement (with an intentional error, a missing semicolon) that will form the body of the loop:
1490 Put_Line("Hello, World" & Integer'Image(I))
1494 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.
1496 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.
1498 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.
1500 To execute the program, choose @code{Ada} and then @code{Run}. You should see the program's output displayed in the bottom window:
1510 @node Simple Debugging with GVD
1511 @subsection Simple Debugging with GVD
1514 This section describes how to set breakpoints, examine/modify variables, and step through execution.
1516 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:
1523 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}.
1525 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.
1527 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.
1529 For this example, set a breakpoint at the statement where @code{Put_Line} is invoked.
1531 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.
1533 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.
1535 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.
1537 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}.
1539 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.
1542 @node Other Glide Features
1543 @subsection Other Glide Features
1546 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...}.
1548 To abort a Glide command, type @key{Ctrl-g}.
1550 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:
1557 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.
1559 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}.
1561 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:
1563 @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)
1564 @item With the focus in one of the windows, select the desired buffer from the @code{Buffers} menu
1568 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1571 @node The GNAT Compilation Model
1572 @chapter The GNAT Compilation Model
1573 @cindex GNAT compilation model
1574 @cindex Compilation model
1577 * Source Representation::
1578 * Foreign Language Representation::
1579 * File Naming Rules::
1580 * Using Other File Names::
1581 * Alternative File Naming Schemes::
1582 * Generating Object Files::
1583 * Source Dependencies::
1584 * The Ada Library Information Files::
1585 * Binding an Ada Program::
1586 * Mixed Language Programming::
1587 * Building Mixed Ada & C++ Programs::
1588 * Comparison between GNAT and C/C++ Compilation Models::
1589 * Comparison between GNAT and Conventional Ada Library Models::
1593 This chapter describes the compilation model used by GNAT. Although
1594 similar to that used by other languages, such as C and C++, this model
1595 is substantially different from the traditional Ada compilation models,
1596 which are based on a library. The model is initially described without
1597 reference to the library-based model. If you have not previously used an
1598 Ada compiler, you need only read the first part of this chapter. The
1599 last section describes and discusses the differences between the GNAT
1600 model and the traditional Ada compiler models. If you have used other
1601 Ada compilers, this section will help you to understand those
1602 differences, and the advantages of the GNAT model.
1604 @node Source Representation
1605 @section Source Representation
1609 Ada source programs are represented in standard text files, using
1610 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1611 7-bit ASCII set, plus additional characters used for
1612 representing foreign languages (@pxref{Foreign Language Representation}
1613 for support of non-USA character sets). The format effector characters
1614 are represented using their standard ASCII encodings, as follows:
1619 Vertical tab, @code{16#0B#}
1623 Horizontal tab, @code{16#09#}
1627 Carriage return, @code{16#0D#}
1631 Line feed, @code{16#0A#}
1635 Form feed, @code{16#0C#}
1639 Source files are in standard text file format. In addition, GNAT will
1640 recognize a wide variety of stream formats, in which the end of physical
1641 physical lines is marked by any of the following sequences:
1642 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1643 in accommodating files that are imported from other operating systems.
1645 @cindex End of source file
1646 @cindex Source file, end
1648 The end of a source file is normally represented by the physical end of
1649 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1650 recognized as signalling the end of the source file. Again, this is
1651 provided for compatibility with other operating systems where this
1652 code is used to represent the end of file.
1654 Each file contains a single Ada compilation unit, including any pragmas
1655 associated with the unit. For example, this means you must place a
1656 package declaration (a package @dfn{spec}) and the corresponding body in
1657 separate files. An Ada @dfn{compilation} (which is a sequence of
1658 compilation units) is represented using a sequence of files. Similarly,
1659 you will place each subunit or child unit in a separate file.
1661 @node Foreign Language Representation
1662 @section Foreign Language Representation
1665 GNAT supports the standard character sets defined in Ada 95 as well as
1666 several other non-standard character sets for use in localized versions
1667 of the compiler (@pxref{Character Set Control}).
1670 * Other 8-Bit Codes::
1671 * Wide Character Encodings::
1679 The basic character set is Latin-1. This character set is defined by ISO
1680 standard 8859, part 1. The lower half (character codes @code{16#00#}
1681 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half is
1682 used to represent additional characters. These include extended letters
1683 used by European languages, such as French accents, the vowels with umlauts
1684 used in German, and the extra letter A-ring used in Swedish.
1686 @findex Ada.Characters.Latin_1
1687 For a complete list of Latin-1 codes and their encodings, see the source
1688 file of library unit @code{Ada.Characters.Latin_1} in file
1689 @file{a-chlat1.ads}.
1690 You may use any of these extended characters freely in character or
1691 string literals. In addition, the extended characters that represent
1692 letters can be used in identifiers.
1694 @node Other 8-Bit Codes
1695 @subsection Other 8-Bit Codes
1698 GNAT also supports several other 8-bit coding schemes:
1703 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1708 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1713 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1719 Latin-4 letters (Cyrillic) allowed in identifiers, with uppercase and lowercase
1722 @item IBM PC (code page 437)
1723 @cindex code page 437
1724 This code page is the normal default for PCs in the U.S. It corresponds
1725 to the original IBM PC character set. This set has some, but not all, of
1726 the extended Latin-1 letters, but these letters do not have the same
1727 encoding as Latin-1. In this mode, these letters are allowed in
1728 identifiers with uppercase and lowercase equivalence.
1730 @item IBM PC (code page 850)
1731 @cindex code page 850
1732 This code page is a modification of 437 extended to include all the
1733 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1734 mode, all these letters are allowed in identifiers with uppercase and
1735 lowercase equivalence.
1737 @item Full Upper 8-bit
1738 Any character in the range 80-FF allowed in identifiers, and all are
1739 considered distinct. In other words, there are no uppercase and lowercase
1740 equivalences in this range. This is useful in conjunction with
1741 certain encoding schemes used for some foreign character sets (e.g.
1742 the typical method of representing Chinese characters on the PC).
1745 No upper-half characters in the range 80-FF are allowed in identifiers.
1746 This gives Ada 83 compatibility for identifier names.
1750 For precise data on the encodings permitted, and the uppercase and lowercase
1751 equivalences that are recognized, see the file @file{csets.adb} in
1752 the GNAT compiler sources. You will need to obtain a full source release
1753 of GNAT to obtain this file.
1755 @node Wide Character Encodings
1756 @subsection Wide Character Encodings
1759 GNAT allows wide character codes to appear in character and string
1760 literals, and also optionally in identifiers, by means of the following
1761 possible encoding schemes:
1766 In this encoding, a wide character is represented by the following five
1774 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1775 characters (using uppercase letters) of the wide character code. For
1776 example, ESC A345 is used to represent the wide character with code
1778 This scheme is compatible with use of the full Wide_Character set.
1780 @item Upper-Half Coding
1781 @cindex Upper-Half Coding
1782 The wide character with encoding @code{16#abcd#} where the upper bit is on (in
1783 other words, "a" is in the range 8-F) is represented as two bytes,
1784 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1785 character, but is not required to be in the upper half. This method can
1786 be also used for shift-JIS or EUC, where the internal coding matches the
1789 @item Shift JIS Coding
1790 @cindex Shift JIS Coding
1791 A wide character is represented by a two-character sequence,
1793 @code{16#cd#}, with the restrictions described for upper-half encoding as
1794 described above. The internal character code is the corresponding JIS
1795 character according to the standard algorithm for Shift-JIS
1796 conversion. Only characters defined in the JIS code set table can be
1797 used with this encoding method.
1801 A wide character is represented by a two-character sequence
1803 @code{16#cd#}, with both characters being in the upper half. The internal
1804 character code is the corresponding JIS character according to the EUC
1805 encoding algorithm. Only characters defined in the JIS code set table
1806 can be used with this encoding method.
1809 A wide character is represented using
1810 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1811 10646-1/Am.2. Depending on the character value, the representation
1812 is a one, two, or three byte sequence:
1817 16#0000#-16#007f#: 2#0xxxxxxx#
1818 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1819 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1824 where the xxx bits correspond to the left-padded bits of the
1825 16-bit character value. Note that all lower half ASCII characters
1826 are represented as ASCII bytes and all upper half characters and
1827 other wide characters are represented as sequences of upper-half
1828 (The full UTF-8 scheme allows for encoding 31-bit characters as
1829 6-byte sequences, but in this implementation, all UTF-8 sequences
1830 of four or more bytes length will be treated as illegal).
1831 @item Brackets Coding
1832 In this encoding, a wide character is represented by the following eight
1840 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1841 characters (using uppercase letters) of the wide character code. For
1842 example, ["A345"] is used to represent the wide character with code
1843 @code{16#A345#}. It is also possible (though not required) to use the
1844 Brackets coding for upper half characters. For example, the code
1845 @code{16#A3#} can be represented as @code{["A3"]}.
1847 This scheme is compatible with use of the full Wide_Character set,
1848 and is also the method used for wide character encoding in the standard
1849 ACVC (Ada Compiler Validation Capability) test suite distributions.
1854 Note: Some of these coding schemes do not permit the full use of the
1855 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
1856 use of the upper half of the Latin-1 set.
1858 @node File Naming Rules
1859 @section File Naming Rules
1862 The default file name is determined by the name of the unit that the
1863 file contains. The name is formed by taking the full expanded name of
1864 the unit and replacing the separating dots with hyphens and using
1865 ^lowercase^uppercase^ for all letters.
1867 An exception arises if the file name generated by the above rules starts
1868 with one of the characters
1875 and the second character is a
1876 minus. In this case, the character ^tilde^dollar sign^ is used in place
1877 of the minus. The reason for this special rule is to avoid clashes with
1878 the standard names for child units of the packages System, Ada,
1879 Interfaces, and GNAT, which use the prefixes
1888 The file extension is @file{.ads} for a spec and
1889 @file{.adb} for a body. The following list shows some
1890 examples of these rules.
1897 @item arith_functions.ads
1898 Arith_Functions (package spec)
1899 @item arith_functions.adb
1900 Arith_Functions (package body)
1902 Func.Spec (child package spec)
1904 Func.Spec (child package body)
1906 Sub (subunit of Main)
1907 @item ^a~bad.adb^A$BAD.ADB^
1908 A.Bad (child package body)
1912 Following these rules can result in excessively long
1913 file names if corresponding
1914 unit names are long (for example, if child units or subunits are
1915 heavily nested). An option is available to shorten such long file names
1916 (called file name "krunching"). This may be particularly useful when
1917 programs being developed with GNAT are to be used on operating systems
1918 with limited file name lengths. @xref{Using gnatkr}.
1920 Of course, no file shortening algorithm can guarantee uniqueness over
1921 all possible unit names; if file name krunching is used, it is your
1922 responsibility to ensure no name clashes occur. Alternatively you
1923 can specify the exact file names that you want used, as described
1924 in the next section. Finally, if your Ada programs are migrating from a
1925 compiler with a different naming convention, you can use the gnatchop
1926 utility to produce source files that follow the GNAT naming conventions.
1927 (For details @pxref{Renaming Files Using gnatchop}.)
1929 @node Using Other File Names
1930 @section Using Other File Names
1934 In the previous section, we have described the default rules used by
1935 GNAT to determine the file name in which a given unit resides. It is
1936 often convenient to follow these default rules, and if you follow them,
1937 the compiler knows without being explicitly told where to find all
1940 However, in some cases, particularly when a program is imported from
1941 another Ada compiler environment, it may be more convenient for the
1942 programmer to specify which file names contain which units. GNAT allows
1943 arbitrary file names to be used by means of the Source_File_Name pragma.
1944 The form of this pragma is as shown in the following examples:
1945 @cindex Source_File_Name pragma
1950 @b{pragma} Source_File_Name (My_Utilities.Stacks,
1951 Spec_File_Name => "myutilst_a.ada");
1952 @b{pragma} Source_File_name (My_Utilities.Stacks,
1953 Body_File_Name => "myutilst.ada");
1959 As shown in this example, the first argument for the pragma is the unit
1960 name (in this example a child unit). The second argument has the form
1961 of a named association. The identifier
1962 indicates whether the file name is for a spec or a body;
1963 the file name itself is given by a string literal.
1965 The source file name pragma is a configuration pragma, which means that
1966 normally it will be placed in the @file{gnat.adc}
1967 file used to hold configuration
1968 pragmas that apply to a complete compilation environment.
1969 For more details on how the @file{gnat.adc} file is created and used
1970 @pxref{Handling of Configuration Pragmas}
1971 @cindex @file{gnat.adc}
1974 GNAT allows completely arbitrary file names to be specified using the
1975 source file name pragma. However, if the file name specified has an
1976 extension other than @file{.ads} or @file{.adb} it is necessary to use a special
1977 syntax when compiling the file. The name in this case must be preceded
1978 by the special sequence @code{-x} followed by a space and the name of the
1979 language, here @code{ada}, as in:
1982 $ gcc -c -x ada peculiar_file_name.sim
1987 @code{gnatmake} handles non-standard file names in the usual manner (the
1988 non-standard file name for the main program is simply used as the
1989 argument to gnatmake). Note that if the extension is also non-standard,
1990 then it must be included in the gnatmake command, it may not be omitted.
1992 @node Alternative File Naming Schemes
1993 @section Alternative File Naming Schemes
1994 @cindex File naming schemes, alternative
1997 In the previous section, we described the use of the @code{Source_File_Name}
1998 pragma to allow arbitrary names to be assigned to individual source files.
1999 However, this approach requires one pragma for each file, and especially in
2000 large systems can result in very long @file{gnat.adc} files, and also create
2001 a maintenance problem.
2003 GNAT also provides a facility for specifying systematic file naming schemes
2004 other than the standard default naming scheme previously described. An
2005 alternative scheme for naming is specified by the use of
2006 @code{Source_File_Name} pragmas having the following format:
2007 @cindex Source_File_Name pragma
2010 pragma Source_File_Name (
2011 Spec_File_Name => FILE_NAME_PATTERN
2012 [,Casing => CASING_SPEC]
2013 [,Dot_Replacement => STRING_LITERAL]);
2015 pragma Source_File_Name (
2016 Body_File_Name => FILE_NAME_PATTERN
2017 [,Casing => CASING_SPEC]
2018 [,Dot_Replacement => STRING_LITERAL]);
2020 pragma Source_File_Name (
2021 Subunit_File_Name => FILE_NAME_PATTERN
2022 [,Casing => CASING_SPEC]
2023 [,Dot_Replacement => STRING_LITERAL]);
2025 FILE_NAME_PATTERN ::= STRING_LITERAL
2026 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2031 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2032 It contains a single asterisk character, and the unit name is substituted
2033 systematically for this asterisk. The optional parameter
2034 @code{Casing} indicates
2035 whether the unit name is to be all upper-case letters, all lower-case letters,
2036 or mixed-case. If no
2037 @code{Casing} parameter is used, then the default is all
2038 ^lower-case^upper-case^.
2040 The optional @code{Dot_Replacement} string is used to replace any periods
2041 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2042 argument is used then separating dots appear unchanged in the resulting
2044 Although the above syntax indicates that the
2045 @code{Casing} argument must appear
2046 before the @code{Dot_Replacement} argument, but it
2047 is also permissible to write these arguments in the opposite order.
2049 As indicated, it is possible to specify different naming schemes for
2050 bodies, specs, and subunits. Quite often the rule for subunits is the
2051 same as the rule for bodies, in which case, there is no need to give
2052 a separate @code{Subunit_File_Name} rule, and in this case the
2053 @code{Body_File_name} rule is used for subunits as well.
2055 The separate rule for subunits can also be used to implement the rather
2056 unusual case of a compilation environment (e.g. a single directory) which
2057 contains a subunit and a child unit with the same unit name. Although
2058 both units cannot appear in the same partition, the Ada Reference Manual
2059 allows (but does not require) the possibility of the two units coexisting
2060 in the same environment.
2062 The file name translation works in the following steps:
2067 If there is a specific @code{Source_File_Name} pragma for the given unit,
2068 then this is always used, and any general pattern rules are ignored.
2071 If there is a pattern type @code{Source_File_Name} pragma that applies to
2072 the unit, then the resulting file name will be used if the file exists. If
2073 more than one pattern matches, the latest one will be tried first, and the
2074 first attempt resulting in a reference to a file that exists will be used.
2077 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2078 for which the corresponding file exists, then the standard GNAT default
2079 naming rules are used.
2084 As an example of the use of this mechanism, consider a commonly used scheme
2085 in which file names are all lower case, with separating periods copied
2086 unchanged to the resulting file name, and specs end with ".1.ada", and
2087 bodies end with ".2.ada". GNAT will follow this scheme if the following
2091 pragma Source_File_Name
2092 (Spec_File_Name => "*.1.ada");
2093 pragma Source_File_Name
2094 (Body_File_Name => "*.2.ada");
2098 The default GNAT scheme is actually implemented by providing the following
2099 default pragmas internally:
2102 pragma Source_File_Name
2103 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2104 pragma Source_File_Name
2105 (Body_File_Name => "*.adb", Dot_Replacement => "-");
2109 Our final example implements a scheme typically used with one of the
2110 Ada 83 compilers, where the separator character for subunits was "__"
2111 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2112 by adding @file{.ADA}, and subunits by
2113 adding @file{.SEP}. All file names were
2114 upper case. Child units were not present of course since this was an
2115 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2116 the same double underscore separator for child units.
2119 pragma Source_File_Name
2120 (Spec_File_Name => "*_.ADA",
2121 Dot_Replacement => "__",
2122 Casing = Uppercase);
2123 pragma Source_File_Name
2124 (Body_File_Name => "*.ADA",
2125 Dot_Replacement => "__",
2126 Casing = Uppercase);
2127 pragma Source_File_Name
2128 (Subunit_File_Name => "*.SEP",
2129 Dot_Replacement => "__",
2130 Casing = Uppercase);
2133 @node Generating Object Files
2134 @section Generating Object Files
2137 An Ada program consists of a set of source files, and the first step in
2138 compiling the program is to generate the corresponding object files.
2139 These are generated by compiling a subset of these source files.
2140 The files you need to compile are the following:
2144 If a package spec has no body, compile the package spec to produce the
2145 object file for the package.
2148 If a package has both a spec and a body, compile the body to produce the
2149 object file for the package. The source file for the package spec need
2150 not be compiled in this case because there is only one object file, which
2151 contains the code for both the spec and body of the package.
2154 For a subprogram, compile the subprogram body to produce the object file
2155 for the subprogram. The spec, if one is present, is as usual in a
2156 separate file, and need not be compiled.
2160 In the case of subunits, only compile the parent unit. A single object
2161 file is generated for the entire subunit tree, which includes all the
2165 Compile child units independently of their parent units
2166 (though, of course, the spec of all the ancestor unit must be present in order
2167 to compile a child unit).
2171 Compile generic units in the same manner as any other units. The object
2172 files in this case are small dummy files that contain at most the
2173 flag used for elaboration checking. This is because GNAT always handles generic
2174 instantiation by means of macro expansion. However, it is still necessary to
2175 compile generic units, for dependency checking and elaboration purposes.
2179 The preceding rules describe the set of files that must be compiled to
2180 generate the object files for a program. Each object file has the same
2181 name as the corresponding source file, except that the extension is
2184 You may wish to compile other files for the purpose of checking their
2185 syntactic and semantic correctness. For example, in the case where a
2186 package has a separate spec and body, you would not normally compile the
2187 spec. However, it is convenient in practice to compile the spec to make
2188 sure it is error-free before compiling clients of this spec, because such
2189 compilations will fail if there is an error in the spec.
2191 GNAT provides an option for compiling such files purely for the
2192 purposes of checking correctness; such compilations are not required as
2193 part of the process of building a program. To compile a file in this
2194 checking mode, use the @option{-gnatc} switch.
2196 @node Source Dependencies
2197 @section Source Dependencies
2200 A given object file clearly depends on the source file which is compiled
2201 to produce it. Here we are using @dfn{depends} in the sense of a typical
2202 @code{make} utility; in other words, an object file depends on a source
2203 file if changes to the source file require the object file to be
2205 In addition to this basic dependency, a given object may depend on
2206 additional source files as follows:
2210 If a file being compiled @code{with}'s a unit @var{X}, the object file
2211 depends on the file containing the spec of unit @var{X}. This includes
2212 files that are @code{with}'ed implicitly either because they are parents
2213 of @code{with}'ed child units or they are run-time units required by the
2214 language constructs used in a particular unit.
2217 If a file being compiled instantiates a library level generic unit, the
2218 object file depends on both the spec and body files for this generic
2222 If a file being compiled instantiates a generic unit defined within a
2223 package, the object file depends on the body file for the package as
2224 well as the spec file.
2228 @cindex @option{-gnatn} switch
2229 If a file being compiled contains a call to a subprogram for which
2230 pragma @code{Inline} applies and inlining is activated with the
2231 @option{-gnatn} switch, the object file depends on the file containing the
2232 body of this subprogram as well as on the file containing the spec. Note
2233 that for inlining to actually occur as a result of the use of this switch,
2234 it is necessary to compile in optimizing mode.
2236 @cindex @option{-gnatN} switch
2237 The use of @option{-gnatN} activates a more extensive inlining optimization
2238 that is performed by the front end of the compiler. This inlining does
2239 not require that the code generation be optimized. Like @option{-gnatn},
2240 the use of this switch generates additional dependencies.
2243 If an object file O depends on the proper body of a subunit through inlining
2244 or instantiation, it depends on the parent unit of the subunit. This means that
2245 any modification of the parent unit or one of its subunits affects the
2249 The object file for a parent unit depends on all its subunit body files.
2252 The previous two rules meant that for purposes of computing dependencies and
2253 recompilation, a body and all its subunits are treated as an indivisible whole.
2256 These rules are applied transitively: if unit @code{A} @code{with}'s
2257 unit @code{B}, whose elaboration calls an inlined procedure in package
2258 @code{C}, the object file for unit @code{A} will depend on the body of
2259 @code{C}, in file @file{c.adb}.
2261 The set of dependent files described by these rules includes all the
2262 files on which the unit is semantically dependent, as described in the
2263 Ada 95 Language Reference Manual. However, it is a superset of what the
2264 ARM describes, because it includes generic, inline, and subunit dependencies.
2266 An object file must be recreated by recompiling the corresponding source
2267 file if any of the source files on which it depends are modified. For
2268 example, if the @code{make} utility is used to control compilation,
2269 the rule for an Ada object file must mention all the source files on
2270 which the object file depends, according to the above definition.
2271 The determination of the necessary
2272 recompilations is done automatically when one uses @code{gnatmake}.
2275 @node The Ada Library Information Files
2276 @section The Ada Library Information Files
2277 @cindex Ada Library Information files
2278 @cindex @file{ali} files
2281 Each compilation actually generates two output files. The first of these
2282 is the normal object file that has a @file{.o} extension. The second is a
2283 text file containing full dependency information. It has the same
2284 name as the source file, but an @file{.ali} extension.
2285 This file is known as the Ada Library Information (@file{ali}) file.
2286 The following information is contained in the @file{ali} file.
2290 Version information (indicates which version of GNAT was used to compile
2291 the unit(s) in question)
2294 Main program information (including priority and time slice settings,
2295 as well as the wide character encoding used during compilation).
2298 List of arguments used in the @code{gcc} command for the compilation
2301 Attributes of the unit, including configuration pragmas used, an indication
2302 of whether the compilation was successful, exception model used etc.
2305 A list of relevant restrictions applying to the unit (used for consistency)
2309 Categorization information (e.g. use of pragma @code{Pure}).
2312 Information on all @code{with}'ed units, including presence of
2313 @code{Elaborate} or @code{Elaborate_All} pragmas.
2316 Information from any @code{Linker_Options} pragmas used in the unit
2319 Information on the use of @code{Body_Version} or @code{Version}
2320 attributes in the unit.
2323 Dependency information. This is a list of files, together with
2324 time stamp and checksum information. These are files on which
2325 the unit depends in the sense that recompilation is required
2326 if any of these units are modified.
2329 Cross-reference data. Contains information on all entities referenced
2330 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2331 provide cross-reference information.
2336 For a full detailed description of the format of the @file{ali} file,
2337 see the source of the body of unit @code{Lib.Writ}, contained in file
2338 @file{lib-writ.adb} in the GNAT compiler sources.
2340 @node Binding an Ada Program
2341 @section Binding an Ada Program
2344 When using languages such as C and C++, once the source files have been
2345 compiled the only remaining step in building an executable program
2346 is linking the object modules together. This means that it is possible to
2347 link an inconsistent version of a program, in which two units have
2348 included different versions of the same header.
2350 The rules of Ada do not permit such an inconsistent program to be built.
2351 For example, if two clients have different versions of the same package,
2352 it is illegal to build a program containing these two clients.
2353 These rules are enforced by the GNAT binder, which also determines an
2354 elaboration order consistent with the Ada rules.
2356 The GNAT binder is run after all the object files for a program have
2357 been created. It is given the name of the main program unit, and from
2358 this it determines the set of units required by the program, by reading the
2359 corresponding ALI files. It generates error messages if the program is
2360 inconsistent or if no valid order of elaboration exists.
2362 If no errors are detected, the binder produces a main program, in Ada by
2363 default, that contains calls to the elaboration procedures of those
2364 compilation unit that require them, followed by
2365 a call to the main program. This Ada program is compiled to generate the
2366 object file for the main program. The name of
2367 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2368 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2371 Finally, the linker is used to build the resulting executable program,
2372 using the object from the main program from the bind step as well as the
2373 object files for the Ada units of the program.
2375 @node Mixed Language Programming
2376 @section Mixed Language Programming
2377 @cindex Mixed Language Programming
2380 * Interfacing to C::
2381 * Calling Conventions::
2384 @node Interfacing to C
2385 @subsection Interfacing to C
2387 There are two ways to
2388 build a program that contains some Ada files and some other language
2389 files depending on whether the main program is in Ada or not.
2390 If the main program is in Ada, you should proceed as follows:
2394 Compile the other language files to generate object files. For instance:
2401 Compile the Ada units to produce a set of object files and ALI
2402 files. For instance:
2404 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2408 Run the Ada binder on the Ada main program. For instance:
2410 gnatbind my_main.ali
2414 Link the Ada main program, the Ada objects and the other language
2415 objects. For instance:
2417 gnatlink my_main.ali file1.o file2.o
2421 The three last steps can be grouped in a single command:
2423 gnatmake my_main.adb -largs file1.o file2.o
2426 @cindex Binder output file
2428 If the main program is in some language other than Ada, you may
2429 have more than one entry point in the Ada subsystem. You must use a
2430 special option of the binder to generate callable routines to initialize
2431 and finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2432 Calls to the initialization and finalization routines must be inserted in
2433 the main program, or some other appropriate point in the code. The call to
2434 initialize the Ada units must occur before the first Ada subprogram is
2435 called, and the call to finalize the Ada units must occur after the last
2436 Ada subprogram returns. You use the same procedure for building the
2437 program as described previously. In this case, however, the binder
2438 only places the initialization and finalization subprograms into file
2439 @file{b~@var{xxx}.adb} instead of the main program.
2440 So, if the main program is not in Ada, you should proceed as follows:
2444 Compile the other language files to generate object files. For instance:
2451 Compile the Ada units to produce a set of object files and ALI
2452 files. For instance:
2454 gnatmake ^-c^/ACTIONS=COMPILE^ entry_point1.adb
2455 gnatmake ^-c^/ACTIONS=COMPILE^ entry_point2.adb
2459 Run the Ada binder on the Ada main program. For instance:
2461 gnatbind ^-n^/NOMAIN^ entry_point1.ali entry_point2.ali
2465 Link the Ada main program, the Ada objects and the other language
2466 objects. You only need to give the last entry point here. For instance:
2468 gnatlink entry_point2.ali file1.o file2.o
2472 @node Calling Conventions
2473 @subsection Calling Conventions
2474 @cindex Foreign Languages
2475 @cindex Calling Conventions
2476 GNAT follows standard calling sequence conventions and will thus interface
2477 to any other language that also follows these conventions. The following
2478 Convention identifiers are recognized by GNAT:
2481 @cindex Interfacing to Ada
2482 @cindex Other Ada compilers
2483 @cindex Convention Ada
2485 Ada. This indicates that the standard Ada calling sequence will be
2486 used and all Ada data items may be passed without any limitations in the
2487 case where GNAT is used to generate both the caller and callee. It is also
2488 possible to mix GNAT generated code and code generated by another Ada
2489 compiler. In this case, the data types should be restricted to simple
2490 cases, including primitive types. Whether complex data types can be passed
2491 depends on the situation. Probably it is safe to pass simple arrays, such
2492 as arrays of integers or floats. Records may or may not work, depending
2493 on whether both compilers lay them out identically. Complex structures
2494 involving variant records, access parameters, tasks, or protected types,
2495 are unlikely to be able to be passed.
2497 Note that in the case of GNAT running
2498 on a platform that supports DEC Ada 83, a higher degree of compatibility
2499 can be guaranteed, and in particular records are layed out in an identical
2500 manner in the two compilers. Note also that if output from two different
2501 compilers is mixed, the program is responsible for dealing with elaboration
2502 issues. Probably the safest approach is to write the main program in the
2503 version of Ada other than GNAT, so that it takes care of its own elaboration
2504 requirements, and then call the GNAT-generated adainit procedure to ensure
2505 elaboration of the GNAT components. Consult the documentation of the other
2506 Ada compiler for further details on elaboration.
2508 However, it is not possible to mix the tasking run time of GNAT and
2509 DEC Ada 83, All the tasking operations must either be entirely within
2510 GNAT compiled sections of the program, or entirely within DEC Ada 83
2511 compiled sections of the program.
2513 @cindex Interfacing to Assembly
2514 @cindex Convention Assembler
2516 Assembler. Specifies assembler as the convention. In practice this has the
2517 same effect as convention Ada (but is not equivalent in the sense of being
2518 considered the same convention).
2520 @cindex Convention Asm
2523 Asm. Equivalent to Assembler.
2525 @cindex Convention Asm
2528 Asm. Equivalent to Assembly.
2530 @cindex Interfacing to COBOL
2531 @cindex Convention COBOL
2534 COBOL. Data will be passed according to the conventions described
2535 in section B.4 of the Ada 95 Reference Manual.
2538 @cindex Interfacing to C
2539 @cindex Convention C
2541 C. Data will be passed according to the conventions described
2542 in section B.3 of the Ada 95 Reference Manual.
2544 @cindex Convention Default
2547 Default. Equivalent to C.
2549 @cindex Convention External
2552 External. Equivalent to C.
2555 @cindex Interfacing to C++
2556 @cindex Convention C++
2558 CPP. This stands for C++. For most purposes this is identical to C.
2559 See the separate description of the specialized GNAT pragmas relating to
2560 C++ interfacing for further details.
2563 @cindex Interfacing to Fortran
2564 @cindex Convention Fortran
2566 Fortran. Data will be passed according to the conventions described
2567 in section B.5 of the Ada 95 Reference Manual.
2570 Intrinsic. This applies to an intrinsic operation, as defined in the Ada 95
2571 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
2572 this means that the body of the subprogram is provided by the compiler itself,
2573 usually by means of an efficient code sequence, and that the user does not
2574 supply an explicit body for it. In an application program, the pragma can only
2575 be applied to the following two sets of names, which the GNAT compiler
2579 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
2580 Arithmetic. The corresponding subprogram declaration must have
2581 two formal parameters. The
2582 first one must be a signed integer type or a modular type with a binary
2583 modulus, and the second parameter must be of type Natural.
2584 The return type must be the same as the type of the first argument. The size
2585 of this type can only be 8, 16, 32, or 64.
2586 @item binary arithmetic operators: "+", "-", "*", "/"
2587 The corresponding operator declaration must have parameters and result type
2588 that have the same root numeric type (for example, all three are long_float
2589 types). This simplifies the definition of operations that use type checking
2590 to perform dimensional checks:
2592 type Distance is new Long_Float;
2593 type Time is new Long_Float;
2594 type Velocity is new Long_Float;
2595 function "/" (D : Distance; T : Time)
2597 pragma Import (Intrinsic, "/");
2600 This common idiom is often programmed with a generic definition and an explicit
2601 body. The pragma makes it simpler to introduce such declarations. It incurs
2602 no overhead in compilation time or code size, because it is implemented as a
2603 single machine instruction.
2608 @cindex Convention Stdcall
2610 Stdcall. This is relevant only to NT/Win95 implementations of GNAT,
2611 and specifies that the Stdcall calling sequence will be used, as defined
2615 @cindex Convention DLL
2617 DLL. This is equivalent to Stdcall.
2620 @cindex Convention Win32
2622 Win32. This is equivalent to Stdcall.
2625 @cindex Convention Stubbed
2627 Stubbed. This is a special convention that indicates that the compiler
2628 should provide a stub body that raises @code{Program_Error}.
2632 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2633 that can be used to parametrize conventions and allow additional synonyms
2634 to be specified. For example if you have legacy code in which the convention
2635 identifier Fortran77 was used for Fortran, you can use the configuration
2639 pragma Convention_Identifier (Fortran77, Fortran);
2643 And from now on the identifier Fortran77 may be used as a convention
2644 identifier (for example in an @code{Import} pragma) with the same
2647 @node Building Mixed Ada & C++ Programs
2648 @section Building Mixed Ada & C++ Programs
2651 Building a mixed application containing both Ada and C++ code may be a
2652 challenge for the unaware programmer. As a matter of fact, this
2653 interfacing has not been standardized in the Ada 95 reference manual due
2654 to the immaturity and lack of standard of C++ at the time. This
2655 section gives a few hints that should make this task easier. In
2656 particular the first section addresses the differences with
2657 interfacing with C. The second section looks into the delicate problem
2658 of linking the complete application from its Ada and C++ parts. The last
2659 section give some hints on how the GNAT run time can be adapted in order
2660 to allow inter-language dispatching with a new C++ compiler.
2663 * Interfacing to C++::
2664 * Linking a Mixed C++ & Ada Program::
2665 * A Simple Example::
2666 * Adapting the Run Time to a New C++ Compiler::
2669 @node Interfacing to C++
2670 @subsection Interfacing to C++
2673 GNAT supports interfacing with C++ compilers generating code that is
2674 compatible with the standard Application Binary Interface of the given
2678 Interfacing can be done at 3 levels: simple data, subprograms and
2679 classes. In the first 2 cases, GNAT offer a specific @var{Convention
2680 CPP} that behaves exactly like @var{Convention C}. Usually C++ mangle
2681 names of subprograms and currently GNAT does not provide any help to
2682 solve the demangling problem. This problem can be addressed in 2 ways:
2685 by modifying the C++ code in order to force a C convention using
2686 the @var{extern "C"} syntax.
2689 by figuring out the mangled name and use it as the Link_Name argument of
2694 Interfacing at the class level can be achieved by using the GNAT specific
2695 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
2696 Reference Manual for additional information.
2698 @node Linking a Mixed C++ & Ada Program
2699 @subsection Linking a Mixed C++ & Ada Program
2702 Usually the linker of the C++ development system must be used to link
2703 mixed applications because most C++ systems will resolve elaboration
2704 issues (such as calling constructors on global class instances)
2705 transparently during the link phase. GNAT has been adapted to ease the
2706 use of a foreign linker for the last phase. Three cases can be
2711 Using GNAT and G++ (GNU C++ compiler) from the same GCC
2712 installation. The c++ linker can simply be called by using the c++
2713 specific driver called @code{c++}. Note that this setup is not
2714 very common because it may request recompiling the whole GCC
2715 tree from sources and it does not allow to upgrade easily to a new
2716 version of one compiler for one of the two languages without taking the
2717 risk of destabilizing the other.
2722 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
2726 Using GNAT and G++ from 2 different GCC installations. If both compilers
2727 are on the PATH, the same method can be used. It is important to be
2728 aware that environment variables such as C_INCLUDE_PATH,
2729 GCC_EXEC_PREFIX, BINUTILS_ROOT or GCC_ROOT will affect both compilers at
2730 the same time and thus may make one of the 2 compilers operate
2731 improperly if they are set for the other. In particular it is important
2732 that the link command has access to the proper gcc library @file{libgcc.a},
2733 that is to say the one that is part of the C++ compiler
2734 installation. The implicit link command as suggested in the gnatmake
2735 command from the former example can be replaced by an explicit link
2736 command with full verbosity in order to verify which library is used:
2739 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2741 If there is a problem due to interfering environment variables, it can
2742 be workaround by using an intermediate script. The following example
2743 shows the proper script to use when GNAT has not been installed at its
2744 default location and g++ has been installed at its default location:
2747 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2756 Using a non GNU C++ compiler. The same set of command as previously
2757 described can be used to insure that the c++ linker is
2758 used. Nonetheless, you need to add the path to libgcc explicitely, since some
2759 libraries needed by GNAT are located in this directory:
2763 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2766 CC $* `gcc -print-libgcc-file-name`
2770 Where CC is the name of the non GNU C++ compiler.
2774 @node A Simple Example
2775 @subsection A Simple Example
2777 The following example, provided as part of the GNAT examples, show how
2778 to achieve procedural interfacing between Ada and C++ in both
2779 directions. The C++ class A has 2 methods. The first method is exported
2780 to Ada by the means of an extern C wrapper function. The second method
2781 calls an Ada subprogram. On the Ada side, The C++ calls is modelized by
2782 a limited record with a layout comparable to the C++ class. The Ada
2783 subprogram, in turn, calls the c++ method. So from the C++ main program
2784 the code goes back and forth between the 2 languages.
2787 Here are the compilation commands
2789 for native configurations:
2791 $ gnatmake -c simple_cpp_interface
2794 $ gnatbind -n simple_cpp_interface
2795 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
2796 -lstdc++ ex7.o cpp_main.o
2800 for a GNAT VxWorks/PowerPC configuration:
2802 $ powerpc-wrs-vxworks-gnatmake -c simple_cpp_interface
2803 $ powerpc-wrs-vxworks-gnatbind -n simple_cpp_interface
2804 $ gnatlink simple_cpp_interface -o ada_part
2805 $ c++ppc -c -DCPU=PPC604 -I/usr/windppc/target/h cpp_main.C
2806 $ c++ppc -c -DCPU=PPC604 -I/usr/windppc/target/h ex7.C
2807 $ ldppc -r -o my_main my_main.o ex7.o ada_part
2811 Here are the corresponding sources:
2819 void adainit (void);
2820 void adafinal (void);
2821 void method1 (A *t);
2843 class A : public Origin @{
2845 void method1 (void);
2846 virtual void method2 (int v);
2856 extern "C" @{ void ada_method2 (A *t, int v);@}
2858 void A::method1 (void)
2861 printf ("in A::method1, a_value = %d \n",a_value);
2865 void A::method2 (int v)
2867 ada_method2 (this, v);
2868 printf ("in A::method2, a_value = %d \n",a_value);
2875 printf ("in A::A, a_value = %d \n",a_value);
2879 @b{package} @b{body} Simple_Cpp_Interface @b{is}
2881 @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
2885 @b{end} Ada_Method2;
2887 @b{end} Simple_Cpp_Interface;
2889 @b{package} Simple_Cpp_Interface @b{is}
2890 @b{type} A @b{is} @b{limited}
2895 @b{pragma} Convention (C, A);
2897 @b{procedure} Method1 (This : @b{in} @b{out} A);
2898 @b{pragma} Import (C, Method1);
2900 @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
2901 @b{pragma} Export (C, Ada_Method2);
2903 @b{end} Simple_Cpp_Interface;
2906 @node Adapting the Run Time to a New C++ Compiler
2907 @subsection Adapting the Run Time to a New C++ Compiler
2909 GNAT offers the capability to derive Ada 95 tagged types directly from
2910 preexisting C++ classes and . See "Interfacing with C++" in the GNAT
2911 reference manual. The mechanism used by GNAT for achieving such a goal
2912 has been made user configurable through a GNAT library unit
2913 @code{Interfaces.CPP}. The default version of this file is adapted to
2914 the GNU c++ compiler. Internal knowledge of the virtual
2915 table layout used by the new C++ compiler is needed to configure
2916 properly this unit. The Interface of this unit is known by the compiler
2917 and cannot be changed except for the value of the constants defining the
2918 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
2919 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
2920 of this unit for more details.
2922 @node Comparison between GNAT and C/C++ Compilation Models
2923 @section Comparison between GNAT and C/C++ Compilation Models
2926 The GNAT model of compilation is close to the C and C++ models. You can
2927 think of Ada specs as corresponding to header files in C. As in C, you
2928 don't need to compile specs; they are compiled when they are used. The
2929 Ada @code{with} is similar in effect to the @code{#include} of a C
2932 One notable difference is that, in Ada, you may compile specs separately
2933 to check them for semantic and syntactic accuracy. This is not always
2934 possible with C headers because they are fragments of programs that have
2935 less specific syntactic or semantic rules.
2937 The other major difference is the requirement for running the binder,
2938 which performs two important functions. First, it checks for
2939 consistency. In C or C++, the only defense against assembling
2940 inconsistent programs lies outside the compiler, in a makefile, for
2941 example. The binder satisfies the Ada requirement that it be impossible
2942 to construct an inconsistent program when the compiler is used in normal
2945 @cindex Elaboration order control
2946 The other important function of the binder is to deal with elaboration
2947 issues. There are also elaboration issues in C++ that are handled
2948 automatically. This automatic handling has the advantage of being
2949 simpler to use, but the C++ programmer has no control over elaboration.
2950 Where @code{gnatbind} might complain there was no valid order of
2951 elaboration, a C++ compiler would simply construct a program that
2952 malfunctioned at run time.
2954 @node Comparison between GNAT and Conventional Ada Library Models
2955 @section Comparison between GNAT and Conventional Ada Library Models
2958 This section is intended to be useful to Ada programmers who have
2959 previously used an Ada compiler implementing the traditional Ada library
2960 model, as described in the Ada 95 Language Reference Manual. If you
2961 have not used such a system, please go on to the next section.
2963 @cindex GNAT library
2964 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
2965 source files themselves acts as the library. Compiling Ada programs does
2966 not generate any centralized information, but rather an object file and
2967 a ALI file, which are of interest only to the binder and linker.
2968 In a traditional system, the compiler reads information not only from
2969 the source file being compiled, but also from the centralized library.
2970 This means that the effect of a compilation depends on what has been
2971 previously compiled. In particular:
2975 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2976 to the version of the unit most recently compiled into the library.
2979 Inlining is effective only if the necessary body has already been
2980 compiled into the library.
2983 Compiling a unit may obsolete other units in the library.
2987 In GNAT, compiling one unit never affects the compilation of any other
2988 units because the compiler reads only source files. Only changes to source
2989 files can affect the results of a compilation. In particular:
2993 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2994 to the source version of the unit that is currently accessible to the
2999 Inlining requires the appropriate source files for the package or
3000 subprogram bodies to be available to the compiler. Inlining is always
3001 effective, independent of the order in which units are complied.
3004 Compiling a unit never affects any other compilations. The editing of
3005 sources may cause previous compilations to be out of date if they
3006 depended on the source file being modified.
3010 The most important result of these differences is that order of compilation
3011 is never significant in GNAT. There is no situation in which one is
3012 required to do one compilation before another. What shows up as order of
3013 compilation requirements in the traditional Ada library becomes, in
3014 GNAT, simple source dependencies; in other words, there is only a set
3015 of rules saying what source files must be present when a file is
3018 @node Compiling Using gcc
3019 @chapter Compiling Using @code{gcc}
3022 This chapter discusses how to compile Ada programs using the @code{gcc}
3023 command. It also describes the set of switches
3024 that can be used to control the behavior of the compiler.
3026 * Compiling Programs::
3027 * Switches for gcc::
3028 * Search Paths and the Run-Time Library (RTL)::
3029 * Order of Compilation Issues::
3033 @node Compiling Programs
3034 @section Compiling Programs
3037 The first step in creating an executable program is to compile the units
3038 of the program using the @code{gcc} command. You must compile the
3043 the body file (@file{.adb}) for a library level subprogram or generic
3047 the spec file (@file{.ads}) for a library level package or generic
3048 package that has no body
3051 the body file (@file{.adb}) for a library level package
3052 or generic package that has a body
3057 You need @emph{not} compile the following files
3062 the spec of a library unit which has a body
3069 because they are compiled as part of compiling related units. GNAT
3071 when the corresponding body is compiled, and subunits when the parent is
3073 @cindex No code generated
3074 If you attempt to compile any of these files, you will get one of the
3075 following error messages (where fff is the name of the file you compiled):
3078 No code generated for file @var{fff} (@var{package spec})
3079 No code generated for file @var{fff} (@var{subunit})
3083 The basic command for compiling a file containing an Ada unit is
3086 $ gcc -c [@var{switches}] @file{file name}
3090 where @var{file name} is the name of the Ada file (usually
3092 @file{.ads} for a spec or @file{.adb} for a body).
3095 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
3097 The result of a successful compilation is an object file, which has the
3098 same name as the source file but an extension of @file{.o} and an Ada
3099 Library Information (ALI) file, which also has the same name as the
3100 source file, but with @file{.ali} as the extension. GNAT creates these
3101 two output files in the current directory, but you may specify a source
3102 file in any directory using an absolute or relative path specification
3103 containing the directory information.
3106 @code{gcc} is actually a driver program that looks at the extensions of
3107 the file arguments and loads the appropriate compiler. For example, the
3108 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3109 These programs are in directories known to the driver program (in some
3110 configurations via environment variables you set), but need not be in
3111 your path. The @code{gcc} driver also calls the assembler and any other
3112 utilities needed to complete the generation of the required object
3115 It is possible to supply several file names on the same @code{gcc}
3116 command. This causes @code{gcc} to call the appropriate compiler for
3117 each file. For example, the following command lists three separate
3118 files to be compiled:
3121 $ gcc -c x.adb y.adb z.c
3125 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3126 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3127 The compiler generates three object files @file{x.o}, @file{y.o} and
3128 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3129 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3132 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3135 @node Switches for gcc
3136 @section Switches for @code{gcc}
3139 The @code{gcc} command accepts switches that control the
3140 compilation process. These switches are fully described in this section.
3141 First we briefly list all the switches, in alphabetical order, then we
3142 describe the switches in more detail in functionally grouped sections.
3145 * Output and Error Message Control::
3146 * Debugging and Assertion Control::
3148 * Stack Overflow Checking::
3149 * Run-Time Control::
3150 * Validity Checking::
3152 * Using gcc for Syntax Checking::
3153 * Using gcc for Semantic Checking::
3154 * Compiling Ada 83 Programs::
3155 * Character Set Control::
3156 * File Naming Control::
3157 * Subprogram Inlining Control::
3158 * Auxiliary Output Control::
3159 * Debugging Control::
3160 * Units to Sources Mapping Files::
3165 @cindex @code{-b} (@code{gcc})
3166 @item -b @var{target}
3167 Compile your program to run on @var{target}, which is the name of a
3168 system configuration. You must have a GNAT cross-compiler built if
3169 @var{target} is not the same as your host system.
3172 @cindex @code{-B} (@code{gcc})
3173 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3174 from @var{dir} instead of the default location. Only use this switch
3175 when multiple versions of the GNAT compiler are available. See the
3176 @code{gcc} manual page for further details. You would normally use the
3177 @code{-b} or @code{-V} switch instead.
3180 @cindex @code{-c} (@code{gcc})
3181 Compile. Always use this switch when compiling Ada programs.
3183 Note: for some other languages when using @code{gcc}, notably in
3184 the case of C and C++, it is possible to use
3185 use @code{gcc} without a @code{-c} switch to
3186 compile and link in one step. In the case of GNAT, you
3187 cannot use this approach, because the binder must be run
3188 and @code{gcc} cannot be used to run the GNAT binder.
3192 @cindex @code{^-g^/DEBUG^} (@code{gcc})
3193 Generate debugging information. This information is stored in the object
3194 file and copied from there to the final executable file by the linker,
3195 where it can be read by the debugger. You must use the
3196 @code{^-g^/DEBUG^} switch if you plan on using the debugger.
3198 @item ^-I^/SEARCH=^@var{dir}
3199 @cindex @code{^-I^/SEARCH^} (@code{gcc})
3201 Direct GNAT to search the @var{dir} directory for source files needed by
3202 the current compilation
3203 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3205 @item ^-I-^/NOCURRENT_DIRECTORY^
3206 @cindex @code{^-I-^/NOCURRENT_DIRECTORY^} (@code{gcc})
3208 Except for the source file named in the command line, do not look for source files
3209 in the directory containing the source file named in the command line
3210 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3214 @cindex @code{-o} (@code{gcc})
3215 This switch is used in @code{gcc} to redirect the generated object file
3216 and its associated ALI file. Beware of this switch with GNAT, because it may
3217 cause the object file and ALI file to have different names which in turn
3218 may confuse the binder and the linker.
3223 @cindex @code{-O} (@code{gcc})
3224 @var{n} controls the optimization level.
3228 No optimization, the default setting if no @code{-O} appears
3231 Normal optimization, the default if you specify @code{-O} without
3235 Extensive optimization
3238 Extensive optimization with automatic inlining. This applies only to
3239 inlining within a unit. For details on control of inter-unit inlining
3240 see @xref{Subprogram Inlining Control}.
3245 @item /NOOPTIMIZE (default)
3246 @itemx /OPTIMIZE[=(keyword[,...])]
3247 Selects the level of optimization for your program. The supported
3248 keywords are as follows:
3251 Perform most optimizations, including those that
3255 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
3258 Perform some optimizations, but omit ones that are costly.
3261 Same as @code{SOME}.
3264 Full optimization, and also attempt automatic inlining of small
3265 subprograms within a unit (@pxref{Inlining of Subprograms}).
3268 Try to unroll loops. This keyword may be specified together with
3269 any keyword above other than @code{NONE}. Loop unrolling
3270 usually, but not always, improves the performance of programs.
3274 @item --RTS=@var{rts-path}
3275 @cindex @code{--RTS} (@code{gcc})
3276 Specifies the default location of the runtime library. Same meaning as the
3277 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
3280 @cindex @code{^-S^/ASM^} (@code{gcc})
3281 ^Used in place of @code{-c} to^Used to^
3282 cause the assembler source file to be
3283 generated, using @file{^.s^.S^} as the extension,
3284 instead of the object file.
3285 This may be useful if you need to examine the generated assembly code.
3288 @cindex @code{^-v^/VERBOSE^} (@code{gcc})
3289 Show commands generated by the @code{gcc} driver. Normally used only for
3290 debugging purposes or if you need to be sure what version of the
3291 compiler you are executing.
3295 @cindex @code{-V} (@code{gcc})
3296 Execute @var{ver} version of the compiler. This is the @code{gcc}
3297 version, not the GNAT version.
3301 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3305 Avoid processing @file{gnat.adc}. If a gnat.adc file is present, it will be ignored.
3308 Generate brief messages to @file{stderr} even if verbose mode set.
3311 Check syntax and semantics only (no code generation attempted).
3314 Compress debug information and external symbol name table entries.
3317 Output expanded source files for source level debugging. This switch
3318 also suppress generation of cross-reference information (see -gnatx).
3320 @item -gnatec@var{path}
3321 Specify a configuration pragma file. (see @ref{The Configuration Pragmas Files})
3323 @item -gnatem@var{path}
3324 Specify a mapping file. (see @ref{Units to Sources Mapping Files})
3327 Full dynamic elaboration checks.
3330 Full errors. Multiple errors per line, all undefined references.
3333 Externals names are folded to all uppercase.
3336 Internal GNAT implementation mode. This should not be used for
3337 applications programs, it is intended only for use by the compiler
3338 and its run-time library. For documentation, see the GNAT sources.
3341 List generated expanded code in source form.
3343 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3344 Identifier character set
3346 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3349 For details of the possible selections for @var{c},
3350 see @xref{Character Set Control}.
3353 @item ^-gnath^/HELP^
3354 Output usage information. The output is written to @file{stdout}.
3356 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
3357 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3360 Output full source listing with embedded error messages.
3362 @item -gnatm^^=^@var{n}
3363 Limit number of detected errors to @var{n} (1-999).
3366 Activate inlining across unit boundaries for subprograms for which
3367 pragma @code{inline} is specified.
3370 Activate front end inlining.
3372 @item ^-fno-inline^/INLINE=SUPPRESS^
3373 Suppresses all inlining, even if other optimization or inlining switches
3378 Activates stack checking. See separate section on stack checking for
3379 details of the use of this option.
3383 Enable numeric overflow checking (which is not normally enabled by
3384 default). Not that division by zero is a separate check that is not
3385 controlled by this switch (division by zero checking is on by default).
3388 Suppress all checks.
3391 Don't quit; try semantics, even if parse errors.
3394 Don't quit; generate @file{ali} and tree files even if illegalities.
3397 Enable polling. This is required on some systems (notably Windows NT) to
3398 obtain asynchronous abort and asynchronous transfer of control capability.
3399 See the description of pragma Polling in the GNAT Reference Manual for
3402 @item -gnatR[0/1/2/3][s]
3403 Output representation information for declared types and objects.
3409 Tree output file to be generated.
3412 Set time slice to specified number of microseconds
3415 List units for this compilation.
3418 Tag all error messages with the unique string "error:"
3421 Verbose mode. Full error output with source lines to @file{stdout}.
3424 Control level of validity checking. See separate section describing
3427 @item ^-gnatwxxx^/WARNINGS=^@var{xxx}
3429 @var{xxx} is a string of options describing the exact warnings that
3430 are enabled or disabled. See separate section on warning control.
3432 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3433 Wide character encoding method
3435 (@var{e}=n/h/u/s/e/8).
3438 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3442 Suppress generation of cross-reference information.
3444 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3445 Enable built-in style checks. See separate section describing this feature.
3447 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3448 Distribution stub generation and compilation
3450 (@var{m}=r/c for receiver/caller stubs).
3453 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3454 to be generated and compiled).
3458 Enforce Ada 83 restrictions.
3461 @item -pass-exit-codes
3462 Catch exit codes from the compiler and use the most meaningful as
3468 You may combine a sequence of GNAT switches into a single switch. For
3469 example, the combined switch
3471 @cindex Combining GNAT switches
3477 is equivalent to specifying the following sequence of switches:
3480 -gnato -gnatf -gnati3
3485 The following restrictions apply to the combination of switches
3490 The switch @option{-gnatc} if combined with other switches must come
3491 first in the string.
3494 The switch @option{-gnats} if combined with other switches must come
3495 first in the string.
3498 Once a "y" appears in the string (that is a use of the @option{-gnaty}
3499 switch), then all further characters in the switch are interpreted
3500 as style modifiers (see description of @option{-gnaty}).
3503 Once a "d" appears in the string (that is a use of the @option{-gnatd}
3504 switch), then all further characters in the switch are interpreted
3505 as debug flags (see description of @option{-gnatd}).
3508 Once a "w" appears in the string (that is a use of the @option{-gnatw}
3509 switch), then all further characters in the switch are interpreted
3510 as warning mode modifiers (see description of @option{-gnatw}).
3513 Once a "V" appears in the string (that is a use of the @option{-gnatV}
3514 switch), then all further characters in the switch are interpreted
3515 as validity checking options (see description of @option{-gnatV}).
3519 @node Output and Error Message Control
3520 @subsection Output and Error Message Control
3524 The standard default format for error messages is called "brief format."
3525 Brief format messages are written to @file{stderr} (the standard error
3526 file) and have the following form:
3532 e.adb:3:04: Incorrect spelling of keyword "function"
3533 e.adb:4:20: ";" should be "is"
3537 The first integer after the file name is the line number in the file,
3538 and the second integer is the column number within the line.
3539 @code{glide} can parse the error messages
3540 and point to the referenced character.
3541 The following switches provide control over the error message
3546 @cindex @option{-gnatv} (@code{gcc})
3549 The v stands for verbose.
3551 The effect of this setting is to write long-format error
3552 messages to @file{stdout} (the standard output file.
3553 The same program compiled with the
3554 @option{-gnatv} switch would generate:
3559 3. funcion X (Q : Integer)
3561 >>> Incorrect spelling of keyword "function"
3564 >>> ";" should be "is"
3570 The vertical bar indicates the location of the error, and the @samp{>>>}
3571 prefix can be used to search for error messages. When this switch is
3572 used the only source lines output are those with errors.
3575 @cindex @option{-gnatl} (@code{gcc})
3577 The @code{l} stands for list.
3579 This switch causes a full listing of
3580 the file to be generated. The output might look as follows:
3587 3. funcion X (Q : Integer)
3589 >>> Incorrect spelling of keyword "function"
3592 >>> ";" should be "is"
3605 When you specify the @option{-gnatv} or @option{-gnatl} switches and
3606 standard output is redirected, a brief summary is written to
3607 @file{stderr} (standard error) giving the number of error messages and
3608 warning messages generated.
3611 @cindex @option{-gnatU} (@code{gcc})
3612 This switch forces all error messages to be preceded by the unique
3613 string "error:". This means that error messages take a few more
3614 characters in space, but allows easy searching for and identification
3618 @cindex @option{-gnatb} (@code{gcc})
3620 The @code{b} stands for brief.
3622 This switch causes GNAT to generate the
3623 brief format error messages to @file{stderr} (the standard error
3624 file) as well as the verbose
3625 format message or full listing (which as usual is written to
3626 @file{stdout} (the standard output file).
3628 @item -gnatm^^=^@var{n}
3629 @cindex @option{-gnatm} (@code{gcc})
3631 The @code{m} stands for maximum.
3633 @var{n} is a decimal integer in the
3634 range of 1 to 999 and limits the number of error messages to be
3635 generated. For example, using @option{-gnatm2} might yield
3641 e.adb:3:04: Incorrect spelling of keyword "function"
3642 e.adb:5:35: missing ".."
3643 fatal error: maximum errors reached
3644 compilation abandoned
3648 @cindex @option{-gnatf} (@code{gcc})
3649 @cindex Error messages, suppressing
3651 The @code{f} stands for full.
3653 Normally, the compiler suppresses error messages that are likely to be
3654 redundant. This switch causes all error
3655 messages to be generated. In particular, in the case of
3656 references to undefined variables. If a given variable is referenced
3657 several times, the normal format of messages is
3662 e.adb:7:07: "V" is undefined (more references follow)
3666 where the parenthetical comment warns that there are additional
3667 references to the variable @code{V}. Compiling the same program with the
3668 @option{-gnatf} switch yields
3671 e.adb:7:07: "V" is undefined
3672 e.adb:8:07: "V" is undefined
3673 e.adb:8:12: "V" is undefined
3674 e.adb:8:16: "V" is undefined
3675 e.adb:9:07: "V" is undefined
3676 e.adb:9:12: "V" is undefined
3680 @cindex @option{-gnatq} (@code{gcc})
3682 The @code{q} stands for quit (really "don't quit").
3684 In normal operation mode, the compiler first parses the program and
3685 determines if there are any syntax errors. If there are, appropriate
3686 error messages are generated and compilation is immediately terminated.
3688 GNAT to continue with semantic analysis even if syntax errors have been
3689 found. This may enable the detection of more errors in a single run. On
3690 the other hand, the semantic analyzer is more likely to encounter some
3691 internal fatal error when given a syntactically invalid tree.
3694 In normal operation mode, the @file{ali} file is not generated if any
3695 illegalities are detected in the program. The use of @option{-gnatQ} forces
3696 generation of the @file{ali} file. This file is marked as being in
3697 error, so it cannot be used for binding purposes, but it does contain
3698 reasonably complete cross-reference information, and thus may be useful
3699 for use by tools (e.g. semantic browsing tools or integrated development
3700 environments) that are driven from the @file{ali} file.
3702 In addition, if @option{-gnatt} is also specified, then the tree file is
3703 generated even if there are illegalities. It may be useful in this case
3704 to also specify @option{-gnatq} to ensure that full semantic processing
3705 occurs. The resulting tree file can be processed by ASIS, for the purpose
3706 of providing partial information about illegal units, but if the error
3707 causes the tree to be badly malformed, then ASIS may crash during the
3713 In addition to error messages, which correspond to illegalities as defined
3714 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
3717 @cindex Warning messages
3718 First, the compiler considers some constructs suspicious and generates a
3719 warning message to alert you to a possible error. Second, if the
3720 compiler detects a situation that is sure to raise an exception at
3721 run time, it generates a warning message. The following shows an example
3722 of warning messages:
3727 e.adb:4:24: warning: creation of object may raise Storage_Error
3728 e.adb:10:17: warning: static value out of range
3729 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
3734 GNAT considers a large number of situations as appropriate
3735 for the generation of warning messages. As always, warnings are not
3736 definite indications of errors. For example, if you do an out-of-range
3737 assignment with the deliberate intention of raising a
3738 @code{Constraint_Error} exception, then the warning that may be
3739 issued does not indicate an error. Some of the situations for which GNAT
3740 issues warnings (at least some of the time) are given in the following
3741 list, which is not necessarily complete.
3745 Possible infinitely recursive calls
3748 Out-of-range values being assigned
3751 Possible order of elaboration problems
3757 Fixed-point type declarations with a null range
3760 Variables that are never assigned a value
3763 Variables that are referenced before being initialized
3766 Task entries with no corresponding accept statement
3769 Duplicate accepts for the same task entry in a select
3772 Objects that take too much storage
3775 Unchecked conversion between types of differing sizes
3778 Missing return statements along some execution paths in a function
3781 Incorrect (unrecognized) pragmas
3784 Incorrect external names
3787 Allocation from empty storage pool
3790 Potentially blocking operations in protected types
3793 Suspicious parenthesization of expressions
3796 Mismatching bounds in an aggregate
3799 Attempt to return local value by reference
3802 Unrecognized pragmas
3805 Premature instantiation of a generic body
3808 Attempt to pack aliased components
3811 Out of bounds array subscripts
3814 Wrong length on string assignment
3817 Violations of style rules if style checking is enabled
3823 Bit_Order usage that does not have any effect
3826 Compile time biased rounding of floating-point constant
3829 Standard.Duration used to resolve universal fixed expression
3832 Dereference of possibly null value
3835 Declaration that is likely to cause storage error
3838 Internal GNAT unit with'ed by application unit
3841 Values known to be out of range at compile time
3844 Unreferenced labels and variables
3847 Address overlays that could clobber memory
3850 Unexpected initialization when address clause present
3853 Bad alignment for address clause
3856 Useless type conversions
3859 Redundant assignment statements
3862 Accidental hiding of name by child unit
3868 Access before elaboration detected at compile time
3871 A range in a @code{for} loop that is known to be null or might be null
3876 The following switches are available to control the handling of
3880 @item -gnatwa (activate all optional errors)
3881 @cindex @option{-gnatwa} (@code{gcc})
3882 This switch activates most optional warning messages, see remaining list
3883 in this section for details on optional warning messages that can be
3884 individually controlled. The warnings that are not turned on by this
3885 switch are @option{-gnatwb} (biased rounding),
3886 @option{-gnatwd} (implicit dereferencing),
3887 and @option{-gnatwh} (hiding). All other optional warnings are
3890 @item -gnatwA (suppress all optional errors)
3891 @cindex @option{-gnatwA} (@code{gcc})
3892 This switch suppresses all optional warning messages, see remaining list
3893 in this section for details on optional warning messages that can be
3894 individually controlled.
3896 @item -gnatwb (activate warnings on biased rounding)
3897 @cindex @option{-gnatwb} (@code{gcc})
3898 @cindex Rounding, biased
3899 @cindex Biased rounding
3900 If a static floating-point expression has a value that is exactly half
3901 way between two adjacent machine numbers, then the rules of Ada
3902 (Ada Reference Manual, section 4.9(38)) require that this rounding
3903 be done away from zero, even if the normal unbiased rounding rules
3904 at run time would require rounding towards zero. This warning message
3905 alerts you to such instances where compile-time rounding and run-time
3906 rounding are not equivalent. If it is important to get proper run-time
3907 rounding, then you can force this by making one of the operands into
3908 a variable. The default is that such warnings are not generated.
3909 Note that @option{-gnatwa} does not affect the setting of
3910 this warning option.
3912 @item -gnatwB (suppress warnings on biased rounding)
3913 @cindex @option{-gnatwB} (@code{gcc})
3914 This switch disables warnings on biased rounding.
3916 @item -gnatwc (activate warnings on conditionals)
3917 @cindex @option{-gnatwc} (@code{gcc})
3918 @cindex Conditionals, constant
3919 This switch activates warnings for conditional expressions used in
3920 tests that are known to be True or False at compile time. The default
3921 is that such warnings are not generated.
3922 This warning can also be turned on using @option{-gnatwa}.
3924 @item -gnatwC (suppress warnings on conditionals)
3925 @cindex @option{-gnatwC} (@code{gcc})
3926 This switch suppresses warnings for conditional expressions used in
3927 tests that are known to be True or False at compile time.
3929 @item -gnatwd (activate warnings on implicit dereferencing)
3930 @cindex @option{-gnatwd} (@code{gcc})
3931 If this switch is set, then the use of a prefix of an access type
3932 in an indexed component, slice, or selected component without an
3933 explicit @code{.all} will generate a warning. With this warning
3934 enabled, access checks occur only at points where an explicit
3935 @code{.all} appears in the source code (assuming no warnings are
3936 generated as a result of this switch). The default is that such
3937 warnings are not generated.
3938 Note that @option{-gnatwa} does not affect the setting of
3939 this warning option.
3941 @item -gnatwD (suppress warnings on implicit dereferencing)
3942 @cindex @option{-gnatwD} (@code{gcc})
3943 @cindex Implicit dereferencing
3944 @cindex Dereferencing, implicit
3945 This switch suppresses warnings for implicit deferences in
3946 indexed components, slices, and selected components.
3948 @item -gnatwe (treat warnings as errors)
3949 @cindex @option{-gnatwe} (@code{gcc})
3950 @cindex Warnings, treat as error
3951 This switch causes warning messages to be treated as errors.
3952 The warning string still appears, but the warning messages are counted
3953 as errors, and prevent the generation of an object file.
3955 @item -gnatwf (activate warnings on unreferenced formals)
3956 @cindex @option{-gnatwf} (@code{gcc})
3957 @cindex Formals, unreferenced
3958 This switch causes a warning to be generated if a formal parameter
3959 is not referenced in the body of the subprogram. This warning can
3960 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
3962 @item -gnatwF (suppress warnings on unreferenced formals)
3963 @cindex @option{-gnatwF} (@code{gcc})
3964 This switch suppresses warnings for unreferenced formal
3965 parameters. Note that the
3966 combination @option{-gnatwu} followed by @option{-gnatwF} has the
3967 effect of warning on unreferenced entities other than subprogram
3970 @item -gnatwh (activate warnings on hiding)
3971 @cindex @option{-gnatwh} (@code{gcc})
3972 @cindex Hiding of Declarations
3973 This switch activates warnings on hiding declarations.
3974 A declaration is considered hiding
3975 if it is for a non-overloadable entity, and it declares an entity with the
3976 same name as some other entity that is directly or use-visible. The default
3977 is that such warnings are not generated.
3978 Note that @option{-gnatwa} does not affect the setting of this warning option.
3980 @item -gnatwH (suppress warnings on hiding)
3981 @cindex @option{-gnatwH} (@code{gcc})
3982 This switch suppresses warnings on hiding declarations.
3984 @item -gnatwi (activate warnings on implementation units).
3985 @cindex @option{-gnatwi} (@code{gcc})
3986 This switch activates warnings for a @code{with} of an internal GNAT
3987 implementation unit, defined as any unit from the @code{Ada},
3988 @code{Interfaces}, @code{GNAT},
3989 ^^@code{DEC},^ or @code{System}
3990 hierarchies that is not
3991 documented in either the Ada Reference Manual or the GNAT
3992 Programmer's Reference Manual. Such units are intended only
3993 for internal implementation purposes and should not be @code{with}'ed
3994 by user programs. The default is that such warnings are generated
3995 This warning can also be turned on using @option{-gnatwa}.
3997 @item -gnatwI (disable warnings on implementation units).
3998 @cindex @option{-gnatwI} (@code{gcc})
3999 This switch disables warnings for a @code{with} of an internal GNAT
4000 implementation unit.
4002 @item -gnatwl (activate warnings on elaboration pragmas)
4003 @cindex @option{-gnatwl} (@code{gcc})
4004 @cindex Elaboration, warnings
4005 This switch activates warnings on missing pragma Elaborate_All statements.
4006 See the section in this guide on elaboration checking for details on
4007 when such pragma should be used. The default is that such warnings
4009 This warning can also be turned on using @option{-gnatwa}.
4011 @item -gnatwL (suppress warnings on elaboration pragmas)
4012 @cindex @option{-gnatwL} (@code{gcc})
4013 This switch suppresses warnings on missing pragma Elaborate_All statements.
4014 See the section in this guide on elaboration checking for details on
4015 when such pragma should be used.
4017 @item -gnatwo (activate warnings on address clause overlays)
4018 @cindex @option{-gnatwo} (@code{gcc})
4019 @cindex Address Clauses, warnings
4020 This switch activates warnings for possibly unintended initialization
4021 effects of defining address clauses that cause one variable to overlap
4022 another. The default is that such warnings are generated.
4023 This warning can also be turned on using @option{-gnatwa}.
4025 @item -gnatwO (suppress warnings on address clause overlays)
4026 @cindex @option{-gnatwO} (@code{gcc})
4027 This switch suppresses warnings on possibly unintended initialization
4028 effects of defining address clauses that cause one variable to overlap
4031 @item -gnatwp (activate warnings on ineffective pragma Inlines)
4032 @cindex @option{-gnatwp} (@code{gcc})
4033 @cindex Inlining, warnings
4034 This switch activates warnings for failure of front end inlining
4035 (activated by @option{-gnatN}) to inline a particular call. There are
4036 many reasons for not being able to inline a call, including most
4037 commonly that the call is too complex to inline.
4038 This warning can also be turned on using @option{-gnatwa}.
4040 @item -gnatwP (suppress warnings on ineffective pragma Inlines)
4041 @cindex @option{-gnatwP} (@code{gcc})
4042 This switch suppresses warnings on ineffective pragma Inlines. If the
4043 inlining mechanism cannot inline a call, it will simply ignore the
4046 @item -gnatwr (activate warnings on redundant constructs)
4047 @cindex @option{-gnatwr} (@code{gcc})
4048 This switch activates warnings for redundant constructs. The following
4049 is the current list of constructs regarded as redundant:
4050 This warning can also be turned on using @option{-gnatwa}.
4054 Assignment of an item to itself.
4056 Type conversion that converts an expression to its own type.
4058 Use of the attribute @code{Base} where @code{typ'Base} is the same
4061 Use of pragma @code{Pack} when all components are placed by a record
4062 representation clause.
4065 @item -gnatwR (suppress warnings on redundant constructs)
4066 @cindex @option{-gnatwR} (@code{gcc})
4067 This switch suppresses warnings for redundant constructs.
4069 @item -gnatws (suppress all warnings)
4070 @cindex @option{-gnatws} (@code{gcc})
4071 This switch completely suppresses the
4072 output of all warning messages from the GNAT front end.
4073 Note that it does not suppress warnings from the @code{gcc} back end.
4074 To suppress these back end warnings as well, use the switch @code{-w}
4075 in addition to @option{-gnatws}.
4077 @item -gnatwu (activate warnings on unused entities)
4078 @cindex @option{-gnatwu} (@code{gcc})
4079 This switch activates warnings to be generated for entities that
4080 are defined but not referenced, and for units that are @code{with}'ed
4082 referenced. In the case of packages, a warning is also generated if
4083 no entities in the package are referenced. This means that if the package
4084 is referenced but the only references are in @code{use}
4085 clauses or @code{renames}
4086 declarations, a warning is still generated. A warning is also generated
4087 for a generic package that is @code{with}'ed but never instantiated.
4088 In the case where a package or subprogram body is compiled, and there
4089 is a @code{with} on the corresponding spec
4090 that is only referenced in the body,
4091 a warning is also generated, noting that the
4092 @code{with} can be moved to the body. The default is that
4093 such warnings are not generated.
4094 This switch also activates warnings on unreferenced formals
4095 (it is includes the effect of @option{-gnatwf}).
4096 This warning can also be turned on using @option{-gnatwa}.
4098 @item -gnatwU (suppress warnings on unused entities)
4099 @cindex @option{-gnatwU} (@code{gcc})
4100 This switch suppresses warnings for unused entities and packages.
4101 It also turns off warnings on unreferenced formals (and thus includes
4102 the effect of @option{-gnatwF}).
4105 A string of warning parameters can be used in the same parameter. For example:
4112 Would turn on all optional warnings except for elaboration pragma warnings,
4113 and also specify that warnings should be treated as errors.
4117 This switch suppresses warnings from the @code{gcc} backend. It may be
4118 used in conjunction with @option{-gnatws} to ensure that all warnings
4119 are suppressed during the entire compilation process.
4123 @node Debugging and Assertion Control
4124 @subsection Debugging and Assertion Control
4128 @cindex @option{-gnata} (@code{gcc})
4134 The pragmas @code{Assert} and @code{Debug} normally have no effect and
4135 are ignored. This switch, where @samp{a} stands for assert, causes
4136 @code{Assert} and @code{Debug} pragmas to be activated.
4138 The pragmas have the form:
4143 @b{pragma} Assert (@var{Boolean-expression} [,
4144 @var{static-string-expression}])
4145 @b{pragma} Debug (@var{procedure call})
4151 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
4152 If the result is @code{True}, the pragma has no effect (other than
4153 possible side effects from evaluating the expression). If the result is
4154 @code{False}, the exception @code{Assert_Failure} declared in the package
4155 @code{System.Assertions} is
4156 raised (passing @var{static-string-expression}, if present, as the
4157 message associated with the exception). If no string expression is
4158 given the default is a string giving the file name and line number
4161 The @code{Debug} pragma causes @var{procedure} to be called. Note that
4162 @code{pragma Debug} may appear within a declaration sequence, allowing
4163 debugging procedures to be called between declarations.
4166 @item /DEBUG[=debug-level]
4168 Specifies how much debugging information is to be included in
4169 the resulting object file where 'debug-level' is one of the following:
4171 @item TRACEBACK (default)
4172 Include both debugger symbol records and traceback
4175 Include both debugger symbol records and traceback in
4178 Excludes both debugger symbol records and traceback
4179 the object file. Same as /NODEBUG.
4181 Includes only debugger symbol records in the object
4182 file. Note that this doesn't include traceback information.
4187 @node Validity Checking
4188 @subsection Validity Checking
4189 @findex Validity Checking
4192 The Ada 95 Reference Manual has specific requirements for checking
4193 for invalid values. In particular, RM 13.9.1 requires that the
4194 evaluation of invalid values (for example from unchecked conversions),
4195 not result in erroneous execution. In GNAT, the result of such an
4196 evaluation in normal default mode is to either use the value
4197 unmodified, or to raise Constraint_Error in those cases where use
4198 of the unmodified value would cause erroneous execution. The cases
4199 where unmodified values might lead to erroneous execution are case
4200 statements (where a wild jump might result from an invalid value),
4201 and subscripts on the left hand side (where memory corruption could
4202 occur as a result of an invalid value).
4204 The @option{-gnatVx} switch allows more control over the validity checking
4205 mode. The @code{x} argument here is a string of letters which control which
4206 validity checks are performed in addition to the default checks described
4211 @option{-gnatVc} Validity checks for copies
4213 The right hand side of assignments, and the initializing values of
4214 object declarations are validity checked.
4217 @option{-gnatVd} Default (RM) validity checks
4219 Some validity checks are done by default following normal Ada semantics
4221 A check is done in case statements that the expression is within the range
4222 of the subtype. If it is not, Constraint_Error is raised.
4223 For assignments to array components, a check is done that the expression used
4224 as index is within the range. If it is not, Constraint_Error is raised.
4225 Both these validity checks may be turned off using switch @option{-gnatVD}.
4226 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
4227 switch @option{-gnatVd} will leave the checks turned on.
4228 Switch @option{-gnatVD} should be used only if you are sure that all such
4229 expressions have valid values. If you use this switch and invalid values
4230 are present, then the program is erroneous, and wild jumps or memory
4231 overwriting may occur.
4234 @option{-gnatVi} Validity checks for @code{in} mode parameters
4236 Arguments for parameters of mode @code{in} are validity checked in function
4237 and procedure calls at the point of call.
4240 @option{-gnatVm} Validity checks for @code{in out} mode parameters
4242 Arguments for parameters of mode @code{in out} are validity checked in
4243 procedure calls at the point of call. The @code{'m'} here stands for
4244 modify, since this concerns parameters that can be modified by the call.
4245 Note that there is no specific option to test @code{out} parameters,
4246 but any reference within the subprogram will be tested in the usual
4247 manner, and if an invalid value is copied back, any reference to it
4248 will be subject to validity checking.
4251 @option{-gnatVo} Validity checks for operator and attribute operands
4253 Arguments for predefined operators and attributes are validity checked.
4254 This includes all operators in package @code{Standard},
4255 the shift operators defined as intrinsic in package @code{Interfaces}
4256 and operands for attributes such as @code{Pos}.
4259 @option{-gnatVr} Validity checks for function returns
4261 The expression in @code{return} statements in functions is validity
4265 @option{-gnatVs} Validity checks for subscripts
4267 All subscripts expressions are checked for validity, whether they appear
4268 on the right side or left side (in default mode only left side subscripts
4269 are validity checked).
4272 @option{-gnatVt} Validity checks for tests
4274 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
4275 statements are checked, as well as guard expressions in entry calls.
4278 @option{-gnatVf} Validity checks for floating-point values
4280 In the absence of this switch, validity checking occurs only for discrete
4281 values. If @option{-gnatVf} is specified, then validity checking also applies
4282 for floating-point values, and NaN's and infinities are considered invalid,
4283 as well as out of range values for constrained types. Note that this means
4284 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
4285 in which floating-point values are checked depends on the setting of other
4286 options. For example @option{-gnatVif} or @option{-gnatVfi} (the order does
4287 not matter) specifies that floating-point parameters of mode @code{in} should
4288 be validity checked.
4291 @option{-gnatVa} All validity checks
4293 All the above validity checks are turned on. That is @option{-gnatVa} is
4294 equivalent to @code{gnatVcdfimorst}.
4297 @option{-gnatVn} No validity checks
4299 This switch turns off all validity checking, including the default checking
4300 for case statements and left hand side subscripts. Note that the use of
4301 the switch @option{-gnatp} supresses all run-time checks, including
4302 validity checks, and thus implies @option{-gnatVn}.
4306 The @option{-gnatV} switch may be followed by a string of letters to turn on
4307 a series of validity checking options. For example, @option{-gnatVcr} specifies
4308 that in addition to the default validity checking, copies and function
4309 return expressions be validity checked. In order to make it easier to specify
4310 a set of options, the upper case letters @code{CDFIMORST} may be used to turn
4311 off the corresponding lower case option, so for example @option{-gnatVaM} turns
4312 on all validity checking options except for checking of @code{in out}
4313 procedure arguments.
4315 The specification of additional validity checking generates extra code (and
4316 in the case of @option{-gnatva} the code expansion can be substantial. However,
4317 these additional checks can be very useful in smoking out cases of
4318 uninitialized variables, incorrect use of unchecked conversion, and other
4319 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
4320 is useful in conjunction with the extra validity checking, since this
4321 ensures that wherever possible uninitialized variables have invalid values.
4323 See also the pragma @code{Validity_Checks} which allows modification of
4324 the validity checking mode at the program source level, and also allows for
4325 temporary disabling of validity checks.
4327 @node Style Checking
4328 @subsection Style Checking
4329 @findex Style checking
4332 The -gnaty^@var{x}^(@var{option},@var{option},..)^ switch causes the compiler to
4333 enforce specified style rules. A limited set of style rules has been used
4334 in writing the GNAT sources themselves. This switch allows user programs
4335 to activate all or some of these checks. If the source program fails a
4336 specified style check, an appropriate warning message is given, preceded by
4337 the character sequence "(style)".
4339 (OPTION,OPTION,..) is a sequence of keywords
4342 The string @var{x} is a sequence of letters or digits
4344 indicating the particular style
4345 checks to be performed. The following checks are defined:
4348 @item 1-9 (specify indentation level)
4349 If a digit from 1-9 appears in the string after @option{-gnaty} then proper
4350 indentation is checked, with the digit indicating the indentation level
4351 required. The general style of required indentation is as specified by
4352 the examples in the Ada Reference Manual. Full line comments must be
4353 aligned with the @code{--} starting on a column that is a multiple of
4354 the alignment level.
4356 @item ^a^ATTRIBUTE^ (check attribute casing)
4357 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty} then
4358 attribute names, including the case of keywords such as @code{digits}
4359 used as attributes names, must be written in mixed case, that is, the
4360 initial letter and any letter following an underscore must be uppercase.
4361 All other letters must be lowercase.
4363 @item ^b^BLANKS^ (blanks not allowed at statement end)
4364 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
4365 trailing blanks are not allowed at the end of statements. The purpose of this
4366 rule, together with h (no horizontal tabs), is to enforce a canonical format
4367 for the use of blanks to separate source tokens.
4369 @item ^c^COMMENTS^ (check comments)
4370 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty} then
4371 comments must meet the following set of rules:
4376 The "--" that starts the column must either start in column one, or else
4377 at least one blank must precede this sequence.
4380 Comments that follow other tokens on a line must have at least one blank
4381 following the "--" at the start of the comment.
4384 Full line comments must have two blanks following the "--" that starts
4385 the comment, with the following exceptions.
4388 A line consisting only of the "--" characters, possibly preceded by blanks
4392 A comment starting with "--x" where x is a special character is permitted.
4393 This alows proper processing of the output generated by specialized tools
4394 including @code{gnatprep} (where --! is used) and the SPARK annnotation
4395 language (where --# is used). For the purposes of this rule, a special
4396 character is defined as being in one of the ASCII ranges
4397 16#21#..16#2F# or 16#3A#..16#3F#.
4400 A line consisting entirely of minus signs, possibly preceded by blanks, is
4401 permitted. This allows the construction of box comments where lines of minus
4402 signs are used to form the top and bottom of the box.
4405 If a comment starts and ends with "--" is permitted as long as at least
4406 one blank follows the initial "--". Together with the preceding rule,
4407 this allows the construction of box comments, as shown in the following
4410 ---------------------------
4411 -- This is a box comment --
4412 -- with two text lines. --
4413 ---------------------------
4417 @item ^e^END^ (check end/exit labels)
4418 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
4419 optional labels on @code{end} statements ending subprograms and on
4420 @code{exit} statements exiting named loops, are required to be present.
4422 @item ^f^VTABS^ (no form feeds or vertical tabs)
4423 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
4424 neither form feeds nor vertical tab characters are not permitted
4427 @item ^h^HTABS^ (no horizontal tabs)
4428 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
4429 horizontal tab characters are not permitted in the source text.
4430 Together with the b (no blanks at end of line) check, this
4431 enforces a canonical form for the use of blanks to separate
4434 @item ^i^IF_THEN^ (check if-then layout)
4435 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
4436 then the keyword @code{then} must appear either on the same
4437 line as corresponding @code{if}, or on a line on its own, lined
4438 up under the @code{if} with at least one non-blank line in between
4439 containing all or part of the condition to be tested.
4441 @item ^k^KEYWORD^ (check keyword casing)
4442 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
4443 all keywords must be in lower case (with the exception of keywords
4444 such as @code{digits} used as attribute names to which this check
4447 @item ^l^LAYOUT^ (check layout)
4448 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
4449 layout of statement and declaration constructs must follow the
4450 recommendations in the Ada Reference Manual, as indicated by the
4451 form of the syntax rules. For example an @code{else} keyword must
4452 be lined up with the corresponding @code{if} keyword.
4454 There are two respects in which the style rule enforced by this check
4455 option are more liberal than those in the Ada Reference Manual. First
4456 in the case of record declarations, it is permissible to put the
4457 @code{record} keyword on the same line as the @code{type} keyword, and
4458 then the @code{end} in @code{end record} must line up under @code{type}.
4459 For example, either of the following two layouts is acceptable:
4464 @b{type} q @b{is record}
4479 Second, in the case of a block statement, a permitted alternative
4480 is to put the block label on the same line as the @code{declare} or
4481 @code{begin} keyword, and then line the @code{end} keyword up under
4482 the block label. For example both the following are permitted:
4504 The same alternative format is allowed for loops. For example, both of
4505 the following are permitted:
4510 Clear : @b{while} J < 10 @b{loop}
4515 @b{while} J < 10 @b{loop}
4522 @item ^m^LINE_LENGTH^ (check maximum line length)
4523 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
4524 then the length of source lines must not exceed 79 characters, including
4525 any trailing blanks. The value of 79 allows convenient display on an
4526 80 character wide device or window, allowing for possible special
4527 treatment of 80 character lines.
4529 @item ^Mnnn^MAX_LENGTH=nnn^ (set maximum line length)
4530 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
4531 the string after @option{-gnaty} then the length of lines must not exceed the
4534 @item ^n^STANDARD_CASING^ (check casing of entities in Standard)
4535 If the ^letter n^word STANDARD_CASING^ appears in the string
4536 after @option{-gnaty} then any identifier from Standard must be cased
4537 to match the presentation in the Ada Reference Manual (for example,
4538 @code{Integer} and @code{ASCII.NUL}).
4540 @item ^o^ORDERED_SUBPROGRAMS^ (check order of subprogram bodies)
4541 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
4542 after @option{-gnaty} then all subprogram bodies in a given scope
4543 (e.g. a package body) must be in alphabetical order. The ordering
4544 rule uses normal Ada rules for comparing strings, ignoring casing
4545 of letters, except that if there is a trailing numeric suffix, then
4546 the value of this suffix is used in the ordering (e.g. Junk2 comes
4549 @item ^p^PRAGMA^ (check pragma casing)
4550 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
4551 pragma names must be written in mixed case, that is, the
4552 initial letter and any letter following an underscore must be uppercase.
4553 All other letters must be lowercase.
4555 @item ^r^REFERENCES^ (check references)
4556 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
4557 then all identifier references must be cased in the same way as the
4558 corresponding declaration. No specific casing style is imposed on
4559 identifiers. The only requirement is for consistency of references
4562 @item ^s^SPECS^ (check separate specs)
4563 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
4564 separate declarations ("specs") are required for subprograms (a
4565 body is not allowed to serve as its own declaration). The only
4566 exception is that parameterless library level procedures are
4567 not required to have a separate declaration. This exception covers
4568 the most frequent form of main program procedures.
4570 @item ^t^TOKEN^ (check token spacing)
4571 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
4572 the following token spacing rules are enforced:
4577 The keywords @code{abs} and @code{not} must be followed by a space.
4580 The token @code{=>} must be surrounded by spaces.
4583 The token @code{<>} must be preceded by a space or a left parenthesis.
4586 Binary operators other than @code{**} must be surrounded by spaces.
4587 There is no restriction on the layout of the @code{**} binary operator.
4590 Colon must be surrounded by spaces.
4593 Colon-equal (assignment) must be surrounded by spaces.
4596 Comma must be the first non-blank character on the line, or be
4597 immediately preceded by a non-blank character, and must be followed
4601 If the token preceding a left paren ends with a letter or digit, then
4602 a space must separate the two tokens.
4605 A right parenthesis must either be the first non-blank character on
4606 a line, or it must be preceded by a non-blank character.
4609 A semicolon must not be preceded by a space, and must not be followed by
4610 a non-blank character.
4613 A unary plus or minus may not be followed by a space.
4616 A vertical bar must be surrounded by spaces.
4620 In the above rules, appearing in column one is always permitted, that is,
4621 counts as meeting either a requirement for a required preceding space,
4622 or as meeting a requirement for no preceding space.
4624 Appearing at the end of a line is also always permitted, that is, counts
4625 as meeting either a requirement for a following space, or as meeting
4626 a requirement for no following space.
4631 If any of these style rules is violated, a message is generated giving
4632 details on the violation. The initial characters of such messages are
4633 always "(style)". Note that these messages are treated as warning
4634 messages, so they normally do not prevent the generation of an object
4635 file. The @option{-gnatwe} switch can be used to treat warning messages,
4636 including style messages, as fatal errors.
4640 ^@option{-gnaty} on its own (that is not followed by any letters or digits),^/STYLE_CHECKS=ALL_BUILTIN^
4641 is equivalent to ^@code{gnaty3abcefhiklmprst}, that is^^ all checking
4642 options ^are^^ enabled with
4643 the exception of ^-gnatyo^ORDERED_SUBPROGRAMS^,
4644 with an indentation level of 3. This is the standard
4645 checking option that is used for the GNAT sources.
4647 @node Run-Time Checks
4648 @subsection Run-Time Checks
4649 @cindex Division by zero
4650 @cindex Access before elaboration
4651 @cindex Checks, division by zero
4652 @cindex Checks, access before elaboration
4655 If you compile with the default options, GNAT will insert many run-time
4656 checks into the compiled code, including code that performs range
4657 checking against constraints, but not arithmetic overflow checking for
4658 integer operations (including division by zero) or checks for access
4659 before elaboration on subprogram calls. All other run-time checks, as
4660 required by the Ada 95 Reference Manual, are generated by default.
4661 The following @code{gcc} switches refine this default behavior:
4665 @cindex @option{-gnatp} (@code{gcc})
4666 @cindex Suppressing checks
4667 @cindex Checks, suppressing
4669 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
4670 had been present in the source. Validity checks are also suppressed (in
4671 other words @option{-gnatp} also implies @option{-gnatVn}.
4672 Use this switch to improve the performance
4673 of the code at the expense of safety in the presence of invalid data or
4677 @cindex @option{-gnato} (@code{gcc})
4678 @cindex Overflow checks
4679 @cindex Check, overflow
4680 Enables overflow checking for integer operations.
4681 This causes GNAT to generate slower and larger executable
4682 programs by adding code to check for overflow (resulting in raising
4683 @code{Constraint_Error} as required by standard Ada
4684 semantics). These overflow checks correspond to situations in which
4685 the true value of the result of an operation may be outside the base
4686 range of the result type. The following example shows the distinction:
4689 X1 : Integer := Integer'Last;
4690 X2 : Integer range 1 .. 5 := 5;
4692 X1 := X1 + 1; -- @option{-gnato} required to catch the Constraint_Error
4693 X2 := X2 + 1; -- range check, @option{-gnato} has no effect here
4697 Here the first addition results in a value that is outside the base range
4698 of Integer, and hence requires an overflow check for detection of the
4699 constraint error. The second increment operation results in a violation
4700 of the explicit range constraint, and such range checks are always
4701 performed. Basically the compiler can assume that in the absence of
4702 the @option{-gnato} switch that any value of type @code{xxx} is
4703 in range of the base type of @code{xxx}.
4705 @findex Machine_Overflows
4706 Note that the @option{-gnato} switch does not affect the code generated
4707 for any floating-point operations; it applies only to integer
4709 For floating-point, GNAT has the @code{Machine_Overflows}
4710 attribute set to @code{False} and the normal mode of operation is to
4711 generate IEEE NaN and infinite values on overflow or invalid operations
4712 (such as dividing 0.0 by 0.0).
4714 The reason that we distinguish overflow checking from other kinds of
4715 range constraint checking is that a failure of an overflow check can
4716 generate an incorrect value, but cannot cause erroneous behavior. This
4717 is unlike the situation with a constraint check on an array subscript,
4718 where failure to perform the check can result in random memory description,
4719 or the range check on a case statement, where failure to perform the check
4720 can cause a wild jump.
4722 Note again that @option{-gnato} is off by default, so overflow checking is
4723 not performed in default mode. This means that out of the box, with the
4724 default settings, GNAT does not do all the checks expected from the
4725 language description in the Ada Reference Manual. If you want all constraint
4726 checks to be performed, as described in this Manual, then you must
4727 explicitly use the -gnato switch either on the @code{gnatmake} or
4731 @cindex @option{-gnatE} (@code{gcc})
4732 @cindex Elaboration checks
4733 @cindex Check, elaboration
4734 Enables dynamic checks for access-before-elaboration
4735 on subprogram calls and generic instantiations.
4736 For full details of the effect and use of this switch,
4737 @xref{Compiling Using gcc}.
4742 The setting of these switches only controls the default setting of the
4743 checks. You may modify them using either @code{Suppress} (to remove
4744 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
4747 @node Stack Overflow Checking
4748 @subsection Stack Overflow Checking
4749 @cindex Stack Overflow Checking
4750 @cindex -fstack-check
4753 For most operating systems, @code{gcc} does not perform stack overflow
4754 checking by default. This means that if the main environment task or
4755 some other task exceeds the available stack space, then unpredictable
4756 behavior will occur.
4758 To activate stack checking, compile all units with the gcc option
4759 @code{-fstack-check}. For example:
4762 gcc -c -fstack-check package1.adb
4766 Units compiled with this option will generate extra instructions to check
4767 that any use of the stack (for procedure calls or for declaring local
4768 variables in declare blocks) do not exceed the available stack space.
4769 If the space is exceeded, then a @code{Storage_Error} exception is raised.
4771 For declared tasks, the stack size is always controlled by the size
4772 given in an applicable @code{Storage_Size} pragma (or is set to
4773 the default size if no pragma is used.
4775 For the environment task, the stack size depends on
4776 system defaults and is unknown to the compiler. The stack
4777 may even dynamically grow on some systems, precluding the
4778 normal Ada semantics for stack overflow. In the worst case,
4779 unbounded stack usage, causes unbounded stack expansion
4780 resulting in the system running out of virtual memory.
4782 The stack checking may still work correctly if a fixed
4783 size stack is allocated, but this cannot be guaranteed.
4784 To ensure that a clean exception is signalled for stack
4785 overflow, set the environment variable
4786 @code{GNAT_STACK_LIMIT} to indicate the maximum
4787 stack area that can be used, as in:
4788 @cindex GNAT_STACK_LIMIT
4791 SET GNAT_STACK_LIMIT 1600
4795 The limit is given in kilobytes, so the above declaration would
4796 set the stack limit of the environment task to 1.6 megabytes.
4797 Note that the only purpose of this usage is to limit the amount
4798 of stack used by the environment task. If it is necessary to
4799 increase the amount of stack for the environment task, then this
4800 is an operating systems issue, and must be addressed with the
4801 appropriate operating systems commands.
4803 @node Run-Time Control
4804 @subsection Run-Time Control
4808 @cindex @option{-gnatT} (@code{gcc})
4809 @cindex Time Slicing
4812 The @code{gnatT} switch can be used to specify the time-slicing value
4813 to be used for task switching between equal priority tasks. The value
4814 @code{nnn} is given in microseconds as a decimal integer.
4816 Setting the time-slicing value is only effective if the underlying thread
4817 control system can accommodate time slicing. Check the documentation of
4818 your operating system for details. Note that the time-slicing value can
4819 also be set by use of pragma @code{Time_Slice} or by use of the
4820 @code{t} switch in the gnatbind step. The pragma overrides a command
4821 line argument if both are present, and the @code{t} switch for gnatbind
4822 overrides both the pragma and the @code{gcc} command line switch.
4825 @node Using gcc for Syntax Checking
4826 @subsection Using @code{gcc} for Syntax Checking
4829 @cindex @option{-gnats} (@code{gcc})
4833 The @code{s} stands for syntax.
4836 Run GNAT in syntax checking only mode. For
4837 example, the command
4840 $ gcc -c -gnats x.adb
4844 compiles file @file{x.adb} in syntax-check-only mode. You can check a
4845 series of files in a single command
4847 , and can use wild cards to specify such a group of files.
4848 Note that you must specify the @code{-c} (compile
4849 only) flag in addition to the @option{-gnats} flag.
4853 You may use other switches in conjunction with @option{-gnats}. In
4854 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
4855 format of any generated error messages.
4857 The output is simply the error messages, if any. No object file or ALI
4858 file is generated by a syntax-only compilation. Also, no units other
4859 than the one specified are accessed. For example, if a unit @code{X}
4860 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
4861 check only mode does not access the source file containing unit
4864 @cindex Multiple units, syntax checking
4865 Normally, GNAT allows only a single unit in a source file. However, this
4866 restriction does not apply in syntax-check-only mode, and it is possible
4867 to check a file containing multiple compilation units concatenated
4868 together. This is primarily used by the @code{gnatchop} utility
4869 (@pxref{Renaming Files Using gnatchop}).
4872 @node Using gcc for Semantic Checking
4873 @subsection Using @code{gcc} for Semantic Checking
4876 @cindex @option{-gnatc} (@code{gcc})
4880 The @code{c} stands for check.
4882 Causes the compiler to operate in semantic check mode,
4883 with full checking for all illegalities specified in the
4884 Ada 95 Reference Manual, but without generation of any object code
4885 (no object file is generated).
4887 Because dependent files must be accessed, you must follow the GNAT
4888 semantic restrictions on file structuring to operate in this mode:
4892 The needed source files must be accessible
4893 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4896 Each file must contain only one compilation unit.
4899 The file name and unit name must match (@pxref{File Naming Rules}).
4902 The output consists of error messages as appropriate. No object file is
4903 generated. An @file{ALI} file is generated for use in the context of
4904 cross-reference tools, but this file is marked as not being suitable
4905 for binding (since no object file is generated).
4906 The checking corresponds exactly to the notion of
4907 legality in the Ada 95 Reference Manual.
4909 Any unit can be compiled in semantics-checking-only mode, including
4910 units that would not normally be compiled (subunits,
4911 and specifications where a separate body is present).
4914 @node Compiling Ada 83 Programs
4915 @subsection Compiling Ada 83 Programs
4917 @cindex Ada 83 compatibility
4919 @cindex @option{-gnat83} (@code{gcc})
4920 @cindex ACVC, Ada 83 tests
4923 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
4924 specify that an Ada 83 program is to be compiled in Ada83 mode. If you specify
4925 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
4926 where this can be done easily.
4927 It is not possible to guarantee this switch does a perfect
4928 job; for example, some subtle tests, such as are
4929 found in earlier ACVC tests (that have been removed from the ACVC suite for Ada
4930 95), may not compile correctly. However, for most purposes, using
4931 this switch should help to ensure that programs that compile correctly
4932 under the @option{-gnat83} switch can be ported easily to an Ada 83
4933 compiler. This is the main use of the switch.
4935 With few exceptions (most notably the need to use @code{<>} on
4936 @cindex Generic formal parameters
4937 unconstrained generic formal parameters, the use of the new Ada 95
4938 keywords, and the use of packages
4939 with optional bodies), it is not necessary to use the
4940 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
4941 exceptions, Ada 95 is upwardly compatible with Ada 83. This
4942 means that a correct Ada 83 program is usually also a correct Ada 95
4947 @node Character Set Control
4948 @subsection Character Set Control
4950 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4951 @cindex @code{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
4954 Normally GNAT recognizes the Latin-1 character set in source program
4955 identifiers, as described in the Ada 95 Reference Manual.
4957 GNAT to recognize alternate character sets in identifiers. @var{c} is a
4958 single character ^^or word^ indicating the character set, as follows:
4965 Latin-2 letters allowed in identifiers
4968 Latin-3 letters allowed in identifiers
4971 Latin-4 letters allowed in identifiers
4974 Latin-5 (Cyrillic) letters allowed in identifiers
4977 Latin-9 letters allowed in identifiers
4980 IBM PC letters (code page 437) allowed in identifiers
4983 IBM PC letters (code page 850) allowed in identifiers
4985 @item ^f^FULL_UPPER^
4986 Full upper-half codes allowed in identifiers
4989 No upper-half codes allowed in identifiers
4992 Wide-character codes (that is, codes greater than 255)
4993 allowed in identifiers
4996 @xref{Foreign Language Representation}, for full details on the
4997 implementation of these character sets.
4999 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
5000 @cindex @code{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
5001 Specify the method of encoding for wide characters.
5002 @var{e} is one of the following:
5007 Hex encoding (brackets coding also recognized)
5010 Upper half encoding (brackets encoding also recognized)
5013 Shift/JIS encoding (brackets encoding also recognized)
5016 EUC encoding (brackets encoding also recognized)
5019 UTF-8 encoding (brackets encoding also recognized)
5022 Brackets encoding only (default value)
5024 For full details on the these encoding
5025 methods see @xref{Wide Character Encodings}.
5026 Note that brackets coding is always accepted, even if one of the other
5027 options is specified, so for example @option{-gnatW8} specifies that both
5028 brackets and @code{UTF-8} encodings will be recognized. The units that are
5029 with'ed directly or indirectly will be scanned using the specified
5030 representation scheme, and so if one of the non-brackets scheme is
5031 used, it must be used consistently throughout the program. However,
5032 since brackets encoding is always recognized, it may be conveniently
5033 used in standard libraries, allowing these libraries to be used with
5034 any of the available coding schemes.
5035 scheme. If no @option{-gnatW?} parameter is present, then the default
5036 representation is Brackets encoding only.
5038 Note that the wide character representation that is specified (explicitly
5039 or by default) for the main program also acts as the default encoding used
5040 for Wide_Text_IO files if not specifically overridden by a WCEM form
5044 @node File Naming Control
5045 @subsection File Naming Control
5048 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
5049 @cindex @option{-gnatk} (@code{gcc})
5050 Activates file name "krunching". @var{n}, a decimal integer in the range
5051 1-999, indicates the maximum allowable length of a file name (not
5052 including the @file{.ads} or @file{.adb} extension). The default is not
5053 to enable file name krunching.
5055 For the source file naming rules, @xref{File Naming Rules}.
5058 @node Subprogram Inlining Control
5059 @subsection Subprogram Inlining Control
5063 @cindex @option{-gnatn} (@code{gcc})
5065 The @code{n} here is intended to suggest the first syllable of the
5068 GNAT recognizes and processes @code{Inline} pragmas. However, for the
5069 inlining to actually occur, optimization must be enabled. To enable
5070 inlining across unit boundaries, this is, inlining a call in one unit of
5071 a subprogram declared in a @code{with}'ed unit, you must also specify
5073 In the absence of this switch, GNAT does not attempt
5074 inlining across units and does not need to access the bodies of
5075 subprograms for which @code{pragma Inline} is specified if they are not
5076 in the current unit.
5078 If you specify this switch the compiler will access these bodies,
5079 creating an extra source dependency for the resulting object file, and
5080 where possible, the call will be inlined.
5081 For further details on when inlining is possible
5082 see @xref{Inlining of Subprograms}.
5085 @cindex @option{-gnatN} (@code{gcc})
5086 The front end inlining activated by this switch is generally more extensive,
5087 and quite often more effective than the standard @option{-gnatn} inlining mode.
5088 It will also generate additional dependencies.
5092 @node Auxiliary Output Control
5093 @subsection Auxiliary Output Control
5097 @cindex @option{-gnatt} (@code{gcc})
5098 @cindex Writing internal trees
5099 @cindex Internal trees, writing to file
5100 Causes GNAT to write the internal tree for a unit to a file (with the
5101 extension @file{.adt}.
5102 This not normally required, but is used by separate analysis tools.
5104 these tools do the necessary compilations automatically, so you should
5105 not have to specify this switch in normal operation.
5108 @cindex @option{-gnatu} (@code{gcc})
5109 Print a list of units required by this compilation on @file{stdout}.
5110 The listing includes all units on which the unit being compiled depends
5111 either directly or indirectly.
5114 @item -pass-exit-codes
5115 @cindex @code{-pass-exit-codes} (@code{gcc})
5116 If this switch is not used, the exit code returned by @code{gcc} when
5117 compiling multiple files indicates whether all source files have
5118 been successfully used to generate object files or not.
5120 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
5121 exit status and allows an integrated development environment to better
5122 react to a compilation failure. Those exit status are:
5126 There was an error in at least one source file.
5128 At least one source file did not generate an object file.
5130 The compiler died unexpectedly (internal error for example).
5132 An object file has been generated for every source file.
5137 @node Debugging Control
5138 @subsection Debugging Control
5141 @cindex Debugging options
5144 Activate internal debugging switches. @var{x} is a letter or digit, or
5145 string of letters or digits, which specifies the type of debugging
5146 outputs desired. Normally these are used only for internal development
5147 or system debugging purposes. You can find full documentation for these
5148 switches in the body of the @code{Debug} unit in the compiler source
5149 file @file{debug.adb}.
5153 @cindex @option{-gnatG} (@code{gcc})
5154 This switch causes the compiler to generate auxiliary output containing
5155 a pseudo-source listing of the generated expanded code. Like most Ada
5156 compilers, GNAT works by first transforming the high level Ada code into
5157 lower level constructs. For example, tasking operations are transformed
5158 into calls to the tasking run-time routines. A unique capability of GNAT
5159 is to list this expanded code in a form very close to normal Ada source.
5160 This is very useful in understanding the implications of various Ada
5161 usage on the efficiency of the generated code. There are many cases in
5162 Ada (e.g. the use of controlled types), where simple Ada statements can
5163 generate a lot of run-time code. By using @option{-gnatG} you can identify
5164 these cases, and consider whether it may be desirable to modify the coding
5165 approach to improve efficiency.
5167 The format of the output is very similar to standard Ada source, and is
5168 easily understood by an Ada programmer. The following special syntactic
5169 additions correspond to low level features used in the generated code that
5170 do not have any exact analogies in pure Ada source form. The following
5171 is a partial list of these special constructions. See the specification
5172 of package @code{Sprint} in file @file{sprint.ads} for a full list.
5175 @item new @var{xxx} [storage_pool = @var{yyy}]
5176 Shows the storage pool being used for an allocator.
5178 @item at end @var{procedure-name};
5179 Shows the finalization (cleanup) procedure for a scope.
5181 @item (if @var{expr} then @var{expr} else @var{expr})
5182 Conditional expression equivalent to the @code{x?y:z} construction in C.
5184 @item @var{target}^^^(@var{source})
5185 A conversion with floating-point truncation instead of rounding.
5187 @item @var{target}?(@var{source})
5188 A conversion that bypasses normal Ada semantic checking. In particular
5189 enumeration types and fixed-point types are treated simply as integers.
5191 @item @var{target}?^^^(@var{source})
5192 Combines the above two cases.
5194 @item @var{x} #/ @var{y}
5195 @itemx @var{x} #mod @var{y}
5196 @itemx @var{x} #* @var{y}
5197 @itemx @var{x} #rem @var{y}
5198 A division or multiplication of fixed-point values which are treated as
5199 integers without any kind of scaling.
5201 @item free @var{expr} [storage_pool = @var{xxx}]
5202 Shows the storage pool associated with a @code{free} statement.
5204 @item freeze @var{typename} [@var{actions}]
5205 Shows the point at which @var{typename} is frozen, with possible
5206 associated actions to be performed at the freeze point.
5208 @item reference @var{itype}
5209 Reference (and hence definition) to internal type @var{itype}.
5211 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
5212 Intrinsic function call.
5214 @item @var{labelname} : label
5215 Declaration of label @var{labelname}.
5217 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
5218 A multiple concatenation (same effect as @var{expr} & @var{expr} &
5219 @var{expr}, but handled more efficiently).
5221 @item [constraint_error]
5222 Raise the @code{Constraint_Error} exception.
5224 @item @var{expression}'reference
5225 A pointer to the result of evaluating @var{expression}.
5227 @item @var{target-type}!(@var{source-expression})
5228 An unchecked conversion of @var{source-expression} to @var{target-type}.
5230 @item [@var{numerator}/@var{denominator}]
5231 Used to represent internal real literals (that) have no exact
5232 representation in base 2-16 (for example, the result of compile time
5233 evaluation of the expression 1.0/27.0).
5236 @cindex @option{-gnatD} (@code{gcc})
5237 This switch is used in conjunction with @option{-gnatG} to cause the expanded
5238 source, as described above to be written to files with names
5239 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
5240 for example, if the source file name is @file{hello.adb},
5241 then a file @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.
5242 The debugging information generated
5243 by the @code{gcc} @code{^-g^/DEBUG^} switch will refer to the generated
5244 @file{^xxx.dg^XXX_DG^} file. This allows you to do source level debugging using
5245 the generated code which is sometimes useful for complex code, for example
5246 to find out exactly which part of a complex construction raised an
5247 exception. This switch also suppress generation of cross-reference
5248 information (see -gnatx).
5251 @cindex @option{-gnatE} (@code{gcc})
5252 In the generated debugging information, and also in the case of long external
5253 names, the compiler uses a compression mechanism if the name is very long.
5254 This compression method uses a checksum, and avoids trouble on some operating
5255 systems which have difficulty with very long names. The @option{-gnatC} switch
5256 forces this compression approach to be used on all external names and names
5257 in the debugging information tables. This reduces the size of the generated
5258 executable, at the expense of making the naming scheme more complex. The
5259 compression only affects the qualification of the name. Thus a name in
5263 Very_Long_Package.Very_Long_Inner_Package.Var
5267 would normally appear in these tables as:
5270 very_long_package__very_long_inner_package__var
5274 but if the @option{-gnatC} switch is used, then the name appears as
5281 Here b7e0c705 is a compressed encoding of the qualification prefix.
5282 The GNAT Ada aware version of GDB understands these encoded prefixes, so if this
5283 debugger is used, the encoding is largely hidden from the user of the compiler.
5287 @item -gnatR[0|1|2|3][s]
5288 @cindex @option{-gnatR} (@code{gcc})
5289 This switch controls output from the compiler of a listing showing
5290 representation information for declared types and objects. For
5291 @option{-gnatR0}, no information is output (equivalent to omitting
5292 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
5293 so @option{-gnatR} with no parameter has the same effect), size and alignment
5294 information is listed for declared array and record types. For
5295 @option{-gnatR2}, size and alignment information is listed for all
5296 expression information for values that are computed at run time for
5297 variant records. These symbolic expressions have a mostly obvious
5298 format with #n being used to represent the value of the n'th
5299 discriminant. See source files @file{repinfo.ads/adb} in the
5300 @code{GNAT} sources for full detalis on the format of @option{-gnatR3}
5301 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
5302 the output is to a file with the name @file{^file.rep^file_REP^} where
5303 file is the name of the corresponding source file.
5306 @cindex @option{-gnatx} (@code{gcc})
5307 Normally the compiler generates full cross-referencing information in
5308 the @file{ALI} file. This information is used by a number of tools,
5309 including @code{gnatfind} and @code{gnatxref}. The -gnatx switch
5310 suppresses this information. This saves some space and may slightly
5311 speed up compilation, but means that these tools cannot be used.
5314 @node Units to Sources Mapping Files
5315 @subsection Units to Sources Mapping Files
5319 @item -gnatem@var{path}
5320 @cindex @option{-gnatem} (@code{gcc})
5321 A mapping file is a way to communicate to the compiler two mappings:
5322 from unit names to file names (without any directory information) and from
5323 file names to path names (with full directory information). These mappings
5324 are used by the compiler to short-circuit the path search.
5326 A mapping file is a sequence of sets of three lines. In each set,
5327 the first line is the unit name, in lower case, with "%s" appended for
5328 specifications and "%b" appended for bodies; the second line is the file
5329 name; and the third line is the path name.
5335 /gnat/project1/sources/main.2.ada
5338 When the switch @option{-gnatem} is specified, the compiler will create
5339 in memory the two mappings from the specified file. If there is any problem
5340 (non existent file, truncated file or duplicate entries), no mapping
5343 Several @option{-gnatem} switches may be specified; however, only the last
5344 one on the command line will be taken into account.
5346 When using a project file, @code{gnatmake} create a temporary mapping file
5347 and communicates it to the compiler using this switch.
5351 @node Search Paths and the Run-Time Library (RTL)
5352 @section Search Paths and the Run-Time Library (RTL)
5355 With the GNAT source-based library system, the compiler must be able to
5356 find source files for units that are needed by the unit being compiled.
5357 Search paths are used to guide this process.
5359 The compiler compiles one source file whose name must be given
5360 explicitly on the command line. In other words, no searching is done
5361 for this file. To find all other source files that are needed (the most
5362 common being the specs of units), the compiler examines the following
5363 directories, in the following order:
5367 The directory containing the source file of the main unit being compiled
5368 (the file name on the command line).
5371 Each directory named by an @code{^-I^/SOURCE_SEARCH^} switch given on the @code{gcc}
5372 command line, in the order given.
5375 @findex ADA_INCLUDE_PATH
5376 Each of the directories listed in the value of the
5377 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
5379 Construct this value
5380 exactly as the @code{PATH} environment variable: a list of directory
5381 names separated by colons (semicolons when working with the NT version).
5384 Normally, define this value as a logical name containing a comma separated
5385 list of directory names.
5387 This variable can also be defined by means of an environment string
5388 (an argument to the DEC C exec* set of functions).
5392 DEFINE ANOTHER_PATH FOO:[BAG]
5393 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
5396 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
5397 first, followed by the standard Ada 95
5398 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
5399 If this is not redefined, the user will obtain the DEC Ada83 IO packages
5400 (Text_IO, Sequential_IO, etc)
5401 instead of the Ada95 packages. Thus, in order to get the Ada 95
5402 packages by default, ADA_INCLUDE_PATH must be redefined.
5405 The content of the "ada_source_path" file which is part of the GNAT
5406 installation tree and is used to store standard libraries such as the
5407 GNAT Run Time Library (RTL) source files.
5409 @ref{Installing an Ada Library}
5414 Specifying the switch @code{^-I-^/NOCURRENT_DIRECTORY^}
5415 inhibits the use of the directory
5416 containing the source file named in the command line. You can still
5417 have this directory on your search path, but in this case it must be
5418 explicitly requested with a @code{^-I^/SOURCE_SEARCH^} switch.
5420 Specifying the switch @code{-nostdinc}
5421 inhibits the search of the default location for the GNAT Run Time
5422 Library (RTL) source files.
5424 The compiler outputs its object files and ALI files in the current
5427 Caution: The object file can be redirected with the @code{-o} switch;
5428 however, @code{gcc} and @code{gnat1} have not been coordinated on this
5429 so the ALI file will not go to the right place. Therefore, you should
5430 avoid using the @code{-o} switch.
5434 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
5435 children make up the GNAT RTL, together with the simple @code{System.IO}
5436 package used in the "Hello World" example. The sources for these units
5437 are needed by the compiler and are kept together in one directory. Not
5438 all of the bodies are needed, but all of the sources are kept together
5439 anyway. In a normal installation, you need not specify these directory
5440 names when compiling or binding. Either the environment variables or
5441 the built-in defaults cause these files to be found.
5443 In addition to the language-defined hierarchies (System, Ada and
5444 Interfaces), the GNAT distribution provides a fourth hierarchy,
5445 consisting of child units of GNAT. This is a collection of generally
5446 useful routines. See the GNAT Reference Manual for further details.
5448 Besides simplifying access to the RTL, a major use of search paths is
5449 in compiling sources from multiple directories. This can make
5450 development environments much more flexible.
5452 @node Order of Compilation Issues
5453 @section Order of Compilation Issues
5456 If, in our earlier example, there was a spec for the @code{hello}
5457 procedure, it would be contained in the file @file{hello.ads}; yet this
5458 file would not have to be explicitly compiled. This is the result of the
5459 model we chose to implement library management. Some of the consequences
5460 of this model are as follows:
5464 There is no point in compiling specs (except for package
5465 specs with no bodies) because these are compiled as needed by clients. If
5466 you attempt a useless compilation, you will receive an error message.
5467 It is also useless to compile subunits because they are compiled as needed
5471 There are no order of compilation requirements: performing a
5472 compilation never obsoletes anything. The only way you can obsolete
5473 something and require recompilations is to modify one of the
5474 source files on which it depends.
5477 There is no library as such, apart from the ALI files
5478 (@pxref{The Ada Library Information Files}, for information on the format of these
5479 files). For now we find it convenient to create separate ALI files, but
5480 eventually the information therein may be incorporated into the object
5484 When you compile a unit, the source files for the specs of all units
5485 that it @code{with}'s, all its subunits, and the bodies of any generics it
5486 instantiates must be available (reachable by the search-paths mechanism
5487 described above), or you will receive a fatal error message.
5494 The following are some typical Ada compilation command line examples:
5497 @item $ gcc -c xyz.adb
5498 Compile body in file @file{xyz.adb} with all default options.
5501 @item $ gcc -c -O2 -gnata xyz-def.adb
5504 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
5507 Compile the child unit package in file @file{xyz-def.adb} with extensive
5508 optimizations, and pragma @code{Assert}/@code{Debug} statements
5511 @item $ gcc -c -gnatc abc-def.adb
5512 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
5516 @node Binding Using gnatbind
5517 @chapter Binding Using @code{gnatbind}
5521 * Running gnatbind::
5522 * Generating the Binder Program in C::
5523 * Consistency-Checking Modes::
5524 * Binder Error Message Control::
5525 * Elaboration Control::
5527 * Binding with Non-Ada Main Programs::
5528 * Binding Programs with No Main Subprogram::
5529 * Summary of Binder Switches::
5530 * Command-Line Access::
5531 * Search Paths for gnatbind::
5532 * Examples of gnatbind Usage::
5536 This chapter describes the GNAT binder, @code{gnatbind}, which is used
5537 to bind compiled GNAT objects. The @code{gnatbind} program performs
5538 four separate functions:
5542 Checks that a program is consistent, in accordance with the rules in
5543 Chapter 10 of the Ada 95 Reference Manual. In particular, error
5544 messages are generated if a program uses inconsistent versions of a
5548 Checks that an acceptable order of elaboration exists for the program
5549 and issues an error message if it cannot find an order of elaboration
5550 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
5553 Generates a main program incorporating the given elaboration order.
5554 This program is a small Ada package (body and spec) that
5555 must be subsequently compiled
5556 using the GNAT compiler. The necessary compilation step is usually
5557 performed automatically by @code{gnatlink}. The two most important
5558 functions of this program
5559 are to call the elaboration routines of units in an appropriate order
5560 and to call the main program.
5563 Determines the set of object files required by the given main program.
5564 This information is output in the forms of comments in the generated program,
5565 to be read by the @code{gnatlink} utility used to link the Ada application.
5568 @node Running gnatbind
5569 @section Running @code{gnatbind}
5572 The form of the @code{gnatbind} command is
5575 $ gnatbind [@var{switches}] @var{mainprog}[.ali] [@var{switches}]
5579 where @var{mainprog}.adb is the Ada file containing the main program
5580 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
5581 package in two files which names are
5582 @file{b~@var{ada_main}.ads}, and @file{b~@var{ada_main}.adb}.
5583 For example, if given the
5584 parameter @samp{hello.ali}, for a main program contained in file
5585 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
5586 and @file{b~hello.adb}.
5588 When doing consistency checking, the binder takes into consideration
5589 any source files it can locate. For example, if the binder determines
5590 that the given main program requires the package @code{Pack}, whose
5592 file is @file{pack.ali} and whose corresponding source spec file is
5593 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
5594 (using the same search path conventions as previously described for the
5595 @code{gcc} command). If it can locate this source file, it checks that
5597 or source checksums of the source and its references to in @file{ali} files
5598 match. In other words, any @file{ali} files that mentions this spec must have
5599 resulted from compiling this version of the source file (or in the case
5600 where the source checksums match, a version close enough that the
5601 difference does not matter).
5603 @cindex Source files, use by binder
5604 The effect of this consistency checking, which includes source files, is
5605 that the binder ensures that the program is consistent with the latest
5606 version of the source files that can be located at bind time. Editing a
5607 source file without compiling files that depend on the source file cause
5608 error messages to be generated by the binder.
5610 For example, suppose you have a main program @file{hello.adb} and a
5611 package @code{P}, from file @file{p.ads} and you perform the following
5616 Enter @code{gcc -c hello.adb} to compile the main program.
5619 Enter @code{gcc -c p.ads} to compile package @code{P}.
5622 Edit file @file{p.ads}.
5625 Enter @code{gnatbind hello}.
5628 At this point, the file @file{p.ali} contains an out-of-date time stamp
5629 because the file @file{p.ads} has been edited. The attempt at binding
5630 fails, and the binder generates the following error messages:
5633 error: "hello.adb" must be recompiled ("p.ads" has been modified)
5634 error: "p.ads" has been modified and must be recompiled
5638 Now both files must be recompiled as indicated, and then the bind can
5639 succeed, generating a main program. You need not normally be concerned
5640 with the contents of this file, but it is similar to the following which
5641 is the binder file generated for a simple "hello world" program.
5647 -- The package is called Ada_Main unless this name is actually used
5648 -- as a unit name in the partition, in which case some other unique
5654 Elab_Final_Code : Integer;
5655 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
5657 -- The main program saves the parameters (argument count,
5658 -- argument values, environment pointer) in global variables
5659 -- for later access by other units including
5660 -- Ada.Command_Line.
5662 gnat_argc : Integer;
5663 gnat_argv : System.Address;
5664 gnat_envp : System.Address;
5666 -- The actual variables are stored in a library routine. This
5667 -- is useful for some shared library situations, where there
5668 -- are problems if variables are not in the library.
5670 pragma Import (C, gnat_argc);
5671 pragma Import (C, gnat_argv);
5672 pragma Import (C, gnat_envp);
5674 -- The exit status is similarly an external location
5676 gnat_exit_status : Integer;
5677 pragma Import (C, gnat_exit_status);
5679 GNAT_Version : constant String :=
5680 "GNAT Version: 3.15w (20010315)";
5681 pragma Export (C, GNAT_Version, "__gnat_version");
5683 -- This is the generated adafinal routine that performs
5684 -- finalization at the end of execution. In the case where
5685 -- Ada is the main program, this main program makes a call
5686 -- to adafinal at program termination.
5689 pragma Export (C, adafinal, "adafinal");
5691 -- This is the generated adainit routine that performs
5692 -- initialization at the start of execution. In the case
5693 -- where Ada is the main program, this main program makes
5694 -- a call to adainit at program startup.
5697 pragma Export (C, adainit, "adainit");
5699 -- This routine is called at the start of execution. It is
5700 -- a dummy routine that is used by the debugger to breakpoint
5701 -- at the start of execution.
5703 procedure Break_Start;
5704 pragma Import (C, Break_Start, "__gnat_break_start");
5706 -- This is the actual generated main program (it would be
5707 -- suppressed if the no main program switch were used). As
5708 -- required by standard system conventions, this program has
5709 -- the external name main.
5713 argv : System.Address;
5714 envp : System.Address)
5716 pragma Export (C, main, "main");
5718 -- The following set of constants give the version
5719 -- identification values for every unit in the bound
5720 -- partition. This identification is computed from all
5721 -- dependent semantic units, and corresponds to the
5722 -- string that would be returned by use of the
5723 -- Body_Version or Version attributes.
5725 type Version_32 is mod 2 ** 32;
5726 u00001 : constant Version_32 := 16#7880BEB3#;
5727 u00002 : constant Version_32 := 16#0D24CBD0#;
5728 u00003 : constant Version_32 := 16#3283DBEB#;
5729 u00004 : constant Version_32 := 16#2359F9ED#;
5730 u00005 : constant Version_32 := 16#664FB847#;
5731 u00006 : constant Version_32 := 16#68E803DF#;
5732 u00007 : constant Version_32 := 16#5572E604#;
5733 u00008 : constant Version_32 := 16#46B173D8#;
5734 u00009 : constant Version_32 := 16#156A40CF#;
5735 u00010 : constant Version_32 := 16#033DABE0#;
5736 u00011 : constant Version_32 := 16#6AB38FEA#;
5737 u00012 : constant Version_32 := 16#22B6217D#;
5738 u00013 : constant Version_32 := 16#68A22947#;
5739 u00014 : constant Version_32 := 16#18CC4A56#;
5740 u00015 : constant Version_32 := 16#08258E1B#;
5741 u00016 : constant Version_32 := 16#367D5222#;
5742 u00017 : constant Version_32 := 16#20C9ECA4#;
5743 u00018 : constant Version_32 := 16#50D32CB6#;
5744 u00019 : constant Version_32 := 16#39A8BB77#;
5745 u00020 : constant Version_32 := 16#5CF8FA2B#;
5746 u00021 : constant Version_32 := 16#2F1EB794#;
5747 u00022 : constant Version_32 := 16#31AB6444#;
5748 u00023 : constant Version_32 := 16#1574B6E9#;
5749 u00024 : constant Version_32 := 16#5109C189#;
5750 u00025 : constant Version_32 := 16#56D770CD#;
5751 u00026 : constant Version_32 := 16#02F9DE3D#;
5752 u00027 : constant Version_32 := 16#08AB6B2C#;
5753 u00028 : constant Version_32 := 16#3FA37670#;
5754 u00029 : constant Version_32 := 16#476457A0#;
5755 u00030 : constant Version_32 := 16#731E1B6E#;
5756 u00031 : constant Version_32 := 16#23C2E789#;
5757 u00032 : constant Version_32 := 16#0F1BD6A1#;
5758 u00033 : constant Version_32 := 16#7C25DE96#;
5759 u00034 : constant Version_32 := 16#39ADFFA2#;
5760 u00035 : constant Version_32 := 16#571DE3E7#;
5761 u00036 : constant Version_32 := 16#5EB646AB#;
5762 u00037 : constant Version_32 := 16#4249379B#;
5763 u00038 : constant Version_32 := 16#0357E00A#;
5764 u00039 : constant Version_32 := 16#3784FB72#;
5765 u00040 : constant Version_32 := 16#2E723019#;
5766 u00041 : constant Version_32 := 16#623358EA#;
5767 u00042 : constant Version_32 := 16#107F9465#;
5768 u00043 : constant Version_32 := 16#6843F68A#;
5769 u00044 : constant Version_32 := 16#63305874#;
5770 u00045 : constant Version_32 := 16#31E56CE1#;
5771 u00046 : constant Version_32 := 16#02917970#;
5772 u00047 : constant Version_32 := 16#6CCBA70E#;
5773 u00048 : constant Version_32 := 16#41CD4204#;
5774 u00049 : constant Version_32 := 16#572E3F58#;
5775 u00050 : constant Version_32 := 16#20729FF5#;
5776 u00051 : constant Version_32 := 16#1D4F93E8#;
5777 u00052 : constant Version_32 := 16#30B2EC3D#;
5778 u00053 : constant Version_32 := 16#34054F96#;
5779 u00054 : constant Version_32 := 16#5A199860#;
5780 u00055 : constant Version_32 := 16#0E7F912B#;
5781 u00056 : constant Version_32 := 16#5760634A#;
5782 u00057 : constant Version_32 := 16#5D851835#;
5784 -- The following Export pragmas export the version numbers
5785 -- with symbolic names ending in B (for body) or S
5786 -- (for spec) so that they can be located in a link. The
5787 -- information provided here is sufficient to track down
5788 -- the exact versions of units used in a given build.
5790 pragma Export (C, u00001, "helloB");
5791 pragma Export (C, u00002, "system__standard_libraryB");
5792 pragma Export (C, u00003, "system__standard_libraryS");
5793 pragma Export (C, u00004, "adaS");
5794 pragma Export (C, u00005, "ada__text_ioB");
5795 pragma Export (C, u00006, "ada__text_ioS");
5796 pragma Export (C, u00007, "ada__exceptionsB");
5797 pragma Export (C, u00008, "ada__exceptionsS");
5798 pragma Export (C, u00009, "gnatS");
5799 pragma Export (C, u00010, "gnat__heap_sort_aB");
5800 pragma Export (C, u00011, "gnat__heap_sort_aS");
5801 pragma Export (C, u00012, "systemS");
5802 pragma Export (C, u00013, "system__exception_tableB");
5803 pragma Export (C, u00014, "system__exception_tableS");
5804 pragma Export (C, u00015, "gnat__htableB");
5805 pragma Export (C, u00016, "gnat__htableS");
5806 pragma Export (C, u00017, "system__exceptionsS");
5807 pragma Export (C, u00018, "system__machine_state_operationsB");
5808 pragma Export (C, u00019, "system__machine_state_operationsS");
5809 pragma Export (C, u00020, "system__machine_codeS");
5810 pragma Export (C, u00021, "system__storage_elementsB");
5811 pragma Export (C, u00022, "system__storage_elementsS");
5812 pragma Export (C, u00023, "system__secondary_stackB");
5813 pragma Export (C, u00024, "system__secondary_stackS");
5814 pragma Export (C, u00025, "system__parametersB");
5815 pragma Export (C, u00026, "system__parametersS");
5816 pragma Export (C, u00027, "system__soft_linksB");
5817 pragma Export (C, u00028, "system__soft_linksS");
5818 pragma Export (C, u00029, "system__stack_checkingB");
5819 pragma Export (C, u00030, "system__stack_checkingS");
5820 pragma Export (C, u00031, "system__tracebackB");
5821 pragma Export (C, u00032, "system__tracebackS");
5822 pragma Export (C, u00033, "ada__streamsS");
5823 pragma Export (C, u00034, "ada__tagsB");
5824 pragma Export (C, u00035, "ada__tagsS");
5825 pragma Export (C, u00036, "system__string_opsB");
5826 pragma Export (C, u00037, "system__string_opsS");
5827 pragma Export (C, u00038, "interfacesS");
5828 pragma Export (C, u00039, "interfaces__c_streamsB");
5829 pragma Export (C, u00040, "interfaces__c_streamsS");
5830 pragma Export (C, u00041, "system__file_ioB");
5831 pragma Export (C, u00042, "system__file_ioS");
5832 pragma Export (C, u00043, "ada__finalizationB");
5833 pragma Export (C, u00044, "ada__finalizationS");
5834 pragma Export (C, u00045, "system__finalization_rootB");
5835 pragma Export (C, u00046, "system__finalization_rootS");
5836 pragma Export (C, u00047, "system__finalization_implementationB");
5837 pragma Export (C, u00048, "system__finalization_implementationS");
5838 pragma Export (C, u00049, "system__string_ops_concat_3B");
5839 pragma Export (C, u00050, "system__string_ops_concat_3S");
5840 pragma Export (C, u00051, "system__stream_attributesB");
5841 pragma Export (C, u00052, "system__stream_attributesS");
5842 pragma Export (C, u00053, "ada__io_exceptionsS");
5843 pragma Export (C, u00054, "system__unsigned_typesS");
5844 pragma Export (C, u00055, "system__file_control_blockS");
5845 pragma Export (C, u00056, "ada__finalization__list_controllerB");
5846 pragma Export (C, u00057, "ada__finalization__list_controllerS");
5848 -- BEGIN ELABORATION ORDER
5851 -- gnat.heap_sort_a (spec)
5852 -- gnat.heap_sort_a (body)
5853 -- gnat.htable (spec)
5854 -- gnat.htable (body)
5855 -- interfaces (spec)
5857 -- system.machine_code (spec)
5858 -- system.parameters (spec)
5859 -- system.parameters (body)
5860 -- interfaces.c_streams (spec)
5861 -- interfaces.c_streams (body)
5862 -- system.standard_library (spec)
5863 -- ada.exceptions (spec)
5864 -- system.exception_table (spec)
5865 -- system.exception_table (body)
5866 -- ada.io_exceptions (spec)
5867 -- system.exceptions (spec)
5868 -- system.storage_elements (spec)
5869 -- system.storage_elements (body)
5870 -- system.machine_state_operations (spec)
5871 -- system.machine_state_operations (body)
5872 -- system.secondary_stack (spec)
5873 -- system.stack_checking (spec)
5874 -- system.soft_links (spec)
5875 -- system.soft_links (body)
5876 -- system.stack_checking (body)
5877 -- system.secondary_stack (body)
5878 -- system.standard_library (body)
5879 -- system.string_ops (spec)
5880 -- system.string_ops (body)
5883 -- ada.streams (spec)
5884 -- system.finalization_root (spec)
5885 -- system.finalization_root (body)
5886 -- system.string_ops_concat_3 (spec)
5887 -- system.string_ops_concat_3 (body)
5888 -- system.traceback (spec)
5889 -- system.traceback (body)
5890 -- ada.exceptions (body)
5891 -- system.unsigned_types (spec)
5892 -- system.stream_attributes (spec)
5893 -- system.stream_attributes (body)
5894 -- system.finalization_implementation (spec)
5895 -- system.finalization_implementation (body)
5896 -- ada.finalization (spec)
5897 -- ada.finalization (body)
5898 -- ada.finalization.list_controller (spec)
5899 -- ada.finalization.list_controller (body)
5900 -- system.file_control_block (spec)
5901 -- system.file_io (spec)
5902 -- system.file_io (body)
5903 -- ada.text_io (spec)
5904 -- ada.text_io (body)
5906 -- END ELABORATION ORDER
5910 -- The following source file name pragmas allow the generated file
5911 -- names to be unique for different main programs. They are needed
5912 -- since the package name will always be Ada_Main.
5914 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
5915 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
5917 -- Generated package body for Ada_Main starts here
5919 package body ada_main is
5921 -- The actual finalization is performed by calling the
5922 -- library routine in System.Standard_Library.Adafinal
5924 procedure Do_Finalize;
5925 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
5932 procedure adainit is
5934 -- These booleans are set to True once the associated unit has
5935 -- been elaborated. It is also used to avoid elaborating the
5938 E040 : Boolean; pragma Import (Ada, E040, "interfaces__c_streams_E");
5939 E008 : Boolean; pragma Import (Ada, E008, "ada__exceptions_E");
5940 E014 : Boolean; pragma Import (Ada, E014, "system__exception_table_E");
5941 E053 : Boolean; pragma Import (Ada, E053, "ada__io_exceptions_E");
5942 E017 : Boolean; pragma Import (Ada, E017, "system__exceptions_E");
5943 E024 : Boolean; pragma Import (Ada, E024, "system__secondary_stack_E");
5944 E030 : Boolean; pragma Import (Ada, E030, "system__stack_checking_E");
5945 E028 : Boolean; pragma Import (Ada, E028, "system__soft_links_E");
5946 E035 : Boolean; pragma Import (Ada, E035, "ada__tags_E");
5947 E033 : Boolean; pragma Import (Ada, E033, "ada__streams_E");
5948 E046 : Boolean; pragma Import (Ada, E046, "system__finalization_root_E");
5949 E048 : Boolean; pragma Import (Ada, E048, "system__finalization_implementation_E");
5950 E044 : Boolean; pragma Import (Ada, E044, "ada__finalization_E");
5951 E057 : Boolean; pragma Import (Ada, E057, "ada__finalization__list_controller_E");
5952 E055 : Boolean; pragma Import (Ada, E055, "system__file_control_block_E");
5953 E042 : Boolean; pragma Import (Ada, E042, "system__file_io_E");
5954 E006 : Boolean; pragma Import (Ada, E006, "ada__text_io_E");
5956 -- Set_Globals is a library routine that stores away the
5957 -- value of the indicated set of global values in global
5958 -- variables within the library.
5960 procedure Set_Globals
5961 (Main_Priority : Integer;
5962 Time_Slice_Value : Integer;
5963 WC_Encoding : Character;
5964 Locking_Policy : Character;
5965 Queuing_Policy : Character;
5966 Task_Dispatching_Policy : Character;
5967 Adafinal : System.Address;
5968 Unreserve_All_Interrupts : Integer;
5969 Exception_Tracebacks : Integer);
5970 @findex __gnat_set_globals
5971 pragma Import (C, Set_Globals, "__gnat_set_globals");
5973 -- SDP_Table_Build is a library routine used to build the
5974 -- exception tables. See unit Ada.Exceptions in files
5975 -- a-except.ads/adb for full details of how zero cost
5976 -- exception handling works. This procedure, the call to
5977 -- it, and the two following tables are all omitted if the
5978 -- build is in longjmp/setjump exception mode.
5980 @findex SDP_Table_Build
5981 @findex Zero Cost Exceptions
5982 procedure SDP_Table_Build
5983 (SDP_Addresses : System.Address;
5984 SDP_Count : Natural;
5985 Elab_Addresses : System.Address;
5986 Elab_Addr_Count : Natural);
5987 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
5989 -- Table of Unit_Exception_Table addresses. Used for zero
5990 -- cost exception handling to build the top level table.
5992 ST : aliased constant array (1 .. 23) of System.Address := (
5994 Ada.Text_Io'UET_Address,
5995 Ada.Exceptions'UET_Address,
5996 Gnat.Heap_Sort_A'UET_Address,
5997 System.Exception_Table'UET_Address,
5998 System.Machine_State_Operations'UET_Address,
5999 System.Secondary_Stack'UET_Address,
6000 System.Parameters'UET_Address,
6001 System.Soft_Links'UET_Address,
6002 System.Stack_Checking'UET_Address,
6003 System.Traceback'UET_Address,
6004 Ada.Streams'UET_Address,
6005 Ada.Tags'UET_Address,
6006 System.String_Ops'UET_Address,
6007 Interfaces.C_Streams'UET_Address,
6008 System.File_Io'UET_Address,
6009 Ada.Finalization'UET_Address,
6010 System.Finalization_Root'UET_Address,
6011 System.Finalization_Implementation'UET_Address,
6012 System.String_Ops_Concat_3'UET_Address,
6013 System.Stream_Attributes'UET_Address,
6014 System.File_Control_Block'UET_Address,
6015 Ada.Finalization.List_Controller'UET_Address);
6017 -- Table of addresses of elaboration routines. Used for
6018 -- zero cost exception handling to make sure these
6019 -- addresses are included in the top level procedure
6022 EA : aliased constant array (1 .. 23) of System.Address := (
6023 adainit'Code_Address,
6024 Do_Finalize'Code_Address,
6025 Ada.Exceptions'Elab_Spec'Address,
6026 System.Exceptions'Elab_Spec'Address,
6027 Interfaces.C_Streams'Elab_Spec'Address,
6028 System.Exception_Table'Elab_Body'Address,
6029 Ada.Io_Exceptions'Elab_Spec'Address,
6030 System.Stack_Checking'Elab_Spec'Address,
6031 System.Soft_Links'Elab_Body'Address,
6032 System.Secondary_Stack'Elab_Body'Address,
6033 Ada.Tags'Elab_Spec'Address,
6034 Ada.Tags'Elab_Body'Address,
6035 Ada.Streams'Elab_Spec'Address,
6036 System.Finalization_Root'Elab_Spec'Address,
6037 Ada.Exceptions'Elab_Body'Address,
6038 System.Finalization_Implementation'Elab_Spec'Address,
6039 System.Finalization_Implementation'Elab_Body'Address,
6040 Ada.Finalization'Elab_Spec'Address,
6041 Ada.Finalization.List_Controller'Elab_Spec'Address,
6042 System.File_Control_Block'Elab_Spec'Address,
6043 System.File_Io'Elab_Body'Address,
6044 Ada.Text_Io'Elab_Spec'Address,
6045 Ada.Text_Io'Elab_Body'Address);
6047 -- Start of processing for adainit
6051 -- Call SDP_Table_Build to build the top level procedure
6052 -- table for zero cost exception handling (omitted in
6053 -- longjmp/setjump mode).
6055 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
6057 -- Call Set_Globals to record various information for
6058 -- this partition. The values are derived by the binder
6059 -- from information stored in the ali files by the compiler.
6061 @findex __gnat_set_globals
6063 (Main_Priority => -1,
6064 -- Priority of main program, -1 if no pragma Priority used
6066 Time_Slice_Value => -1,
6067 -- Time slice from Time_Slice pragma, -1 if none used
6070 -- Wide_Character encoding used, default is brackets
6072 Locking_Policy => ' ',
6073 -- Locking_Policy used, default of space means not
6074 -- specified, otherwise it is the first character of
6077 Queuing_Policy => ' ',
6078 -- Queuing_Policy used, default of space means not
6079 -- specified, otherwise it is the first character of
6082 Task_Dispatching_Policy => ' ',
6083 -- Task_Dispatching_Policy used, default of space means
6084 -- not specified, otherwise first character of the
6087 Adafinal => System.Null_Address,
6088 -- Address of Adafinal routine, not used anymore
6090 Unreserve_All_Interrupts => 0,
6091 -- Set true if pragma Unreserve_All_Interrupts was used
6093 Exception_Tracebacks => 0);
6094 -- Indicates if exception tracebacks are enabled
6096 Elab_Final_Code := 1;
6098 -- Now we have the elaboration calls for all units in the partition.
6099 -- The Elab_Spec and Elab_Body attributes generate references to the
6100 -- implicit elaboration procedures generated by the compiler for
6101 -- each unit that requires elaboration.
6104 Interfaces.C_Streams'Elab_Spec;
6108 Ada.Exceptions'Elab_Spec;
6111 System.Exception_Table'Elab_Body;
6115 Ada.Io_Exceptions'Elab_Spec;
6119 System.Exceptions'Elab_Spec;
6123 System.Stack_Checking'Elab_Spec;
6126 System.Soft_Links'Elab_Body;
6131 System.Secondary_Stack'Elab_Body;
6142 Ada.Streams'Elab_Spec;
6146 System.Finalization_Root'Elab_Spec;
6150 Ada.Exceptions'Elab_Body;
6154 System.Finalization_Implementation'Elab_Spec;
6157 System.Finalization_Implementation'Elab_Body;
6161 Ada.Finalization'Elab_Spec;
6165 Ada.Finalization.List_Controller'Elab_Spec;
6169 System.File_Control_Block'Elab_Spec;
6173 System.File_Io'Elab_Body;
6177 Ada.Text_Io'Elab_Spec;
6180 Ada.Text_Io'Elab_Body;
6184 Elab_Final_Code := 0;
6192 procedure adafinal is
6201 -- main is actually a function, as in the ANSI C standard,
6202 -- defined to return the exit status. The three parameters
6203 -- are the argument count, argument values and environment
6206 @findex Main Program
6209 argv : System.Address;
6210 envp : System.Address)
6213 -- The initialize routine performs low level system
6214 -- initialization using a standard library routine which
6215 -- sets up signal handling and performs any other
6216 -- required setup. The routine can be found in file
6219 @findex __gnat_initialize
6220 procedure initialize;
6221 pragma Import (C, initialize, "__gnat_initialize");
6223 -- The finalize routine performs low level system
6224 -- finalization using a standard library routine. The
6225 -- routine is found in file a-final.c and in the standard
6226 -- distribution is a dummy routine that does nothing, so
6227 -- really this is a hook for special user finalization.
6229 @findex __gnat_finalize
6231 pragma Import (C, finalize, "__gnat_finalize");
6233 -- We get to the main program of the partition by using
6234 -- pragma Import because if we try to with the unit and
6235 -- call it Ada style, then not only do we waste time
6236 -- recompiling it, but also, we don't really know the right
6237 -- switches (e.g. identifier character set) to be used
6240 procedure Ada_Main_Program;
6241 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
6243 -- Start of processing for main
6246 -- Save global variables
6252 -- Call low level system initialization
6256 -- Call our generated Ada initialization routine
6260 -- This is the point at which we want the debugger to get
6265 -- Now we call the main program of the partition
6269 -- Perform Ada finalization
6273 -- Perform low level system finalization
6277 -- Return the proper exit status
6278 return (gnat_exit_status);
6281 -- This section is entirely comments, so it has no effect on the
6282 -- compilation of the Ada_Main package. It provides the list of
6283 -- object files and linker options, as well as some standard
6284 -- libraries needed for the link. The gnatlink utility parses
6285 -- this b~hello.adb file to read these comment lines to generate
6286 -- the appropriate command line arguments for the call to the
6287 -- system linker. The BEGIN/END lines are used for sentinels for
6288 -- this parsing operation.
6290 -- The exact file names will of course depend on the environment,
6291 -- host/target and location of files on the host system.
6293 @findex Object file list
6294 -- BEGIN Object file/option list
6297 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
6298 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
6299 -- END Object file/option list
6306 The Ada code in the above example is exactly what is generated by the
6307 binder. We have added comments to more clearly indicate the function
6308 of each part of the generated @code{Ada_Main} package.
6310 The code is standard Ada in all respects, and can be processed by any
6311 tools that handle Ada. In particular, it is possible to use the debugger
6312 in Ada mode to debug the generated Ada_Main package. For example, suppose
6313 that for reasons that you do not understand, your program is blowing up
6314 during elaboration of the body of @code{Ada.Text_IO}. To chase this bug
6315 down, you can place a breakpoint on the call:
6318 Ada.Text_Io'Elab_Body;
6322 and trace the elaboration routine for this package to find out where
6323 the problem might be (more usually of course you would be debugging
6324 elaboration code in your own application).
6326 @node Generating the Binder Program in C
6327 @section Generating the Binder Program in C
6329 In most normal usage, the default mode of @code{gnatbind} which is to
6330 generate the main package in Ada, as described in the previous section.
6331 In particular, this means that any Ada programmer can read and understand
6332 the generated main program. It can also be debugged just like any other
6333 Ada code provided the @code{-g} switch is used for @code{gnatbind}
6334 and @code{gnatlink}.
6336 However for some purposes it may be convenient to generate the main
6337 program in C rather than Ada. This may for example be helpful when you
6338 are generating a mixed language program with the main program in C. The
6339 GNAT compiler itself is an example. The use of the @code{-C} switch
6340 for both @code{gnatbind} and @code{gnatlink} will cause the program to
6341 be generated in C (and compiled using the gnu C compiler). The
6342 following shows the C code generated for the same "Hello World"
6348 #define PARAMS(paramlist) paramlist
6350 #define PARAMS(paramlist) ()
6353 extern void __gnat_set_globals
6354 PARAMS ((int, int, int, int, int, int,
6355 void (*) PARAMS ((void)), int, int));
6356 extern void adafinal PARAMS ((void));
6357 extern void adainit PARAMS ((void));
6358 extern void system__standard_library__adafinal PARAMS ((void));
6359 extern int main PARAMS ((int, char **, char **));
6360 extern void exit PARAMS ((int));
6361 extern void __gnat_break_start PARAMS ((void));
6362 extern void _ada_hello PARAMS ((void));
6363 extern void __gnat_initialize PARAMS ((void));
6364 extern void __gnat_finalize PARAMS ((void));
6366 extern void ada__exceptions___elabs PARAMS ((void));
6367 extern void system__exceptions___elabs PARAMS ((void));
6368 extern void interfaces__c_streams___elabs PARAMS ((void));
6369 extern void system__exception_table___elabb PARAMS ((void));
6370 extern void ada__io_exceptions___elabs PARAMS ((void));
6371 extern void system__stack_checking___elabs PARAMS ((void));
6372 extern void system__soft_links___elabb PARAMS ((void));
6373 extern void system__secondary_stack___elabb PARAMS ((void));
6374 extern void ada__tags___elabs PARAMS ((void));
6375 extern void ada__tags___elabb PARAMS ((void));
6376 extern void ada__streams___elabs PARAMS ((void));
6377 extern void system__finalization_root___elabs PARAMS ((void));
6378 extern void ada__exceptions___elabb PARAMS ((void));
6379 extern void system__finalization_implementation___elabs PARAMS ((void));
6380 extern void system__finalization_implementation___elabb PARAMS ((void));
6381 extern void ada__finalization___elabs PARAMS ((void));
6382 extern void ada__finalization__list_controller___elabs PARAMS ((void));
6383 extern void system__file_control_block___elabs PARAMS ((void));
6384 extern void system__file_io___elabb PARAMS ((void));
6385 extern void ada__text_io___elabs PARAMS ((void));
6386 extern void ada__text_io___elabb PARAMS ((void));
6388 extern int __gnat_inside_elab_final_code;
6390 extern int gnat_argc;
6391 extern char **gnat_argv;
6392 extern char **gnat_envp;
6393 extern int gnat_exit_status;
6395 char __gnat_version[] = "GNAT Version: 3.15w (20010315)";
6397 system__standard_library__adafinal ();
6402 extern char ada__exceptions_E;
6403 extern char system__exceptions_E;
6404 extern char interfaces__c_streams_E;
6405 extern char system__exception_table_E;
6406 extern char ada__io_exceptions_E;
6407 extern char system__secondary_stack_E;
6408 extern char system__stack_checking_E;
6409 extern char system__soft_links_E;
6410 extern char ada__tags_E;
6411 extern char ada__streams_E;
6412 extern char system__finalization_root_E;
6413 extern char system__finalization_implementation_E;
6414 extern char ada__finalization_E;
6415 extern char ada__finalization__list_controller_E;
6416 extern char system__file_control_block_E;
6417 extern char system__file_io_E;
6418 extern char ada__text_io_E;
6420 extern void *__gnat_hello__SDP;
6421 extern void *__gnat_ada__text_io__SDP;
6422 extern void *__gnat_ada__exceptions__SDP;
6423 extern void *__gnat_gnat__heap_sort_a__SDP;
6424 extern void *__gnat_system__exception_table__SDP;
6425 extern void *__gnat_system__machine_state_operations__SDP;
6426 extern void *__gnat_system__secondary_stack__SDP;
6427 extern void *__gnat_system__parameters__SDP;
6428 extern void *__gnat_system__soft_links__SDP;
6429 extern void *__gnat_system__stack_checking__SDP;
6430 extern void *__gnat_system__traceback__SDP;
6431 extern void *__gnat_ada__streams__SDP;
6432 extern void *__gnat_ada__tags__SDP;
6433 extern void *__gnat_system__string_ops__SDP;
6434 extern void *__gnat_interfaces__c_streams__SDP;
6435 extern void *__gnat_system__file_io__SDP;
6436 extern void *__gnat_ada__finalization__SDP;
6437 extern void *__gnat_system__finalization_root__SDP;
6438 extern void *__gnat_system__finalization_implementation__SDP;
6439 extern void *__gnat_system__string_ops_concat_3__SDP;
6440 extern void *__gnat_system__stream_attributes__SDP;
6441 extern void *__gnat_system__file_control_block__SDP;
6442 extern void *__gnat_ada__finalization__list_controller__SDP;
6446 &__gnat_ada__text_io__SDP,
6447 &__gnat_ada__exceptions__SDP,
6448 &__gnat_gnat__heap_sort_a__SDP,
6449 &__gnat_system__exception_table__SDP,
6450 &__gnat_system__machine_state_operations__SDP,
6451 &__gnat_system__secondary_stack__SDP,
6452 &__gnat_system__parameters__SDP,
6453 &__gnat_system__soft_links__SDP,
6454 &__gnat_system__stack_checking__SDP,
6455 &__gnat_system__traceback__SDP,
6456 &__gnat_ada__streams__SDP,
6457 &__gnat_ada__tags__SDP,
6458 &__gnat_system__string_ops__SDP,
6459 &__gnat_interfaces__c_streams__SDP,
6460 &__gnat_system__file_io__SDP,
6461 &__gnat_ada__finalization__SDP,
6462 &__gnat_system__finalization_root__SDP,
6463 &__gnat_system__finalization_implementation__SDP,
6464 &__gnat_system__string_ops_concat_3__SDP,
6465 &__gnat_system__stream_attributes__SDP,
6466 &__gnat_system__file_control_block__SDP,
6467 &__gnat_ada__finalization__list_controller__SDP@};
6469 extern void ada__exceptions___elabs ();
6470 extern void system__exceptions___elabs ();
6471 extern void interfaces__c_streams___elabs ();
6472 extern void system__exception_table___elabb ();
6473 extern void ada__io_exceptions___elabs ();
6474 extern void system__stack_checking___elabs ();
6475 extern void system__soft_links___elabb ();
6476 extern void system__secondary_stack___elabb ();
6477 extern void ada__tags___elabs ();
6478 extern void ada__tags___elabb ();
6479 extern void ada__streams___elabs ();
6480 extern void system__finalization_root___elabs ();
6481 extern void ada__exceptions___elabb ();
6482 extern void system__finalization_implementation___elabs ();
6483 extern void system__finalization_implementation___elabb ();
6484 extern void ada__finalization___elabs ();
6485 extern void ada__finalization__list_controller___elabs ();
6486 extern void system__file_control_block___elabs ();
6487 extern void system__file_io___elabb ();
6488 extern void ada__text_io___elabs ();
6489 extern void ada__text_io___elabb ();
6491 void (*ea[23]) () = @{
6493 system__standard_library__adafinal,
6494 ada__exceptions___elabs,
6495 system__exceptions___elabs,
6496 interfaces__c_streams___elabs,
6497 system__exception_table___elabb,
6498 ada__io_exceptions___elabs,
6499 system__stack_checking___elabs,
6500 system__soft_links___elabb,
6501 system__secondary_stack___elabb,
6504 ada__streams___elabs,
6505 system__finalization_root___elabs,
6506 ada__exceptions___elabb,
6507 system__finalization_implementation___elabs,
6508 system__finalization_implementation___elabb,
6509 ada__finalization___elabs,
6510 ada__finalization__list_controller___elabs,
6511 system__file_control_block___elabs,
6512 system__file_io___elabb,
6513 ada__text_io___elabs,
6514 ada__text_io___elabb@};
6516 __gnat_SDP_Table_Build (&st, 23, ea, 23);
6517 __gnat_set_globals (
6518 -1, /* Main_Priority */
6519 -1, /* Time_Slice_Value */
6520 'b', /* WC_Encoding */
6521 ' ', /* Locking_Policy */
6522 ' ', /* Queuing_Policy */
6523 ' ', /* Tasking_Dispatching_Policy */
6524 0, /* Finalization routine address, not used anymore */
6525 0, /* Unreserve_All_Interrupts */
6526 0); /* Exception_Tracebacks */
6528 __gnat_inside_elab_final_code = 1;
6530 if (ada__exceptions_E == 0) @{
6531 ada__exceptions___elabs ();
6533 if (system__exceptions_E == 0) @{
6534 system__exceptions___elabs ();
6535 system__exceptions_E++;
6537 if (interfaces__c_streams_E == 0) @{
6538 interfaces__c_streams___elabs ();
6540 interfaces__c_streams_E = 1;
6541 if (system__exception_table_E == 0) @{
6542 system__exception_table___elabb ();
6543 system__exception_table_E++;
6545 if (ada__io_exceptions_E == 0) @{
6546 ada__io_exceptions___elabs ();
6547 ada__io_exceptions_E++;
6549 if (system__stack_checking_E == 0) @{
6550 system__stack_checking___elabs ();
6552 if (system__soft_links_E == 0) @{
6553 system__soft_links___elabb ();
6554 system__soft_links_E++;
6556 system__stack_checking_E = 1;
6557 if (system__secondary_stack_E == 0) @{
6558 system__secondary_stack___elabb ();
6559 system__secondary_stack_E++;
6561 if (ada__tags_E == 0) @{
6562 ada__tags___elabs ();
6564 if (ada__tags_E == 0) @{
6565 ada__tags___elabb ();
6568 if (ada__streams_E == 0) @{
6569 ada__streams___elabs ();
6572 if (system__finalization_root_E == 0) @{
6573 system__finalization_root___elabs ();
6575 system__finalization_root_E = 1;
6576 if (ada__exceptions_E == 0) @{
6577 ada__exceptions___elabb ();
6578 ada__exceptions_E++;
6580 if (system__finalization_implementation_E == 0) @{
6581 system__finalization_implementation___elabs ();
6583 if (system__finalization_implementation_E == 0) @{
6584 system__finalization_implementation___elabb ();
6585 system__finalization_implementation_E++;
6587 if (ada__finalization_E == 0) @{
6588 ada__finalization___elabs ();
6590 ada__finalization_E = 1;
6591 if (ada__finalization__list_controller_E == 0) @{
6592 ada__finalization__list_controller___elabs ();
6594 ada__finalization__list_controller_E = 1;
6595 if (system__file_control_block_E == 0) @{
6596 system__file_control_block___elabs ();
6597 system__file_control_block_E++;
6599 if (system__file_io_E == 0) @{
6600 system__file_io___elabb ();
6601 system__file_io_E++;
6603 if (ada__text_io_E == 0) @{
6604 ada__text_io___elabs ();
6606 if (ada__text_io_E == 0) @{
6607 ada__text_io___elabb ();
6611 __gnat_inside_elab_final_code = 0;
6613 int main (argc, argv, envp)
6622 __gnat_initialize ();
6624 __gnat_break_start ();
6628 system__standard_library__adafinal ();
6630 exit (gnat_exit_status);
6632 unsigned helloB = 0x7880BEB3;
6633 unsigned system__standard_libraryB = 0x0D24CBD0;
6634 unsigned system__standard_libraryS = 0x3283DBEB;
6635 unsigned adaS = 0x2359F9ED;
6636 unsigned ada__text_ioB = 0x47C85FC4;
6637 unsigned ada__text_ioS = 0x496FE45C;
6638 unsigned ada__exceptionsB = 0x74F50187;
6639 unsigned ada__exceptionsS = 0x6736945B;
6640 unsigned gnatS = 0x156A40CF;
6641 unsigned gnat__heap_sort_aB = 0x033DABE0;
6642 unsigned gnat__heap_sort_aS = 0x6AB38FEA;
6643 unsigned systemS = 0x0331C6FE;
6644 unsigned system__exceptionsS = 0x20C9ECA4;
6645 unsigned system__exception_tableB = 0x68A22947;
6646 unsigned system__exception_tableS = 0x394BADD5;
6647 unsigned gnat__htableB = 0x08258E1B;
6648 unsigned gnat__htableS = 0x367D5222;
6649 unsigned system__machine_state_operationsB = 0x4F3B7492;
6650 unsigned system__machine_state_operationsS = 0x182F5CF4;
6651 unsigned system__storage_elementsB = 0x2F1EB794;
6652 unsigned system__storage_elementsS = 0x102C83C7;
6653 unsigned system__secondary_stackB = 0x1574B6E9;
6654 unsigned system__secondary_stackS = 0x708E260A;
6655 unsigned system__parametersB = 0x56D770CD;
6656 unsigned system__parametersS = 0x237E39BE;
6657 unsigned system__soft_linksB = 0x08AB6B2C;
6658 unsigned system__soft_linksS = 0x1E2491F3;
6659 unsigned system__stack_checkingB = 0x476457A0;
6660 unsigned system__stack_checkingS = 0x5299FCED;
6661 unsigned system__tracebackB = 0x2971EBDE;
6662 unsigned system__tracebackS = 0x2E9C3122;
6663 unsigned ada__streamsS = 0x7C25DE96;
6664 unsigned ada__tagsB = 0x39ADFFA2;
6665 unsigned ada__tagsS = 0x769A0464;
6666 unsigned system__string_opsB = 0x5EB646AB;
6667 unsigned system__string_opsS = 0x63CED018;
6668 unsigned interfacesS = 0x0357E00A;
6669 unsigned interfaces__c_streamsB = 0x3784FB72;
6670 unsigned interfaces__c_streamsS = 0x2E723019;
6671 unsigned system__file_ioB = 0x623358EA;
6672 unsigned system__file_ioS = 0x31F873E6;
6673 unsigned ada__finalizationB = 0x6843F68A;
6674 unsigned ada__finalizationS = 0x63305874;
6675 unsigned system__finalization_rootB = 0x31E56CE1;
6676 unsigned system__finalization_rootS = 0x23169EF3;
6677 unsigned system__finalization_implementationB = 0x6CCBA70E;
6678 unsigned system__finalization_implementationS = 0x604AA587;
6679 unsigned system__string_ops_concat_3B = 0x572E3F58;
6680 unsigned system__string_ops_concat_3S = 0x01F57876;
6681 unsigned system__stream_attributesB = 0x1D4F93E8;
6682 unsigned system__stream_attributesS = 0x30B2EC3D;
6683 unsigned ada__io_exceptionsS = 0x34054F96;
6684 unsigned system__unsigned_typesS = 0x7B9E7FE3;
6685 unsigned system__file_control_blockS = 0x2FF876A8;
6686 unsigned ada__finalization__list_controllerB = 0x5760634A;
6687 unsigned ada__finalization__list_controllerS = 0x5D851835;
6689 /* BEGIN ELABORATION ORDER
6692 gnat.heap_sort_a (spec)
6697 system.parameters (spec)
6698 system.standard_library (spec)
6699 ada.exceptions (spec)
6700 system.exceptions (spec)
6701 system.parameters (body)
6702 gnat.heap_sort_a (body)
6703 interfaces.c_streams (spec)
6704 interfaces.c_streams (body)
6705 system.exception_table (spec)
6706 system.exception_table (body)
6707 ada.io_exceptions (spec)
6708 system.storage_elements (spec)
6709 system.storage_elements (body)
6710 system.machine_state_operations (spec)
6711 system.machine_state_operations (body)
6712 system.secondary_stack (spec)
6713 system.stack_checking (spec)
6714 system.soft_links (spec)
6715 system.soft_links (body)
6716 system.stack_checking (body)
6717 system.secondary_stack (body)
6718 system.standard_library (body)
6719 system.string_ops (spec)
6720 system.string_ops (body)
6724 system.finalization_root (spec)
6725 system.finalization_root (body)
6726 system.string_ops_concat_3 (spec)
6727 system.string_ops_concat_3 (body)
6728 system.traceback (spec)
6729 system.traceback (body)
6730 ada.exceptions (body)
6731 system.unsigned_types (spec)
6732 system.stream_attributes (spec)
6733 system.stream_attributes (body)
6734 system.finalization_implementation (spec)
6735 system.finalization_implementation (body)
6736 ada.finalization (spec)
6737 ada.finalization (body)
6738 ada.finalization.list_controller (spec)
6739 ada.finalization.list_controller (body)
6740 system.file_control_block (spec)
6741 system.file_io (spec)
6742 system.file_io (body)
6746 END ELABORATION ORDER */
6748 /* BEGIN Object file/option list
6751 -L/usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/
6752 /usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/libgnat.a
6754 END Object file/option list */
6759 Here again, the C code is exactly what is generated by the binder. The
6760 functions of the various parts of this code correspond in an obvious
6761 manner with the commented Ada code shown in the example in the previous
6764 @node Consistency-Checking Modes
6765 @section Consistency-Checking Modes
6768 As described in the previous section, by default @code{gnatbind} checks
6769 that object files are consistent with one another and are consistent
6770 with any source files it can locate. The following switches control binder
6774 @item ^-s^/READ_SOURCES=ALL^
6775 @cindex @code{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
6776 Require source files to be present. In this mode, the binder must be
6777 able to locate all source files that are referenced, in order to check
6778 their consistency. In normal mode, if a source file cannot be located it
6779 is simply ignored. If you specify this switch, a missing source
6782 @item ^-x^/READ_SOURCES=NONE^
6783 @cindex @code{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
6784 Exclude source files. In this mode, the binder only checks that ALI
6785 files are consistent with one another. Source files are not accessed.
6786 The binder runs faster in this mode, and there is still a guarantee that
6787 the resulting program is self-consistent.
6788 If a source file has been edited since it was last compiled, and you
6789 specify this switch, the binder will not detect that the object
6790 file is out of date with respect to the source file. Note that this is the
6791 mode that is automatically used by @code{gnatmake} because in this
6792 case the checking against sources has already been performed by
6793 @code{gnatmake} in the course of compilation (i.e. before binding).
6796 @item /READ_SOURCES=AVAILABLE
6797 This is the default mode in which source files are checked if they are
6798 available, and ignored if they are not available.
6802 @node Binder Error Message Control
6803 @section Binder Error Message Control
6806 The following switches provide control over the generation of error
6807 messages from the binder:
6810 @item ^-v^/REPORT_ERRORS=VERBOSE^
6811 @cindex @code{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
6812 Verbose mode. In the normal mode, brief error messages are generated to
6813 @file{stderr}. If this switch is present, a header is written
6814 to @file{stdout} and any error messages are directed to @file{stdout}.
6815 All that is written to @file{stderr} is a brief summary message.
6817 @item ^-b^/REPORT_ERRORS=BRIEF^
6818 @cindex @code{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
6819 Generate brief error messages to @file{stderr} even if verbose mode is
6820 specified. This is relevant only when used with the
6821 @code{^-v^/REPORT_ERRORS=VERBOSE^} switch.
6825 @cindex @code{-m} (@code{gnatbind})
6826 Limits the number of error messages to @var{n}, a decimal integer in the
6827 range 1-999. The binder terminates immediately if this limit is reached.
6830 @cindex @code{-M} (@code{gnatbind})
6831 Renames the generated main program from @code{main} to @code{xxx}.
6832 This is useful in the case of some cross-building environments, where
6833 the actual main program is separate from the one generated
6837 @item ^-ws^/WARNINGS=SUPPRESS^
6838 @cindex @code{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
6840 Suppress all warning messages.
6842 @item ^-we^/WARNINGS=ERROR^
6843 @cindex @code{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
6844 Treat any warning messages as fatal errors.
6847 @item /WARNINGS=NORMAL
6848 Standard mode with warnings generated, but warnings do not get treated
6852 @item ^-t^/NOTIME_STAMP_CHECK^
6853 @cindex @code{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
6854 @cindex Time stamp checks, in binder
6855 @cindex Binder consistency checks
6856 @cindex Consistency checks, in binder
6857 The binder performs a number of consistency checks including:
6861 Check that time stamps of a given source unit are consistent
6863 Check that checksums of a given source unit are consistent
6865 Check that consistent versions of @code{GNAT} were used for compilation
6867 Check consistency of configuration pragmas as required
6871 Normally failure of such checks, in accordance with the consistency
6872 requirements of the Ada Reference Manual, causes error messages to be
6873 generated which abort the binder and prevent the output of a binder
6874 file and subsequent link to obtain an executable.
6876 The @code{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
6877 into warnings, so that
6878 binding and linking can continue to completion even in the presence of such
6879 errors. The result may be a failed link (due to missing symbols), or a
6880 non-functional executable which has undefined semantics.
6881 @emph{This means that
6882 @code{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
6886 @node Elaboration Control
6887 @section Elaboration Control
6890 The following switches provide additional control over the elaboration
6891 order. For full details see @xref{Elaboration Order Handling in GNAT}.
6894 @item ^-p^/PESSIMISTIC_ELABORATION^
6895 @cindex @code{^-h^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
6896 Normally the binder attempts to choose an elaboration order that is
6897 likely to minimize the likelihood of an elaboration order error resulting
6898 in raising a @code{Program_Error} exception. This switch reverses the
6899 action of the binder, and requests that it deliberately choose an order
6900 that is likely to maximize the likelihood of an elaboration error.
6901 This is useful in ensuring portability and avoiding dependence on
6902 accidental fortuitous elaboration ordering.
6904 Normally it only makes sense to use the @code{-p} switch if dynamic
6905 elaboration checking is used (@option{-gnatE} switch used for compilation).
6906 This is because in the default static elaboration mode, all necessary
6907 @code{Elaborate_All} pragmas are implicitly inserted. These implicit
6908 pragmas are still respected by the binder in @code{-p} mode, so a
6909 safe elaboration order is assured.
6912 @node Output Control
6913 @section Output Control
6916 The following switches allow additional control over the output
6917 generated by the binder.
6921 @item ^-A^/BIND_FILE=ADA^
6922 @cindex @code{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
6923 Generate binder program in Ada (default). The binder program is named
6924 @file{b~@var{mainprog}.adb} by default. This can be changed with
6925 @code{-o} @code{gnatbind} option.
6927 @item ^-c^/NOOUTPUT^
6928 @cindex @code{^-c^/NOOUTPUT^} (@code{gnatbind})
6929 Check only. Do not generate the binder output file. In this mode the
6930 binder performs all error checks but does not generate an output file.
6932 @item ^-C^/BIND_FILE=C^
6933 @cindex @code{^-C^/BIND_FILE=C^} (@code{gnatbind})
6934 Generate binder program in C. The binder program is named
6935 @file{b_@var{mainprog}.c}. This can be changed with @code{-o} @code{gnatbind}
6938 @item ^-e^/ELABORATION_DEPENDENCIES^
6939 @cindex @code{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
6940 Output complete list of elaboration-order dependencies, showing the
6941 reason for each dependency. This output can be rather extensive but may
6942 be useful in diagnosing problems with elaboration order. The output is
6943 written to @file{stdout}.
6946 @cindex @code{^-h^/HELP^} (@code{gnatbind})
6947 Output usage information. The output is written to @file{stdout}.
6949 @item ^-K^/LINKER_OPTION_LIST^
6950 @cindex @code{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
6951 Output linker options to @file{stdout}. Includes library search paths,
6952 contents of pragmas Ident and Linker_Options, and libraries added
6955 @item ^-l^/ORDER_OF_ELABORATION^
6956 @cindex @code{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
6957 Output chosen elaboration order. The output is written to @file{stdout}.
6959 @item ^-O^/OBJECT_LIST^
6960 @cindex @code{^-O^/OBJECT_LIST^} (@code{gnatbind})
6961 Output full names of all the object files that must be linked to provide
6962 the Ada component of the program. The output is written to @file{stdout}.
6963 This list includes the files explicitly supplied and referenced by the user
6964 as well as implicitly referenced run-time unit files. The latter are
6965 omitted if the corresponding units reside in shared libraries. The
6966 directory names for the run-time units depend on the system configuration.
6968 @item ^-o ^/OUTPUT=^@var{file}
6969 @cindex @code{^-o^/OUTPUT^} (@code{gnatbind})
6970 Set name of output file to @var{file} instead of the normal
6971 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
6972 binder generated body filename. In C mode you would normally give
6973 @var{file} an extension of @file{.c} because it will be a C source program.
6974 Note that if this option is used, then linking must be done manually.
6975 It is not possible to use gnatlink in this case, since it cannot locate
6978 @item ^-r^/RESTRICTION_LIST^
6979 @cindex @code{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
6980 Generate list of @code{pragma Rerstrictions} that could be applied to
6981 the current unit. This is useful for code audit purposes, and also may
6982 be used to improve code generation in some cases.
6986 @node Binding with Non-Ada Main Programs
6987 @section Binding with Non-Ada Main Programs
6990 In our description so far we have assumed that the main
6991 program is in Ada, and that the task of the binder is to generate a
6992 corresponding function @code{main} that invokes this Ada main
6993 program. GNAT also supports the building of executable programs where
6994 the main program is not in Ada, but some of the called routines are
6995 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
6996 The following switch is used in this situation:
7000 @cindex @code{^-n^/NOMAIN^} (@code{gnatbind})
7001 No main program. The main program is not in Ada.
7005 In this case, most of the functions of the binder are still required,
7006 but instead of generating a main program, the binder generates a file
7007 containing the following callable routines:
7012 You must call this routine to initialize the Ada part of the program by
7013 calling the necessary elaboration routines. A call to @code{adainit} is
7014 required before the first call to an Ada subprogram.
7016 Note that it is assumed that the basic execution environment must be setup
7017 to be appropriate for Ada execution at the point where the first Ada
7018 subprogram is called. In particular, if the Ada code will do any
7019 floating-point operations, then the FPU must be setup in an appropriate
7020 manner. For the case of the x86, for example, full precision mode is
7021 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7022 that the FPU is in the right state.
7026 You must call this routine to perform any library-level finalization
7027 required by the Ada subprograms. A call to @code{adafinal} is required
7028 after the last call to an Ada subprogram, and before the program
7033 If the @code{^-n^/NOMAIN^} switch
7034 @cindex Binder, multiple input files
7035 is given, more than one ALI file may appear on
7036 the command line for @code{gnatbind}. The normal @dfn{closure}
7037 calculation is performed for each of the specified units. Calculating
7038 the closure means finding out the set of units involved by tracing
7039 @code{with} references. The reason it is necessary to be able to
7040 specify more than one ALI file is that a given program may invoke two or
7041 more quite separate groups of Ada units.
7043 The binder takes the name of its output file from the last specified ALI
7044 file, unless overridden by the use of the @code{^-o file^/OUTPUT=file^}.
7045 The output is an Ada unit in source form that can
7046 be compiled with GNAT unless the -C switch is used in which case the
7047 output is a C source file, which must be compiled using the C compiler.
7048 This compilation occurs automatically as part of the @code{gnatlink}
7051 Currently the GNAT run time requires a FPU using 80 bits mode
7052 precision. Under targets where this is not the default it is required to
7053 call GNAT.Float_Control.Reset before using floating point numbers (this
7054 include float computation, float input and output) in the Ada code. A
7055 side effect is that this could be the wrong mode for the foreign code
7056 where floating point computation could be broken after this call.
7058 @node Binding Programs with No Main Subprogram
7059 @section Binding Programs with No Main Subprogram
7062 It is possible to have an Ada program which does not have a main
7063 subprogram. This program will call the elaboration routines of all the
7064 packages, then the finalization routines.
7066 The following switch is used to bind programs organized in this manner:
7069 @item ^-z^/ZERO_MAIN^
7070 @cindex @code{^-z^/ZERO_MAIN^} (@code{gnatbind})
7071 Normally the binder checks that the unit name given on the command line
7072 corresponds to a suitable main subprogram. When this switch is used,
7073 a list of ALI files can be given, and the execution of the program
7074 consists of elaboration of these units in an appropriate order.
7077 @node Summary of Binder Switches
7078 @section Summary of Binder Switches
7081 The following are the switches available with @code{gnatbind}:
7084 @item ^-aO^/OBJECT_SEARCH^
7085 Specify directory to be searched for ALI files.
7087 @item ^-aI^/SOURCE_SEARCH^
7088 Specify directory to be searched for source file.
7090 @item ^-A^/BIND_FILE=ADA^
7091 Generate binder program in Ada (default)
7093 @item ^-b^/REPORT_ERRORS=BRIEF^
7094 Generate brief messages to @file{stderr} even if verbose mode set.
7096 @item ^-c^/NOOUTPUT^
7097 Check only, no generation of binder output file.
7099 @item ^-C^/BIND_FILE=C^
7100 Generate binder program in C
7102 @item ^-e^/ELABORATION_DEPENDENCIES^
7103 Output complete list of elaboration-order dependencies.
7106 Store tracebacks in exception occurrences when the target supports it.
7107 This is the default with the zero cost exception mechanism.
7108 This option is currently supported on the following targets:
7109 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7110 See also the packages @code{GNAT.Traceback} and
7111 @code{GNAT.Traceback.Symbolic} for more information.
7112 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
7116 Output usage (help) information
7119 Specify directory to be searched for source and ALI files.
7121 @item ^-I-^/NOCURRENT_DIRECTORY^
7122 Do not look for sources in the current directory where @code{gnatbind} was
7123 invoked, and do not look for ALI files in the directory containing the
7124 ALI file named in the @code{gnatbind} command line.
7126 @item ^-l^/ORDER_OF_ELABORATION^
7127 Output chosen elaboration order.
7130 Binds the units for library building. In this case the adainit and
7131 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
7132 are renamed to xxxinit and xxxfinal. Implies -n.
7134 See @pxref{GNAT and Libraries} for more details.
7138 Rename generated main program from main to xyz
7140 @item ^-m^/ERROR_LIMIT=^@var{n}
7141 Limit number of detected errors to @var{n} (1-999).
7143 Furthermore, under Windows, the sources pointed to by the libraries path
7144 set in the registry are not searched for.
7151 Do not look for sources in the system default directory.
7154 Do not look for library files in the system default directory.
7156 @item --RTS=@var{rts-path}
7157 @cindex @code{--RTS} (@code{gnatbind})
7158 Specifies the default location of the runtime library. Same meaning as the
7159 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
7161 @item ^-o ^/OUTPUT=^@var{file}
7162 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7163 Note that if this option is used, then linking must be done manually,
7164 gnatlink cannot be used.
7166 @item ^-O^/OBJECT_LIST^
7170 Pessimistic (worst-case) elaboration order
7172 @item ^-s^/READ_SOURCES=ALL^
7173 Require all source files to be present.
7177 Link against a static GNAT run time.
7180 Link against a shared GNAT run time when available.
7183 @item ^-t^/NOTIME_STAMP_CHECK^
7184 Tolerate time stamp and other consistency errors
7187 Set the time slice value to n microseconds. A value of zero means no time
7188 slicing and also indicates to the tasking run time to match as close as
7189 possible to the annex D requirements of the RM.
7191 @item ^-v^/REPORT_ERRORS=VERBOSE^
7192 Verbose mode. Write error messages, header, summary output to
7197 Warning mode (@var{x}=s/e for suppress/treat as error)
7201 @item /WARNINGS=NORMAL
7202 Normal warnings mode. Warnings are issued but ignored
7204 @item /WARNINGS=SUPPRESS
7205 All warning messages are suppressed
7207 @item /WARNINGS=ERROR
7208 Warning messages are treated as fatal errors
7211 @item ^-x^/READ_SOURCES=NONE^
7212 Exclude source files (check object consistency only).
7215 @item /READ_SOURCES=AVAILABLE
7216 Default mode, in which sources are checked for consistency only if
7220 @item ^-z^/ZERO_MAIN^
7226 You may obtain this listing by running the program @code{gnatbind} with
7230 @node Command-Line Access
7231 @section Command-Line Access
7234 The package @code{Ada.Command_Line} provides access to the command-line
7235 arguments and program name. In order for this interface to operate
7236 correctly, the two variables
7250 are declared in one of the GNAT library routines. These variables must
7251 be set from the actual @code{argc} and @code{argv} values passed to the
7252 main program. With no @code{^n^/NOMAIN^} present, @code{gnatbind}
7253 generates the C main program to automatically set these variables.
7254 If the @code{^n^/NOMAIN^} switch is used, there is no automatic way to
7255 set these variables. If they are not set, the procedures in
7256 @code{Ada.Command_Line} will not be available, and any attempt to use
7257 them will raise @code{Constraint_Error}. If command line access is
7258 required, your main program must set @code{gnat_argc} and
7259 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7262 @node Search Paths for gnatbind
7263 @section Search Paths for @code{gnatbind}
7266 The binder takes the name of an ALI file as its argument and needs to
7267 locate source files as well as other ALI files to verify object consistency.
7269 For source files, it follows exactly the same search rules as @code{gcc}
7270 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7271 directories searched are:
7275 The directory containing the ALI file named in the command line, unless
7276 the switch @code{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7279 All directories specified by @code{^-I^/SEARCH^}
7280 switches on the @code{gnatbind}
7281 command line, in the order given.
7284 @findex ADA_OBJECTS_PATH
7285 Each of the directories listed in the value of the
7286 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7288 Construct this value
7289 exactly as the @code{PATH} environment variable: a list of directory
7290 names separated by colons (semicolons when working with the NT version
7294 Normally, define this value as a logical name containing a comma separated
7295 list of directory names.
7297 This variable can also be defined by means of an environment string
7298 (an argument to the DEC C exec* set of functions).
7302 DEFINE ANOTHER_PATH FOO:[BAG]
7303 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7306 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7307 first, followed by the standard Ada 95
7308 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7309 If this is not redefined, the user will obtain the DEC Ada83 IO packages
7310 (Text_IO, Sequential_IO, etc)
7311 instead of the Ada95 packages. Thus, in order to get the Ada 95
7312 packages by default, ADA_OBJECTS_PATH must be redefined.
7316 The content of the "ada_object_path" file which is part of the GNAT
7317 installation tree and is used to store standard libraries such as the
7318 GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is
7321 @ref{Installing an Ada Library}
7326 In the binder the switch @code{^-I^/SEARCH^}
7327 is used to specify both source and
7328 library file paths. Use @code{^-aI^/SOURCE_SEARCH^}
7329 instead if you want to specify
7330 source paths only, and @code{^-aO^/LIBRARY_SEARCH^}
7331 if you want to specify library paths
7332 only. This means that for the binder
7333 @code{^-I^/SEARCH=^}@var{dir} is equivalent to
7334 @code{^-aI^/SOURCE_SEARCH=^}@var{dir}
7335 @code{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7336 The binder generates the bind file (a C language source file) in the
7337 current working directory.
7343 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7344 children make up the GNAT Run-Time Library, together with the package
7345 GNAT and its children, which contain a set of useful additional
7346 library functions provided by GNAT. The sources for these units are
7347 needed by the compiler and are kept together in one directory. The ALI
7348 files and object files generated by compiling the RTL are needed by the
7349 binder and the linker and are kept together in one directory, typically
7350 different from the directory containing the sources. In a normal
7351 installation, you need not specify these directory names when compiling
7352 or binding. Either the environment variables or the built-in defaults
7353 cause these files to be found.
7355 Besides simplifying access to the RTL, a major use of search paths is
7356 in compiling sources from multiple directories. This can make
7357 development environments much more flexible.
7359 @node Examples of gnatbind Usage
7360 @section Examples of @code{gnatbind} Usage
7363 This section contains a number of examples of using the GNAT binding
7364 utility @code{gnatbind}.
7367 @item gnatbind hello
7368 The main program @code{Hello} (source program in @file{hello.adb}) is
7369 bound using the standard switch settings. The generated main program is
7370 @file{b~hello.adb}. This is the normal, default use of the binder.
7373 @item gnatbind hello -o mainprog.adb
7376 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7378 The main program @code{Hello} (source program in @file{hello.adb}) is
7379 bound using the standard switch settings. The generated main program is
7380 @file{mainprog.adb} with the associated spec in
7381 @file{mainprog.ads}. Note that you must specify the body here not the
7382 spec, in the case where the output is in Ada. Note that if this option
7383 is used, then linking must be done manually, since gnatlink will not
7384 be able to find the generated file.
7387 @item gnatbind main -C -o mainprog.c -x
7390 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7392 The main program @code{Main} (source program in
7393 @file{main.adb}) is bound, excluding source files from the
7394 consistency checking, generating
7395 the file @file{mainprog.c}.
7398 @item gnatbind -x main_program -C -o mainprog.c
7399 This command is exactly the same as the previous example. Switches may
7400 appear anywhere in the command line, and single letter switches may be
7401 combined into a single switch.
7405 @item gnatbind -n math dbase -C -o ada-control.c
7408 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7410 The main program is in a language other than Ada, but calls to
7411 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7412 to @code{gnatbind} generates the file @file{ada-control.c} containing
7413 the @code{adainit} and @code{adafinal} routines to be called before and
7414 after accessing the Ada units.
7417 @node Linking Using gnatlink
7418 @chapter Linking Using @code{gnatlink}
7422 This chapter discusses @code{gnatlink}, a utility program used to link
7423 Ada programs and build an executable file. This is a simple program
7424 that invokes the Unix linker (via the @code{gcc}
7425 command) with a correct list of object files and library references.
7426 @code{gnatlink} automatically determines the list of files and
7427 references for the Ada part of a program. It uses the binder file
7428 generated by the binder to determine this list.
7431 * Running gnatlink::
7432 * Switches for gnatlink::
7433 * Setting Stack Size from gnatlink::
7434 * Setting Heap Size from gnatlink::
7437 @node Running gnatlink
7438 @section Running @code{gnatlink}
7441 The form of the @code{gnatlink} command is
7444 $ gnatlink [@var{switches}] @var{mainprog}[.ali] [@var{non-Ada objects}]
7445 [@var{linker options}]
7449 @file{@var{mainprog}.ali} references the ALI file of the main program.
7450 The @file{.ali} extension of this file can be omitted. From this
7451 reference, @code{gnatlink} locates the corresponding binder file
7452 @file{b~@var{mainprog}.adb} and, using the information in this file along
7453 with the list of non-Ada objects and linker options, constructs a Unix
7454 linker command file to create the executable.
7456 The arguments following @file{@var{mainprog}.ali} are passed to the
7457 linker uninterpreted. They typically include the names of object files
7458 for units written in other languages than Ada and any library references
7459 required to resolve references in any of these foreign language units,
7460 or in @code{pragma Import} statements in any Ada units.
7462 @var{linker options} is an optional list of linker specific
7463 switches. The default linker called by gnatlink is @var{gcc} which in
7464 turn calls the appropriate system linker usually called
7465 @var{ld}. Standard options for the linker such as @code{-lmy_lib} or
7466 @code{-Ldir} can be added as is. For options that are not recognized by
7467 @var{gcc} as linker options, the @var{gcc} switches @code{-Xlinker} or
7468 @code{-Wl,} shall be used. Refer to the GCC documentation for
7469 details. Here is an example showing how to generate a linker map
7470 assuming that the underlying linker is GNU ld:
7473 $ gnatlink my_prog -Wl,-Map,MAPFILE
7476 Using @var{linker options} it is possible to set the program stack and
7477 heap size. See @pxref{Setting Stack Size from gnatlink} and
7478 @pxref{Setting Heap Size from gnatlink}.
7480 @code{gnatlink} determines the list of objects required by the Ada
7481 program and prepends them to the list of objects passed to the linker.
7482 @code{gnatlink} also gathers any arguments set by the use of
7483 @code{pragma Linker_Options} and adds them to the list of arguments
7484 presented to the linker.
7487 @code{gnatlink} accepts the following types of extra files on the command
7488 line: objects (.OBJ), libraries (.OLB), shareable images (.EXE), and
7489 options files (.OPT). These are recognized and handled according to their
7493 @node Switches for gnatlink
7494 @section Switches for @code{gnatlink}
7497 The following switches are available with the @code{gnatlink} utility:
7501 @item ^-A^/BIND_FILE=ADA^
7502 @cindex @code{^-A^/BIND_FILE=ADA^} (@code{gnatlink})
7503 The binder has generated code in Ada. This is the default.
7505 @item ^-C^/BIND_FILE=C^
7506 @cindex @code{^-C^/BIND_FILE=C^} (@code{gnatlink})
7507 If instead of generating a file in Ada, the binder has generated one in
7508 C, then the linker needs to know about it. Use this switch to signal
7509 to @code{gnatlink} that the binder has generated C code rather than
7513 @cindex Command line length
7514 @cindex @code{-f} (@code{gnatlink})
7515 On some targets, the command line length is limited, and @code{gnatlink}
7516 will generate a separate file for the linker if the list of object files
7517 is too long. The @code{-f} flag forces this file to be generated even if
7518 the limit is not exceeded. This is useful in some cases to deal with
7519 special situations where the command line length is exceeded.
7522 @cindex Debugging information, including
7523 @cindex @code{^-g^/DEBUG^} (@code{gnatlink})
7524 The option to include debugging information causes the Ada bind file (in
7525 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7527 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7528 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7529 Without @code{^-g^/DEBUG^}, the binder removes these files by
7530 default. The same procedure apply if a C bind file was generated using
7531 @code{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames are
7532 @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7536 @cindex @code{-n} (@code{gnatlink})
7537 Do not compile the file generated by the binder. This may be used when
7538 a link is rerun with different options, but there is no need to recompile
7543 @cindex @code{^-v^/VERBOSE^} (@code{gnatlink})
7544 Causes additional information to be output, including a full list of the
7545 included object files. This switch option is most useful when you want
7546 to see what set of object files are being used in the link step.
7550 @cindex @code{-v -v} (@code{gnatlink})
7551 Very verbose mode. Requests that the compiler operate in verbose mode when
7552 it compiles the binder file, and that the system linker run in verbose mode.
7555 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7556 @cindex @code{^-o^/EXECUTABLE^} (@code{gnatlink})
7557 @var{exec-name} specifies an alternate name for the generated
7558 executable program. If this switch is omitted, the executable has the same
7559 name as the main unit. For example, @code{gnatlink try.ali} creates
7560 an executable called @file{^try^TRY.EXE^}.
7563 @item -b @var{target}
7564 @cindex @code{-b} (@code{gnatlink})
7565 Compile your program to run on @var{target}, which is the name of a
7566 system configuration. You must have a GNAT cross-compiler built if
7567 @var{target} is not the same as your host system.
7570 @cindex @code{-B} (@code{gnatlink})
7571 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
7572 from @var{dir} instead of the default location. Only use this switch
7573 when multiple versions of the GNAT compiler are available. See the
7574 @code{gcc} manual page for further details. You would normally use the
7575 @code{-b} or @code{-V} switch instead.
7577 @item --GCC=@var{compiler_name}
7578 @cindex @code{--GCC=compiler_name} (@code{gnatlink})
7579 Program used for compiling the binder file. The default is
7580 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
7581 @code{compiler_name} contains spaces or other separator characters. As
7582 an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
7583 @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
7584 inserted after your command name. Thus in the above example the compiler
7585 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
7586 If several @code{--GCC=compiler_name} are used, only the last
7587 @var{compiler_name} is taken into account. However, all the additional
7588 switches are also taken into account. Thus,
7589 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7590 @code{--GCC="bar -x -y -z -t"}.
7592 @item --LINK=@var{name}
7593 @cindex @code{--LINK=} (@code{gnatlink})
7594 @var{name} is the name of the linker to be invoked. This is especially
7595 useful in mixed language programs since languages such as c++ require
7596 their own linker to be used. When this switch is omitted, the default
7597 name for the linker is (@file{gcc}). When this switch is used, the
7598 specified linker is called instead of (@file{gcc}) with exactly the same
7599 parameters that would have been passed to (@file{gcc}) so if the desired
7600 linker requires different parameters it is necessary to use a wrapper
7601 script that massages the parameters before invoking the real linker. It
7602 may be useful to control the exact invocation by using the verbose
7608 @item /DEBUG=TRACEBACK
7609 @cindex @code{/DEBUG=TRACEBACK} (@code{gnatlink})
7610 This qualifier causes sufficient information to be included in the
7611 executable file to allow a traceback, but does not include the full
7612 symbol information needed by the debugger.
7614 @item /IDENTIFICATION="<string>"
7615 "<string>" specifies the string to be stored in the image file identification
7616 field in the image header. It overrides any pragma Ident specified string.
7618 @item /NOINHIBIT-EXEC
7619 Generate the executable file even if there are linker warnings.
7621 @item /NOSTART_FILES
7622 Don't link in the object file containing the "main" transfer address.
7623 Used when linking with a foreign language main program compiled with a
7627 Prefer linking with object libraries over shareable images, even without
7633 @node Setting Stack Size from gnatlink
7634 @section Setting Stack Size from @code{gnatlink}
7637 It is possible to specify the program stack size from @code{gnatlink}.
7638 Assuming that the underlying linker is GNU ld there is two ways to do so:
7642 @item using @code{-Xlinker} linker option
7645 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
7648 This set the stack reserve size to 0x10000 bytes and the stack commit
7649 size to 0x1000 bytes.
7651 @item using @code{-Wl} linker option
7654 $ gnatlink hello -Wl,--stack=0x1000000
7657 This set the stack reserve size to 0x1000000 bytes. Note that with
7658 @code{-Wl} option it is not possible to set the stack commit size
7659 because the coma is a separator for this option.
7663 @node Setting Heap Size from gnatlink
7664 @section Setting Heap Size from @code{gnatlink}
7667 It is possible to specify the program heap size from @code{gnatlink}.
7668 Assuming that the underlying linker is GNU ld there is two ways to do so:
7672 @item using @code{-Xlinker} linker option
7675 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
7678 This set the heap reserve size to 0x10000 bytes and the heap commit
7679 size to 0x1000 bytes.
7681 @item using @code{-Wl} linker option
7684 $ gnatlink hello -Wl,--heap=0x1000000
7687 This set the heap reserve size to 0x1000000 bytes. Note that with
7688 @code{-Wl} option it is not possible to set the heap commit size
7689 because the coma is a separator for this option.
7693 @node The GNAT Make Program gnatmake
7694 @chapter The GNAT Make Program @code{gnatmake}
7698 * Running gnatmake::
7699 * Switches for gnatmake::
7700 * Mode Switches for gnatmake::
7701 * Notes on the Command Line::
7702 * How gnatmake Works::
7703 * Examples of gnatmake Usage::
7706 A typical development cycle when working on an Ada program consists of
7707 the following steps:
7711 Edit some sources to fix bugs.
7717 Compile all sources affected.
7727 The third step can be tricky, because not only do the modified files
7728 @cindex Dependency rules
7729 have to be compiled, but any files depending on these files must also be
7730 recompiled. The dependency rules in Ada can be quite complex, especially
7731 in the presence of overloading, @code{use} clauses, generics and inlined
7734 @code{gnatmake} automatically takes care of the third and fourth steps
7735 of this process. It determines which sources need to be compiled,
7736 compiles them, and binds and links the resulting object files.
7738 Unlike some other Ada make programs, the dependencies are always
7739 accurately recomputed from the new sources. The source based approach of
7740 the GNAT compilation model makes this possible. This means that if
7741 changes to the source program cause corresponding changes in
7742 dependencies, they will always be tracked exactly correctly by
7745 @node Running gnatmake
7746 @section Running @code{gnatmake}
7749 The usual form of the @code{gnatmake} command is
7752 $ gnatmake [@var{switches}] @var{file_name} [@var{file_names}] [@var{mode_switches}]
7756 The only required argument is one @var{file_name}, which specifies
7757 a compilation unit that is a main program. Several @var{file_names} can be
7758 specified: this will result in several executables being built.
7759 If @code{switches} are present, they can be placed before the first
7760 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
7761 If @var{mode_switches} are present, they must always be placed after
7762 the last @var{file_name} and all @code{switches}.
7764 If you are using standard file extensions (.adb and .ads), then the
7765 extension may be omitted from the @var{file_name} arguments. However, if
7766 you are using non-standard extensions, then it is required that the
7767 extension be given. A relative or absolute directory path can be
7768 specified in a @var{file_name}, in which case, the input source file will
7769 be searched for in the specified directory only. Otherwise, the input
7770 source file will first be searched in the directory where
7771 @code{gnatmake} was invoked and if it is not found, it will be search on
7772 the source path of the compiler as described in
7773 @ref{Search Paths and the Run-Time Library (RTL)}.
7775 When several @var{file_names} are specified, if an executable needs to be
7776 rebuilt and relinked, all subsequent executables will be rebuilt and
7777 relinked, even if this would not be absolutely necessary.
7779 All @code{gnatmake} output (except when you specify
7780 @code{^-M^/DEPENDENCIES_LIST^}) is to
7781 @file{stderr}. The output produced by the
7782 @code{^-M^/DEPENDENCIES_LIST^} switch is send to
7785 @node Switches for gnatmake
7786 @section Switches for @code{gnatmake}
7789 You may specify any of the following switches to @code{gnatmake}:
7793 @item --GCC=@var{compiler_name}
7794 @cindex @code{--GCC=compiler_name} (@code{gnatmake})
7795 Program used for compiling. The default is `@code{gcc}'. You need to use
7796 quotes around @var{compiler_name} if @code{compiler_name} contains
7797 spaces or other separator characters. As an example @code{--GCC="foo -x
7798 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
7799 compiler. Note that switch @code{-c} is always inserted after your
7800 command name. Thus in the above example the compiler command that will
7801 be used by @code{gnatmake} will be @code{foo -c -x -y}.
7802 If several @code{--GCC=compiler_name} are used, only the last
7803 @var{compiler_name} is taken into account. However, all the additional
7804 switches are also taken into account. Thus,
7805 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7806 @code{--GCC="bar -x -y -z -t"}.
7808 @item --GNATBIND=@var{binder_name}
7809 @cindex @code{--GNATBIND=binder_name} (@code{gnatmake})
7810 Program used for binding. The default is `@code{gnatbind}'. You need to
7811 use quotes around @var{binder_name} if @var{binder_name} contains spaces
7812 or other separator characters. As an example @code{--GNATBIND="bar -x
7813 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
7814 binder. Binder switches that are normally appended by @code{gnatmake} to
7815 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
7817 @item --GNATLINK=@var{linker_name}
7818 @cindex @code{--GNATLINK=linker_name} (@code{gnatmake})
7819 Program used for linking. The default is `@code{gnatlink}'. You need to
7820 use quotes around @var{linker_name} if @var{linker_name} contains spaces
7821 or other separator characters. As an example @code{--GNATLINK="lan -x
7822 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
7823 linker. Linker switches that are normally appended by @code{gnatmake} to
7824 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
7828 @item ^-a^/ALL_FILES^
7829 @cindex @code{^-a^/ALL_FILES^} (@code{gnatmake})
7830 Consider all files in the make process, even the GNAT internal system
7831 files (for example, the predefined Ada library files), as well as any
7832 locked files. Locked files are files whose ALI file is write-protected.
7834 @code{gnatmake} does not check these files,
7835 because the assumption is that the GNAT internal files are properly up
7836 to date, and also that any write protected ALI files have been properly
7837 installed. Note that if there is an installation problem, such that one
7838 of these files is not up to date, it will be properly caught by the
7840 You may have to specify this switch if you are working on GNAT
7841 itself. @code{^-a^/ALL_FILES^} is also useful in conjunction with
7842 @code{^-f^/FORCE_COMPILE^}
7843 if you need to recompile an entire application,
7844 including run-time files, using special configuration pragma settings,
7845 such as a non-standard @code{Float_Representation} pragma.
7847 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
7850 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7853 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
7856 @item ^-b^/ACTIONS=BIND^
7857 @cindex @code{^-b^/ACTIONS=BIND^} (@code{gnatmake})
7858 Bind only. Can be combined with @code{^-c^/ACTIONS=COMPILE^} to do compilation
7859 and binding, but no link. Can be combined with @code{^-l^/ACTIONS=LINK^}
7860 to do binding and linking. When not combined with @code{^-c^/ACTIONS=COMPILE^}
7861 all the units in the closure of the main program must have been previously
7862 compiled and must be up to date. The root unit specified by @var{file_name}
7863 may be given without extension, with the source extension or, if no GNAT
7864 Project File is specified, with the ALI file extension.
7866 @item ^-c^/ACTIONS=COMPILE^
7867 @cindex @code{^-c^/ACTIONS=COMPILE^} (@code{gnatmake})
7868 Compile only. Do not perform binding, except when @code{^-b^/ACTIONS=BIND^}
7869 is also specified. Do not perform linking, except if both
7870 @code{^-b^/ACTIONS=BIND^} and
7871 @code{^-l^/ACTIONS=LINK^} are also specified.
7872 If the root unit specified by @var{file_name} is not a main unit, this is the
7873 default. Otherwise @code{gnatmake} will attempt binding and linking
7874 unless all objects are up to date and the executable is more recent than
7878 @cindex @code{^-C^/MAPPING^} (@code{gnatmake})
7879 Use a mapping file. A mapping file is a way to communicate to the compiler
7880 two mappings: from unit names to file names (without any directory information)
7881 and from file names to path names (with full directory information).
7882 These mappings are used by the compiler to short-circuit the path search.
7883 When @code{gnatmake} is invoked with this switch, it will create a mapping
7884 file, initially populated by the project manager, if @code{-P} is used,
7885 otherwise initially empty. Each invocation of the compiler will add the newly
7886 accessed sources to the mapping file. This will improve the source search
7887 during the next invocation of the compiler.
7889 @item ^-f^/FORCE_COMPILE^
7890 @cindex @code{^-f^/FORCE_COMPILE^} (@code{gnatmake})
7891 Force recompilations. Recompile all sources, even though some object
7892 files may be up to date, but don't recompile predefined or GNAT internal
7893 files or locked files (files with a write-protected ALI file),
7894 unless the @code{^-a^/ALL_FILES^} switch is also specified.
7897 @item ^-i^/IN_PLACE^
7898 @cindex @code{^-i^/IN_PLACE^} (@code{gnatmake})
7899 In normal mode, @code{gnatmake} compiles all object files and ALI files
7900 into the current directory. If the @code{^-i^/IN_PLACE^} switch is used,
7901 then instead object files and ALI files that already exist are overwritten
7902 in place. This means that once a large project is organized into separate
7903 directories in the desired manner, then @code{gnatmake} will automatically
7904 maintain and update this organization. If no ALI files are found on the
7905 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
7906 the new object and ALI files are created in the
7907 directory containing the source being compiled. If another organization
7908 is desired, where objects and sources are kept in different directories,
7909 a useful technique is to create dummy ALI files in the desired directories.
7910 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
7911 the corresponding source file, and it will be put the resulting object
7912 and ALI files in the directory where it found the dummy file.
7914 @item ^-j^/PROCESSES=^@var{n}
7915 @cindex @code{^-j^/PROCESSES^} (@code{gnatmake})
7916 @cindex Parallel make
7917 Use @var{n} processes to carry out the (re)compilations. On a
7918 multiprocessor machine compilations will occur in parallel. In the
7919 event of compilation errors, messages from various compilations might
7920 get interspersed (but @code{gnatmake} will give you the full ordered
7921 list of failing compiles at the end). If this is problematic, rerun
7922 the make process with n set to 1 to get a clean list of messages.
7924 @item ^-k^/CONTINUE_ON_ERROR^
7925 @cindex @code{^-k^/CONTINUE_ON_ERROR^} (@code{gnatmake})
7926 Keep going. Continue as much as possible after a compilation error. To
7927 ease the programmer's task in case of compilation errors, the list of
7928 sources for which the compile fails is given when @code{gnatmake}
7931 If @code{gnatmake} is invoked with several @file{file_names} and with this
7932 switch, if there are compilation errors when building an executable,
7933 @code{gnatmake} will not attempt to build the following executables.
7935 @item ^-l^/ACTIONS=LINK^
7936 @cindex @code{^-l^/ACTIONS=LINK^} (@code{gnatmake})
7937 Link only. Can be combined with @code{^-b^/ACTIONS=BIND^} to binding
7938 and linking. Linking will not be performed if combined with
7939 @code{^-c^/ACTIONS=COMPILE^}
7940 but not with @code{^-b^/ACTIONS=BIND^}.
7941 When not combined with @code{^-b^/ACTIONS=BIND^}
7942 all the units in the closure of the main program must have been previously
7943 compiled and must be up to date, and the main program need to have been bound.
7944 The root unit specified by @var{file_name}
7945 may be given without extension, with the source extension or, if no GNAT
7946 Project File is specified, with the ALI file extension.
7948 @item ^-m^/MINIMAL_RECOMPILATION^
7949 @cindex @code{^-m^/MINIMAL_RECOMPILATION^} (@code{gnatmake})
7950 Specifies that the minimum necessary amount of recompilations
7951 be performed. In this mode @code{gnatmake} ignores time
7952 stamp differences when the only
7953 modifications to a source file consist in adding/removing comments,
7954 empty lines, spaces or tabs. This means that if you have changed the
7955 comments in a source file or have simply reformatted it, using this
7956 switch will tell gnatmake not to recompile files that depend on it
7957 (provided other sources on which these files depend have undergone no
7958 semantic modifications). Note that the debugging information may be
7959 out of date with respect to the sources if the @code{-m} switch causes
7960 a compilation to be switched, so the use of this switch represents a
7961 trade-off between compilation time and accurate debugging information.
7963 @item ^-M^/DEPENDENCIES_LIST^
7964 @cindex Dependencies, producing list
7965 @cindex @code{^-M^/DEPENDENCIES_LIST^} (@code{gnatmake})
7966 Check if all objects are up to date. If they are, output the object
7967 dependences to @file{stdout} in a form that can be directly exploited in
7968 a @file{Makefile}. By default, each source file is prefixed with its
7969 (relative or absolute) directory name. This name is whatever you
7970 specified in the various @code{^-aI^/SOURCE_SEARCH^}
7971 and @code{^-I^/SEARCH^} switches. If you use
7972 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
7974 (see below), only the source file names,
7975 without relative paths, are output. If you just specify the
7976 @code{^-M^/DEPENDENCIES_LIST^}
7977 switch, dependencies of the GNAT internal system files are omitted. This
7978 is typically what you want. If you also specify
7979 the @code{^-a^/ALL_FILES^} switch,
7980 dependencies of the GNAT internal files are also listed. Note that
7981 dependencies of the objects in external Ada libraries (see switch
7982 @code{^-aL^/SKIP_MISSING=^}@var{dir} in the following list) are never reported.
7984 @item ^-n^/DO_OBJECT_CHECK^
7985 @cindex @code{^-n^/DO_OBJECT_CHECK^} (@code{gnatmake})
7986 Don't compile, bind, or link. Checks if all objects are up to date.
7987 If they are not, the full name of the first file that needs to be
7988 recompiled is printed.
7989 Repeated use of this option, followed by compiling the indicated source
7990 file, will eventually result in recompiling all required units.
7992 @item ^-o ^/EXECUTABLE=^@var{exec_name}
7993 @cindex @code{^-o^/EXECUTABLE^} (@code{gnatmake})
7994 Output executable name. The name of the final executable program will be
7995 @var{exec_name}. If the @code{^-o^/EXECUTABLE^} switch is omitted the default
7996 name for the executable will be the name of the input file in appropriate form
7997 for an executable file on the host system.
7999 This switch cannot be used when invoking @code{gnatmake} with several
8003 @cindex @code{^-q^/QUIET^} (@code{gnatmake})
8004 Quiet. When this flag is not set, the commands carried out by
8005 @code{gnatmake} are displayed.
8007 @item ^-s^/SWITCH_CHECK/^
8008 @cindex @code{^-s^/SWITCH_CHECK^} (@code{gnatmake})
8009 Recompile if compiler switches have changed since last compilation.
8010 All compiler switches but -I and -o are taken into account in the
8012 orders between different ``first letter'' switches are ignored, but
8013 orders between same switches are taken into account. For example,
8014 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O} is equivalent
8018 @cindex @code{^-u^/UNIQUE^} (@code{gnatmake})
8019 Unique. Recompile at most the main file. It implies -c. Combined with
8020 -f, it is equivalent to calling the compiler directly.
8023 @cindex @code{^-v^/REASONS^} (@code{gnatmake})
8024 Verbose. Displays the reason for all recompilations @code{gnatmake}
8025 decides are necessary.
8028 @cindex @code{^-z^/NOMAIN^} (@code{gnatmake})
8029 No main subprogram. Bind and link the program even if the unit name
8030 given on the command line is a package name. The resulting executable
8031 will execute the elaboration routines of the package and its closure,
8032 then the finalization routines.
8034 @item @code{gcc} @asis{switches}
8036 The switch @code{-g} or any uppercase switch (other than @code{-A},
8038 @code{-S}) or any switch that is more than one character is passed to
8039 @code{gcc} (e.g. @code{-O}, @option{-gnato,} etc.)
8042 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8043 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8044 automatically treated as a compiler switch, and passed on to all
8045 compilations that are carried out.
8050 Source and library search path switches:
8053 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8054 @cindex @code{^-aI^/SOURCE_SEARCH^} (@code{gnatmake})
8055 When looking for source files also look in directory @var{dir}.
8056 The order in which source files search is undertaken is
8057 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8059 @item ^-aL^/SKIP_MISSING=^@var{dir}
8060 @cindex @code{^-aL^/SKIP_MISSING^} (@code{gnatmake})
8061 Consider @var{dir} as being an externally provided Ada library.
8062 Instructs @code{gnatmake} to skip compilation units whose @file{.ali}
8063 files have been located in directory @var{dir}. This allows you to have
8064 missing bodies for the units in @var{dir} and to ignore out of date bodies
8065 for the same units. You still need to specify
8066 the location of the specs for these units by using the switches
8067 @code{^-aI^/SOURCE_SEARCH=^@var{dir}}
8068 or @code{^-I^/SEARCH=^@var{dir}}.
8069 Note: this switch is provided for compatibility with previous versions
8070 of @code{gnatmake}. The easier method of causing standard libraries
8071 to be excluded from consideration is to write-protect the corresponding
8074 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8075 @cindex @code{^-aO^/OBJECT_SEARCH^} (@code{gnatmake})
8076 When searching for library and object files, look in directory
8077 @var{dir}. The order in which library files are searched is described in
8078 @ref{Search Paths for gnatbind}.
8080 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8081 @cindex Search paths, for @code{gnatmake}
8082 @cindex @code{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@code{gnatmake})
8083 Equivalent to @code{^-aL^/SKIP_MISSING=^@var{dir}
8084 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8086 @item ^-I^/SEARCH=^@var{dir}
8087 @cindex @code{^-I^/SEARCH^} (@code{gnatmake})
8088 Equivalent to @code{^-aO^/OBJECT_SEARCH=^@var{dir}
8089 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8091 @item ^-I-^/NOCURRENT_DIRECTORY^
8092 @cindex @code{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatmake})
8093 @cindex Source files, suppressing search
8094 Do not look for source files in the directory containing the source
8095 file named in the command line.
8096 Do not look for ALI or object files in the directory
8097 where @code{gnatmake} was invoked.
8099 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8100 @cindex @code{^-L^/LIBRARY_SEARCH^} (@code{gnatmake})
8101 @cindex Linker libraries
8102 Add directory @var{dir} to the list of directories in which the linker
8104 Furthermore, under Windows, the sources pointed to by the libraries path
8105 set in the registry are not searched for.
8107 will search for libraries. This is equivalent to
8108 @code{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8111 @cindex @code{-nostdinc} (@code{gnatmake})
8112 Do not look for source files in the system default directory.
8115 @cindex @code{-nostdlib} (@code{gnatmake})
8116 Do not look for library files in the system default directory.
8118 @item --RTS=@var{rts-path}
8119 @cindex @code{--RTS} (@code{gnatmake})
8120 Specifies the default location of the runtime library. We look for the runtime
8121 in the following directories, and stop as soon as a valid runtime is found
8122 ("adainclude" or "ada_source_path", and "adalib" or "ada_object_path" present):
8125 @item <current directory>/$rts_path
8127 @item <default-search-dir>/$rts_path
8129 @item <default-search-dir>/rts-$rts_path
8133 The selected path is handled like a normal RTS path.
8137 @node Mode Switches for gnatmake
8138 @section Mode Switches for @code{gnatmake}
8141 The mode switches (referred to as @code{mode_switches}) allow the
8142 inclusion of switches that are to be passed to the compiler itself, the
8143 binder or the linker. The effect of a mode switch is to cause all
8144 subsequent switches up to the end of the switch list, or up to the next
8145 mode switch, to be interpreted as switches to be passed on to the
8146 designated component of GNAT.
8149 @item -cargs @var{switches}
8150 @cindex @code{-cargs} (@code{gnatmake})
8151 Compiler switches. Here @var{switches} is a list of switches
8152 that are valid switches for @code{gcc}. They will be passed on to
8153 all compile steps performed by @code{gnatmake}.
8155 @item -bargs @var{switches}
8156 @cindex @code{-bargs} (@code{gnatmake})
8157 Binder switches. Here @var{switches} is a list of switches
8158 that are valid switches for @code{gcc}. They will be passed on to
8159 all bind steps performed by @code{gnatmake}.
8161 @item -largs @var{switches}
8162 @cindex @code{-largs} (@code{gnatmake})
8163 Linker switches. Here @var{switches} is a list of switches
8164 that are valid switches for @code{gcc}. They will be passed on to
8165 all link steps performed by @code{gnatmake}.
8168 @node Notes on the Command Line
8169 @section Notes on the Command Line
8172 This section contains some additional useful notes on the operation
8173 of the @code{gnatmake} command.
8177 @cindex Recompilation, by @code{gnatmake}
8178 If @code{gnatmake} finds no ALI files, it recompiles the main program
8179 and all other units required by the main program.
8180 This means that @code{gnatmake}
8181 can be used for the initial compile, as well as during subsequent steps of
8182 the development cycle.
8185 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8186 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8187 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8191 In @code{gnatmake} the switch @code{^-I^/SEARCH^}
8192 is used to specify both source and
8193 library file paths. Use @code{^-aI^/SOURCE_SEARCH^}
8194 instead if you just want to specify
8195 source paths only and @code{^-aO^/OBJECT_SEARCH^}
8196 if you want to specify library paths
8200 @code{gnatmake} examines both an ALI file and its corresponding object file
8201 for consistency. If an ALI is more recent than its corresponding object,
8202 or if the object file is missing, the corresponding source will be recompiled.
8203 Note that @code{gnatmake} expects an ALI and the corresponding object file
8204 to be in the same directory.
8207 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8208 This may conveniently be used to exclude standard libraries from
8209 consideration and in particular it means that the use of the
8210 @code{^-f^/FORCE_COMPILE^} switch will not recompile these files
8211 unless @code{^-a^/ALL_FILES^} is also specified.
8214 @code{gnatmake} has been designed to make the use of Ada libraries
8215 particularly convenient. Assume you have an Ada library organized
8216 as follows: ^@var{obj-dir}^[@var{OBJ_DIR}]^ contains the objects and ALI files for
8217 of your Ada compilation units,
8218 whereas ^@var{include-dir}^[@var{INCLUDE_DIR}]^ contains the
8219 specs of these units, but no bodies. Then to compile a unit
8220 stored in @code{main.adb}, which uses this Ada library you would just type
8224 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
8227 $ gnatmake /SOURCE_SEARCH=[@var{INCLUDE_DIR}]
8228 /SKIP_MISSING=[@var{OBJ_DIR}] main
8233 Using @code{gnatmake} along with the
8234 @code{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8235 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8237 you can update the comments/format of your
8238 source files without having to recompile everything. Note, however, that
8239 adding or deleting lines in a source files may render its debugging
8240 info obsolete. If the file in question is a spec, the impact is rather
8241 limited, as that debugging info will only be useful during the
8242 elaboration phase of your program. For bodies the impact can be more
8243 significant. In all events, your debugger will warn you if a source file
8244 is more recent than the corresponding object, and alert you to the fact
8245 that the debugging information may be out of date.
8248 @node How gnatmake Works
8249 @section How @code{gnatmake} Works
8252 Generally @code{gnatmake} automatically performs all necessary
8253 recompilations and you don't need to worry about how it works. However,
8254 it may be useful to have some basic understanding of the @code{gnatmake}
8255 approach and in particular to understand how it uses the results of
8256 previous compilations without incorrectly depending on them.
8258 First a definition: an object file is considered @dfn{up to date} if the
8259 corresponding ALI file exists and its time stamp predates that of the
8260 object file and if all the source files listed in the
8261 dependency section of this ALI file have time stamps matching those in
8262 the ALI file. This means that neither the source file itself nor any
8263 files that it depends on have been modified, and hence there is no need
8264 to recompile this file.
8266 @code{gnatmake} works by first checking if the specified main unit is up
8267 to date. If so, no compilations are required for the main unit. If not,
8268 @code{gnatmake} compiles the main program to build a new ALI file that
8269 reflects the latest sources. Then the ALI file of the main unit is
8270 examined to find all the source files on which the main program depends,
8271 and @code{gnatmake} recursively applies the above procedure on all these files.
8273 This process ensures that @code{gnatmake} only trusts the dependencies
8274 in an existing ALI file if they are known to be correct. Otherwise it
8275 always recompiles to determine a new, guaranteed accurate set of
8276 dependencies. As a result the program is compiled "upside down" from what may
8277 be more familiar as the required order of compilation in some other Ada
8278 systems. In particular, clients are compiled before the units on which
8279 they depend. The ability of GNAT to compile in any order is critical in
8280 allowing an order of compilation to be chosen that guarantees that
8281 @code{gnatmake} will recompute a correct set of new dependencies if
8284 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
8285 imported by several of the executables, it will be recompiled at most once.
8287 @node Examples of gnatmake Usage
8288 @section Examples of @code{gnatmake} Usage
8291 @item gnatmake hello.adb
8292 Compile all files necessary to bind and link the main program
8293 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8294 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8296 @item gnatmake main1 main2 main3
8297 Compile all files necessary to bind and link the main programs
8298 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8299 (containing unit @code{Main2}) and @file{main3.adb}
8300 (containing unit @code{Main3}) and bind and link the resulting object files
8301 to generate three executable files @file{^main1^MAIN1.EXE^},
8302 @file{^main2^MAIN2.EXE^}
8303 and @file{^main3^MAIN3.EXE^}.
8306 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8310 @item gnatmake Main_Unit /QUIET /COMPILER_QUALIFIERS /OPTIMIZE=ALL /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8312 Compile all files necessary to bind and link the main program unit
8313 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8314 be done with optimization level 2 and the order of elaboration will be
8315 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8316 displaying commands it is executing.
8319 @node Renaming Files Using gnatchop
8320 @chapter Renaming Files Using @code{gnatchop}
8324 This chapter discusses how to handle files with multiple units by using
8325 the @code{gnatchop} utility. This utility is also useful in renaming
8326 files to meet the standard GNAT default file naming conventions.
8329 * Handling Files with Multiple Units::
8330 * Operating gnatchop in Compilation Mode::
8331 * Command Line for gnatchop::
8332 * Switches for gnatchop::
8333 * Examples of gnatchop Usage::
8336 @node Handling Files with Multiple Units
8337 @section Handling Files with Multiple Units
8340 The basic compilation model of GNAT requires that a file submitted to the
8341 compiler have only one unit and there be a strict correspondence
8342 between the file name and the unit name.
8344 The @code{gnatchop} utility allows both of these rules to be relaxed,
8345 allowing GNAT to process files which contain multiple compilation units
8346 and files with arbitrary file names. @code{gnatchop}
8347 reads the specified file and generates one or more output files,
8348 containing one unit per file. The unit and the file name correspond,
8349 as required by GNAT.
8351 If you want to permanently restructure a set of "foreign" files so that
8352 they match the GNAT rules, and do the remaining development using the
8353 GNAT structure, you can simply use @code{gnatchop} once, generate the
8354 new set of files and work with them from that point on.
8356 Alternatively, if you want to keep your files in the "foreign" format,
8357 perhaps to maintain compatibility with some other Ada compilation
8358 system, you can set up a procedure where you use @code{gnatchop} each
8359 time you compile, regarding the source files that it writes as temporary
8360 files that you throw away.
8362 @node Operating gnatchop in Compilation Mode
8363 @section Operating gnatchop in Compilation Mode
8366 The basic function of @code{gnatchop} is to take a file with multiple units
8367 and split it into separate files. The boundary between files is reasonably
8368 clear, except for the issue of comments and pragmas. In default mode, the
8369 rule is that any pragmas between units belong to the previous unit, except
8370 that configuration pragmas always belong to the following unit. Any comments
8371 belong to the following unit. These rules
8372 almost always result in the right choice of
8373 the split point without needing to mark it explicitly and most users will
8374 find this default to be what they want. In this default mode it is incorrect to
8375 submit a file containing only configuration pragmas, or one that ends in
8376 configuration pragmas, to @code{gnatchop}.
8378 However, using a special option to activate "compilation mode",
8380 can perform another function, which is to provide exactly the semantics
8381 required by the RM for handling of configuration pragmas in a compilation.
8382 In the absence of configuration pragmas (at the main file level), this
8383 option has no effect, but it causes such configuration pragmas to be handled
8384 in a quite different manner.
8386 First, in compilation mode, if @code{gnatchop} is given a file that consists of
8387 only configuration pragmas, then this file is appended to the
8388 @file{gnat.adc} file in the current directory. This behavior provides
8389 the required behavior described in the RM for the actions to be taken
8390 on submitting such a file to the compiler, namely that these pragmas
8391 should apply to all subsequent compilations in the same compilation
8392 environment. Using GNAT, the current directory, possibly containing a
8393 @file{gnat.adc} file is the representation
8394 of a compilation environment. For more information on the
8395 @file{gnat.adc} file, see the section on handling of configuration
8396 pragmas @pxref{Handling of Configuration Pragmas}.
8398 Second, in compilation mode, if @code{gnatchop}
8399 is given a file that starts with
8400 configuration pragmas, and contains one or more units, then these
8401 configuration pragmas are prepended to each of the chopped files. This
8402 behavior provides the required behavior described in the RM for the
8403 actions to be taken on compiling such a file, namely that the pragmas
8404 apply to all units in the compilation, but not to subsequently compiled
8407 Finally, if configuration pragmas appear between units, they are appended
8408 to the previous unit. This results in the previous unit being illegal,
8409 since the compiler does not accept configuration pragmas that follow
8410 a unit. This provides the required RM behavior that forbids configuration
8411 pragmas other than those preceding the first compilation unit of a
8414 For most purposes, @code{gnatchop} will be used in default mode. The
8415 compilation mode described above is used only if you need exactly
8416 accurate behavior with respect to compilations, and you have files
8417 that contain multiple units and configuration pragmas. In this
8418 circumstance the use of @code{gnatchop} with the compilation mode
8419 switch provides the required behavior, and is for example the mode
8420 in which GNAT processes the ACVC tests.
8422 @node Command Line for gnatchop
8423 @section Command Line for @code{gnatchop}
8426 The @code{gnatchop} command has the form:
8429 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
8434 The only required argument is the file name of the file to be chopped.
8435 There are no restrictions on the form of this file name. The file itself
8436 contains one or more Ada units, in normal GNAT format, concatenated
8437 together. As shown, more than one file may be presented to be chopped.
8439 When run in default mode, @code{gnatchop} generates one output file in
8440 the current directory for each unit in each of the files.
8442 @var{directory}, if specified, gives the name of the directory to which
8443 the output files will be written. If it is not specified, all files are
8444 written to the current directory.
8446 For example, given a
8447 file called @file{hellofiles} containing
8452 @b{procedure} hello;
8454 @b{with} Text_IO; @b{use} Text_IO;
8455 @b{procedure} hello @b{is}
8467 $ gnatchop ^hellofiles^HELLOFILES.^
8471 generates two files in the current directory, one called
8472 @file{hello.ads} containing the single line that is the procedure spec,
8473 and the other called @file{hello.adb} containing the remaining text. The
8474 original file is not affected. The generated files can be compiled in
8477 @node Switches for gnatchop
8478 @section Switches for @code{gnatchop}
8481 @code{gnatchop} recognizes the following switches:
8485 @item ^-c^/COMPILATION^
8486 @cindex @code{^-c^/COMPILATION^} (@code{gnatchop})
8487 Causes @code{gnatchop} to operate in compilation mode, in which
8488 configuration pragmas are handled according to strict RM rules. See
8489 previous section for a full description of this mode.
8493 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
8494 used to parse the given file. Not all @code{xxx} options make sense,
8495 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
8496 process a source file that uses Latin-2 coding for identifiers.
8500 Causes @code{gnatchop} to generate a brief help summary to the standard
8501 output file showing usage information.
8503 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
8504 @cindex @code{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
8505 Limit generated file names to the specified number @code{mm}
8507 This is useful if the
8508 resulting set of files is required to be interoperable with systems
8509 which limit the length of file names.
8511 If no value is given, or
8512 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
8513 a default of 39, suitable for OpenVMS Alpha
8517 No space is allowed between the @code{-k} and the numeric value. The numeric
8518 value may be omitted in which case a default of @code{-k8},
8520 with DOS-like file systems, is used. If no @code{-k} switch
8522 there is no limit on the length of file names.
8525 @item ^-p^/PRESERVE^
8526 @cindex @code{^-p^/PRESERVE^} (@code{gnatchop})
8527 Causes the file ^modification^creation^ time stamp of the input file to be
8528 preserved and used for the time stamp of the output file(s). This may be
8529 useful for preserving coherency of time stamps in an enviroment where
8530 @code{gnatchop} is used as part of a standard build process.
8533 @cindex @code{^-q^/QUIET^} (@code{gnatchop})
8534 Causes output of informational messages indicating the set of generated
8535 files to be suppressed. Warnings and error messages are unaffected.
8537 @item ^-r^/REFERENCE^
8538 @cindex @code{^-r^/REFERENCE^} (@code{gnatchop})
8539 @findex Source_Reference
8540 Generate @code{Source_Reference} pragmas. Use this switch if the output
8541 files are regarded as temporary and development is to be done in terms
8542 of the original unchopped file. This switch causes
8543 @code{Source_Reference} pragmas to be inserted into each of the
8544 generated files to refers back to the original file name and line number.
8545 The result is that all error messages refer back to the original
8547 In addition, the debugging information placed into the object file (when
8548 the @code{^-g^/DEBUG^} switch of @code{gcc} or @code{gnatmake} is specified) also
8549 refers back to this original file so that tools like profilers and
8550 debuggers will give information in terms of the original unchopped file.
8552 If the original file to be chopped itself contains
8553 a @code{Source_Reference}
8554 pragma referencing a third file, then gnatchop respects
8555 this pragma, and the generated @code{Source_Reference} pragmas
8556 in the chopped file refer to the original file, with appropriate
8557 line numbers. This is particularly useful when @code{gnatchop}
8558 is used in conjunction with @code{gnatprep} to compile files that
8559 contain preprocessing statements and multiple units.
8562 @cindex @code{^-v^/VERBOSE^} (@code{gnatchop})
8563 Causes @code{gnatchop} to operate in verbose mode. The version
8564 number and copyright notice are output, as well as exact copies of
8565 the gnat1 commands spawned to obtain the chop control information.
8567 @item ^-w^/OVERWRITE^
8568 @cindex @code{^-w^/OVERWRITE^} (@code{gnatchop})
8569 Overwrite existing file names. Normally @code{gnatchop} regards it as a
8570 fatal error if there is already a file with the same name as a
8571 file it would otherwise output, in other words if the files to be
8572 chopped contain duplicated units. This switch bypasses this
8573 check, and causes all but the last instance of such duplicated
8574 units to be skipped.
8578 @cindex @code{--GCC=} (@code{gnatchop})
8579 Specify the path of the GNAT parser to be used. When this switch is used,
8580 no attempt is made to add the prefix to the GNAT parser executable.
8584 @node Examples of gnatchop Usage
8585 @section Examples of @code{gnatchop} Usage
8589 @item gnatchop /OVERWRITE HELLO_S.ADA [ICHBIAH.FILES]
8592 @item gnatchop -w hello_s.ada ichbiah/files
8595 Chops the source file @file{hello_s.ada}. The output files will be
8596 placed in the directory @file{^ichbiah/files^[ICHBIAH.FILES]^},
8598 files with matching names in that directory (no files in the current
8599 directory are modified).
8601 @item gnatchop ^archive^ARCHIVE.^
8602 Chops the source file @file{^archive^ARCHIVE.^}
8603 into the current directory. One
8604 useful application of @code{gnatchop} is in sending sets of sources
8605 around, for example in email messages. The required sources are simply
8606 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
8608 @code{gnatchop} is used at the other end to reconstitute the original
8611 @item gnatchop file1 file2 file3 direc
8612 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
8613 the resulting files in the directory @file{direc}. Note that if any units
8614 occur more than once anywhere within this set of files, an error message
8615 is generated, and no files are written. To override this check, use the
8616 @code{^-w^/OVERWRITE^} switch,
8617 in which case the last occurrence in the last file will
8618 be the one that is output, and earlier duplicate occurrences for a given
8619 unit will be skipped.
8622 @node Configuration Pragmas
8623 @chapter Configuration Pragmas
8624 @cindex Configuration pragmas
8625 @cindex Pragmas, configuration
8628 In Ada 95, configuration pragmas include those pragmas described as
8629 such in the Ada 95 Reference Manual, as well as
8630 implementation-dependent pragmas that are configuration pragmas. See the
8631 individual descriptions of pragmas in the GNAT Reference Manual for
8632 details on these additional GNAT-specific configuration pragmas. Most
8633 notably, the pragma @code{Source_File_Name}, which allows
8634 specifying non-default names for source files, is a configuration
8635 pragma. The following is a complete list of configuration pragmas
8636 recognized by @code{GNAT}:
8648 External_Name_Casing
8649 Float_Representation
8657 Propagate_Exceptions
8666 Task_Dispatching_Policy
8674 * Handling of Configuration Pragmas::
8675 * The Configuration Pragmas Files::
8678 @node Handling of Configuration Pragmas
8679 @section Handling of Configuration Pragmas
8681 Configuration pragmas may either appear at the start of a compilation
8682 unit, in which case they apply only to that unit, or they may apply to
8683 all compilations performed in a given compilation environment.
8685 GNAT also provides the @code{gnatchop} utility to provide an automatic
8686 way to handle configuration pragmas following the semantics for
8687 compilations (that is, files with multiple units), described in the RM.
8688 See section @pxref{Operating gnatchop in Compilation Mode} for details.
8689 However, for most purposes, it will be more convenient to edit the
8690 @file{gnat.adc} file that contains configuration pragmas directly,
8691 as described in the following section.
8693 @node The Configuration Pragmas Files
8694 @section The Configuration Pragmas Files
8695 @cindex @file{gnat.adc}
8698 In GNAT a compilation environment is defined by the current
8699 directory at the time that a compile command is given. This current
8700 directory is searched for a file whose name is @file{gnat.adc}. If
8701 this file is present, it is expected to contain one or more
8702 configuration pragmas that will be applied to the current compilation.
8703 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
8706 Configuration pragmas may be entered into the @file{gnat.adc} file
8707 either by running @code{gnatchop} on a source file that consists only of
8708 configuration pragmas, or more conveniently by
8709 direct editing of the @file{gnat.adc} file, which is a standard format
8712 In addition to @file{gnat.adc}, one additional file containing configuration
8713 pragmas may be applied to the current compilation using the switch
8714 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
8715 contains only configuration pragmas. These configuration pragmas are
8716 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
8717 is present and switch @option{-gnatA} is not used).
8719 It is allowed to specify several switches @option{-gnatec}, however only
8720 the last one on the command line will be taken into account.
8723 Of special interest to GNAT OpenVMS Alpha is the following configuration pragma:
8727 @b{pragma} Extend_System (Aux_DEC);
8732 In the presence of this pragma, GNAT adds to the definition of the
8733 predefined package SYSTEM all the additional types and subprograms that are
8734 defined in DEC Ada. See @pxref{Compatibility with DEC Ada} for details.
8737 @node Handling Arbitrary File Naming Conventions Using gnatname
8738 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
8739 @cindex Arbitrary File Naming Conventions
8742 * Arbitrary File Naming Conventions::
8743 * Running gnatname::
8744 * Switches for gnatname::
8745 * Examples of gnatname Usage::
8748 @node Arbitrary File Naming Conventions
8749 @section Arbitrary File Naming Conventions
8752 The GNAT compiler must be able to know the source file name of a compilation unit.
8753 When using the standard GNAT default file naming conventions (@code{.ads} for specs,
8754 @code{.adb} for bodies), the GNAT compiler does not need additional information.
8757 When the source file names do not follow the standard GNAT default file naming
8758 conventions, the GNAT compiler must be given additional information through
8759 a configuration pragmas file (see @ref{Configuration Pragmas}) or a project file.
8760 When the non standard file naming conventions are well-defined, a small number of
8761 pragmas @code{Source_File_Name} specifying a naming pattern
8762 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
8763 if the file naming conventions are irregular or arbitrary, a number
8764 of pragma @code{Source_File_Name} for individual compilation units must be defined.
8765 To help maintain the correspondence between compilation unit names and
8766 source file names within the compiler,
8767 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
8770 @node Running gnatname
8771 @section Running @code{gnatname}
8774 The usual form of the @code{gnatname} command is
8777 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
8781 All of the arguments are optional. If invoked without any argument,
8782 @code{gnatname} will display its usage.
8785 When used with at least one naming pattern, @code{gnatname} will attempt to
8786 find all the compilation units in files that follow at least one of the
8787 naming patterns. To find these compilation units,
8788 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
8792 One or several Naming Patterns may be given as arguments to @code{gnatname}.
8793 Each Naming Pattern is enclosed between double quotes.
8794 A Naming Pattern is a regular expression similar to the wildcard patterns
8795 used in file names by the Unix shells or the DOS prompt.
8798 Examples of Naming Patterns are
8807 For a more complete description of the syntax of Naming Patterns, see the second kind
8808 of regular expressions described in @file{g-regexp.ads} (the "Glob" regular
8812 When invoked with no switches, @code{gnatname} will create a configuration
8813 pragmas file @file{gnat.adc} in the current working directory, with pragmas
8814 @code{Source_File_Name} for each file that contains a valid Ada unit.
8816 @node Switches for gnatname
8817 @section Switches for @code{gnatname}
8820 Switches for @code{gnatname} must precede any specified Naming Pattern.
8823 You may specify any of the following switches to @code{gnatname}:
8828 @cindex @code{-c} (@code{gnatname})
8829 Create a configuration pragmas file @file{file} (instead of the default
8830 @file{gnat.adc}). There may be zero, one or more space between @code{-c} and
8831 @file{file}. @file{file} may include directory information. @file{file} must be
8832 writeable. There may be only one switch @code{-c}. When a switch @code{-c} is
8833 specified, no switch @code{-P} may be specified (see below).
8836 @cindex @code{-d} (@code{gnatname})
8837 Look for source files in directory @file{dir}. There may be zero, one or more spaces
8838 between @code{-d} and @file{dir}. When a switch @code{-d} is specified,
8839 the current working directory will not be searched for source files, unless it
8841 specified with a @code{-d} or @code{-D} switch. Several switches @code{-d} may be
8842 specified. If @file{dir} is a relative path, it is relative to the directory of
8843 the configuration pragmas file specified with switch @code{-c}, or to the directory
8844 of the project file specified with switch @code{-P} or, if neither switch @code{-c}
8845 nor switch @code{-P} are specified, it is relative to the current working
8846 directory. The directory
8847 specified with switch @code{-c} must exist and be readable.
8850 @cindex @code{-D} (@code{gnatname})
8851 Look for source files in all directories listed in text file @file{file}. There may be
8852 zero, one or more spaces between @code{-d} and @file{dir}. @file{file}
8853 must be an existing, readable text file. Each non empty line in @file{file} must be
8854 a directory. Specifying switch @code{-D} is equivalent to specifying as many switches
8855 @code{-d} as there are non empty lines in @file{file}.
8858 @cindex @code{-h} (@code{gnatname})
8859 Output usage (help) information. The output is written to @file{stdout}.
8862 @cindex @code{-P} (@code{gnatname})
8863 Create or update project file @file{proj}. There may be zero, one or more space
8864 between @code{-P} and @file{proj}. @file{proj} may include directory information.
8865 @file{proj} must be writeable. There may be only one switch @code{-P}.
8866 When a switch @code{-P} is specified, no switch @code{-c} may be specified.
8869 @cindex @code{-v} (@code{gnatname})
8870 Verbose mode. Output detailed explanation of behavior to @file{stdout}. This includes
8871 name of the file written, the name of the directories to search and, for each file
8872 in those directories whose name matches at least one of the Naming Patterns, an
8873 indication of whether the file contains a unit, and if so the name of the unit.
8876 Very Verbose mode. In addition to the output produced in verbose mode, for each file
8877 in the searched directories whose name matches none of the Naming Patterns, an
8878 indication is given that there is no match.
8880 @item -x@file{pattern}
8881 Excluded patterns. Using this switch, it is possible to exclude some files
8882 that would match the name patterns. For example,
8883 @code{"gnatname -x "*_nt.ada" "*.ada"} will look for Ada units in all files
8884 with the @file{.ada} extension, except those whose names end with
8889 @node Examples of gnatname Usage
8890 @section Examples of @code{gnatname} Usage
8893 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
8896 In this example, the directory @file{/home/me} must already exist and be
8897 writeable. In addition, the directory @file{/home/me/sources} (specified by
8898 @code{-d sources}) must exist and be readable. Note the optional spaces after
8899 @code{-c} and @code{-d}.
8902 $ gnatname -P/home/me/proj -x "*_nt_body.ada" -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
8905 Note that several switches @code{-d} may be used, even in conjunction with one
8906 or several switches @code{-D}. Several Naming Patterns and one excluded pattern
8907 are used in this example.
8910 @c *****************************************
8911 @c * G N A T P r o j e c t M a n a g e r *
8912 @c *****************************************
8913 @node GNAT Project Manager
8914 @chapter GNAT Project Manager
8918 * Examples of Project Files::
8919 * Project File Syntax::
8920 * Objects and Sources in Project Files::
8921 * Importing Projects::
8922 * Project Extension::
8923 * External References in Project Files::
8924 * Packages in Project Files::
8925 * Variables from Imported Projects::
8927 * Library Projects::
8928 * Switches Related to Project Files::
8929 * Tools Supporting Project Files::
8930 * An Extended Example::
8931 * Project File Complete Syntax::
8940 @section Introduction
8943 This chapter describes GNAT's @emph{Project Manager}, a facility that
8944 lets you configure various properties for a collection of source files. In
8945 particular, you can specify:
8948 The directory or set of directories containing the source files, and/or the
8949 names of the specific source files themselves
8951 The directory in which the compiler's output
8952 (@file{ALI} files, object files, tree files) will be placed
8954 The directory in which the executable programs will be placed
8956 Switch settings for any of the project-enabled tools (@command{gnatmake},
8957 compiler, binder, linker, @code{gnatls}, @code{gnatxref}, @code{gnatfind});
8958 you can apply these settings either globally or to individual units
8960 The source files containing the main subprogram(s) to be built
8962 The source programming language(s) (currently Ada and/or C)
8964 Source file naming conventions; you can specify these either globally or for
8973 @subsection Project Files
8976 A @dfn{project} is a specific set of values for these properties. You can
8977 define a project's settings in a @dfn{project file}, a text file with an
8978 Ada-like syntax; a property value is either a string or a list of strings.
8979 Properties that are not explicitly set receive default values. A project
8980 file may interrogate the values of @dfn{external variables} (user-defined
8981 command-line switches or environment variables), and it may specify property
8982 settings conditionally, based on the value of such variables.
8984 In simple cases, a project's source files depend only on other source files
8985 in the same project, or on the predefined libraries. ("Dependence" is in
8986 the technical sense; for example, one Ada unit "with"ing another.) However,
8987 the Project Manager also allows much more sophisticated arrangements,
8988 with the source files in one project depending on source files in other
8992 One project can @emph{import} other projects containing needed source files.
8994 You can organize GNAT projects in a hierarchy: a @emph{child} project
8995 can extend a @emph{parent} project, inheriting the parent's source files and
8996 optionally overriding any of them with alternative versions
9000 More generally, the Project Manager lets you structure large development
9001 efforts into hierarchical subsystems, with build decisions deferred to the
9002 subsystem level and thus different compilation environments (switch settings)
9003 used for different subsystems.
9005 The Project Manager is invoked through the @option{-P@emph{projectfile}}
9006 switch to @command{gnatmake} or to the @command{gnat} front driver.
9007 If you want to define (on the command line) an external variable that is
9008 queried by the project file, additionally use the
9009 @option{-X@emph{vbl}=@emph{value}} switch.
9010 The Project Manager parses and interprets the project file, and drives the
9011 invoked tool based on the project settings.
9013 The Project Manager supports a wide range of development strategies,
9014 for systems of all sizes. Some typical practices that are easily handled:
9017 Using a common set of source files, but generating object files in different
9018 directories via different switch settings
9020 Using a mostly-shared set of source files, but with different versions of
9025 The destination of an executable can be controlled inside a project file
9026 using the @option{-o} switch. In the absence of such a switch either inside
9027 the project file or on the command line, any executable files generated by
9028 @command{gnatmake} will be placed in the directory @code{Exec_Dir} specified
9029 in the project file. If no @code{Exec_Dir} is specified, they will be placed
9030 in the object directory of the project.
9032 You can use project files to achieve some of the effects of a source
9033 versioning system (for example, defining separate projects for
9034 the different sets of sources that comprise different releases) but the
9035 Project Manager is independent of any source configuration management tools
9036 that might be used by the developers.
9038 The next section introduces the main features of GNAT's project facility
9039 through a sequence of examples; subsequent sections will present the syntax
9040 and semantics in more detail.
9043 @c *****************************
9044 @c * Examples of Project Files *
9045 @c *****************************
9047 @node Examples of Project Files
9048 @section Examples of Project Files
9050 This section illustrates some of the typical uses of project files and
9051 explains their basic structure and behavior.
9054 * Common Sources with Different Switches and Different Output Directories::
9055 * Using External Variables::
9056 * Importing Other Projects::
9057 * Extending a Project::
9060 @node Common Sources with Different Switches and Different Output Directories
9061 @subsection Common Sources with Different Switches and Different Output Directories
9065 * Specifying the Object Directory::
9066 * Specifying the Exec Directory::
9067 * Project File Packages::
9068 * Specifying Switch Settings::
9069 * Main Subprograms::
9070 * Source File Naming Conventions::
9071 * Source Language(s)::
9075 Assume that the Ada source files @file{pack.ads}, @file{pack.adb}, and
9076 @file{proc.adb} are in the @file{/common} directory. The file
9077 @file{proc.adb} contains an Ada main subprogram @code{Proc} that "with"s
9078 package @code{Pack}. We want to compile these source files under two sets
9082 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
9083 and the @option{-gnata}, @option{-gnato}, and @option{-gnatE} switches to the
9084 compiler; the compiler's output is to appear in @file{/common/debug}
9086 When preparing a release version, we want to pass the @option{-O2} switch to
9087 the compiler; the compiler's output is to appear in @file{/common/release}
9091 The GNAT project files shown below, respectively @file{debug.gpr} and
9092 @file{release.gpr} in the @file{/common} directory, achieve these effects.
9105 /common/debug @{-g, -gnata, -gnato, -gnatE@}
9110 /common/release @{-O2@}
9115 Here are the project files:
9119 for Object_Dir use "debug";
9120 for Main use ("proc");
9123 for Default_Switches ("Ada") use ("-g");
9129 for Default_Switches ("Ada")
9130 use ("-fstack-check", "-gnata", "-gnato", "-gnatE");
9139 for Object_Dir use "release";
9140 for Exec_Dir use ".";
9141 for Main use ("proc");
9144 for Default_Switches ("Ada") use ("-O2");
9151 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
9152 insensitive), and analogously the project defined by @file{release.gpr} is
9153 @code{"Release"}. For consistency the file should have the same name as the
9154 project, and the project file's extension should be @code{"gpr"}. These
9155 conventions are not required, but a warning is issued if they are not followed.
9157 If the current directory is @file{/temp}, then the command
9159 gnatmake -P/common/debug.gpr
9163 generates object and ALI files in @file{/common/debug}, and the @code{proc}
9164 executable also in @file{/common/debug}, using the switch settings defined in
9167 Likewise, the command
9169 gnatmake -P/common/release.gpr
9173 generates object and ALI files in @file{/common/release}, and the @code{proc}
9174 executable in @file{/common}, using the switch settings from the project file.
9177 @unnumberedsubsubsec Source Files
9180 If a project file does not explicitly specify a set of source directories or
9181 a set of source files, then by default the project's source files are the
9182 Ada source files in the project file directory. Thus @file{pack.ads},
9183 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
9185 @node Specifying the Object Directory
9186 @unnumberedsubsubsec Specifying the Object Directory
9189 Several project properties are modeled by Ada-style @emph{attributes};
9190 you define the property by supplying the equivalent of an Ada attribute
9191 definition clause in the project file.
9192 A project's object directory is such a property; the corresponding
9193 attribute is @code{Object_Dir}, and its value is a string expression. A
9194 directory may be specified either as absolute or as relative; in the latter
9195 case, it is relative to the project file directory. Thus the compiler's
9196 output is directed to @file{/common/debug} (for the @code{Debug} project)
9197 and to @file{/common/release} (for the @code{Release} project). If
9198 @code{Object_Dir} is not specified, then the default is the project file
9201 @node Specifying the Exec Directory
9202 @unnumberedsubsubsec Specifying the Exec Directory
9205 A project's exec directory is another property; the corresponding
9206 attribute is @code{Exec_Dir}, and its value is also a string expression,
9207 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
9208 then the default is the object directory (which may also be the project file
9209 directory if attribute @code{Object_Dir} is not specified). Thus the executable
9210 is placed in @file{/common/debug} for the @code{Debug} project (attribute
9211 @code{Exec_Dir} not specified) and in @file{/common} for the @code{Release}
9214 @node Project File Packages
9215 @unnumberedsubsubsec Project File Packages
9218 A GNAT tool integrated with the Project Manager is modeled by a
9219 corresponding package in the project file.
9220 The @code{Debug} project defines the packages @code{Builder}
9221 (for @command{gnatmake}) and @code{Compiler};
9222 the @code{Release} project defines only the @code{Compiler} package.
9224 The Ada package syntax is not to be taken literally. Although packages in
9225 project files bear a surface resemblance to packages in Ada source code, the
9226 notation is simply a way to convey a grouping of properties for a named
9227 entity. Indeed, the package names permitted in project files are restricted
9228 to a predefined set, corresponding to the project-aware tools, and the contents
9229 of packages are limited to a small set of constructs.
9230 The packages in the example above contain attribute definitions.
9233 @node Specifying Switch Settings
9234 @unnumberedsubsubsec Specifying Switch Settings
9237 Switch settings for a project-aware tool can be specified through attributes
9238 in the package corresponding to the tool.
9239 The example above illustrates one of the relevant attributes,
9240 @code{Default_Switches}, defined in the packages in both project files.
9241 Unlike simple attributes like @code{Source_Dirs}, @code{Default_Switches} is
9242 known as an @emph{associative array}. When you define this attribute, you must
9243 supply an "index" (a literal string), and the effect of the attribute
9244 definition is to set the value of the "array" at the specified "index".
9245 For the @code{Default_Switches} attribute, the index is a programming
9246 language (in our case, Ada) , and the value specified (after @code{use})
9247 must be a list of string expressions.
9249 The attributes permitted in project files are restricted to a predefined set.
9250 Some may appear at project level, others in packages.
9251 For any attribute that is an associate array, the index must always be a
9252 literal string, but the restrictions on this string (e.g., a file name or a
9253 language name) depend on the individual attribute.
9254 Also depending on the attribute, its specified value will need to be either a
9255 string or a string list.
9257 In the @code{Debug} project, we set the switches for two tools,
9258 @command{gnatmake} and the compiler, and thus we include corresponding
9259 packages, with each package defining the @code{Default_Switches} attribute
9260 with index @code{"Ada"}.
9261 Note that the package corresponding to
9262 @command{gnatmake} is named @code{Builder}. The @code{Release} project is
9263 similar, but with just the @code{Compiler} package.
9265 In project @code{Debug} above the switches starting with @option{-gnat} that
9266 are specified in package @code{Compiler} could have been placed in package
9267 @code{Builder}, since @command{gnatmake} transmits all such switches to the
9270 @node Main Subprograms
9271 @unnumberedsubsubsec Main Subprograms
9274 One of the properties of a project is its list of main subprograms (actually
9275 a list of names of source files containing main subprograms, with the file
9276 extension optional. This property is captured in the @code{Main} attribute,
9277 whose value is a list of strings. If a project defines the @code{Main}
9278 attribute, then you do not need to identify the main subprogram(s) when
9279 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
9281 @node Source File Naming Conventions
9282 @unnumberedsubsubsec Source File Naming Conventions
9285 Since the project files do not specify any source file naming conventions,
9286 the GNAT defaults are used. The mechanism for defining source file naming
9287 conventions -- a package named @code{Naming} -- will be described below
9288 (@pxref{Naming Schemes}).
9290 @node Source Language(s)
9291 @unnumberedsubsubsec Source Language(s)
9294 Since the project files do not specify a @code{Languages} attribute, by
9295 default the GNAT tools assume that the language of the project file is Ada.
9296 More generally, a project can comprise source files
9297 in Ada, C, and/or other languages.
9299 @node Using External Variables
9300 @subsection Using External Variables
9303 Instead of supplying different project files for debug and release, we can
9304 define a single project file that queries an external variable (set either
9305 on the command line or via an environment variable) in order to
9306 conditionally define the appropriate settings. Again, assume that the
9307 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
9308 located in directory @file{/common}. The following project file,
9309 @file{build.gpr}, queries the external variable named @code{STYLE} and
9310 defines an object directory and switch settings based on whether the value
9311 is @code{"deb"} (debug) or @code{"rel"} (release), where the default is
9317 for Main use ("proc");
9319 type Style_Type is ("deb", "rel");
9320 Style : Style_Type := external ("STYLE", "deb");
9324 for Object_Dir use "debug";
9327 for Object_Dir use "release";
9328 for Exec_Dir use ".";
9337 for Default_Switches ("Ada") use ("-g");
9348 for Default_Switches ("Ada") use ("-gnata", "-gnato", "-gnatE");
9351 for Default_Switches ("Ada") use ("-O2");
9361 @code{Style_Type} is an example of a @emph{string type}, which is the project
9362 file analog of an Ada enumeration type but containing string literals rather
9363 than identifiers. @code{Style} is declared as a variable of this type.
9365 The form @code{external("STYLE", "deb")} is known as an
9366 @emph{external reference}; its first argument is the name of an
9367 @emph{external variable}, and the second argument is a default value to be
9368 used if the external variable doesn't exist. You can define an external
9369 variable on the command line via the @option{-X} switch, or you can use an
9370 environment variable as an external variable.
9372 Each @code{case} construct is expanded by the Project Manager based on the
9373 value of @code{Style}. Thus the command
9375 gnatmake -P/common/build.gpr -XSTYLE=deb
9379 is equivalent to the @command{gnatmake} invocation using the project file
9380 @file{debug.gpr} in the earlier example. So is the command
9382 gnatmake -P/common/build.gpr
9386 since @code{"deb"} is the default for @code{STYLE}.
9390 gnatmake -P/common/build.gpr -XSTYLE=rel
9394 is equivalent to the @command{gnatmake} invocation using the project file
9395 @file{release.gpr} in the earlier example.
9398 @node Importing Other Projects
9399 @subsection Importing Other Projects
9402 A compilation unit in a source file in one project may depend on compilation
9403 units in source files in other projects. To obtain this behavior, the
9404 dependent project must @emph{import} the projects containing the needed source
9405 files. This effect is embodied in syntax similar to an Ada @code{with} clause,
9406 but the "with"ed entities are strings denoting project files.
9408 As an example, suppose that the two projects @code{GUI_Proj} and
9409 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
9410 @file{comm_proj.gpr} in directories @file{/gui} and @file{/comm},
9411 respectively. Assume that the source files for @code{GUI_Proj} are
9412 @file{gui.ads} and @file{gui.adb}, and that the source files for
9413 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, with each set of
9414 files located in its respective project file directory. Diagrammatically:
9433 We want to develop an application in directory @file{/app} that "with"s the
9434 packages @code{GUI} and @code{Comm}, using the properties of the
9435 corresponding project files (e.g. the switch settings and object directory).
9436 Skeletal code for a main procedure might be something like the following:
9441 procedure App_Main is
9450 Here is a project file, @file{app_proj.gpr}, that achieves the desired
9455 with "/gui/gui_proj", "/comm/comm_proj";
9457 for Main use ("app_main");
9463 Building an executable is achieved through the command:
9465 gnatmake -P/app/app_proj
9468 which will generate the @code{app_main} executable in the directory where
9469 @file{app_proj.gpr} resides.
9471 If an imported project file uses the standard extension (@code{gpr}) then
9472 (as illustrated above) the @code{with} clause can omit the extension.
9474 Our example specified an absolute path for each imported project file.
9475 Alternatively, you can omit the directory if either
9478 The imported project file is in the same directory as the importing project
9481 You have defined an environment variable @code{ADA_PROJECT_PATH} that
9482 includes the directory containing the needed project file.
9486 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{/gui} and
9487 @file{/comm}, then our project file @file{app_proj.gpr} could be written as
9492 with "gui_proj", "comm_proj";
9494 for Main use ("app_main");
9500 Importing other projects raises the possibility of ambiguities. For
9501 example, the same unit might be present in different imported projects, or
9502 it might be present in both the importing project and an imported project.
9503 Both of these conditions are errors. Note that in the current version of
9504 the Project Manager, it is illegal to have an ambiguous unit even if the
9505 unit is never referenced by the importing project. This restriction may be
9506 relaxed in a future release.
9508 @node Extending a Project
9509 @subsection Extending a Project
9512 A common situation in large software systems is to have multiple
9513 implementations for a common interface; in Ada terms, multiple versions of a
9514 package body for the same specification. For example, one implementation
9515 might be safe for use in tasking programs, while another might only be used
9516 in sequential applications. This can be modeled in GNAT using the concept
9517 of @emph{project extension}. If one project (the "child") @emph{extends}
9518 another project (the "parent") then by default all source files of the
9519 parent project are inherited by the child, but the child project can
9520 override any of the parent's source files with new versions, and can also
9521 add new files. This facility is the project analog of extension in
9522 Object-Oriented Programming. Project hierarchies are permitted (a child
9523 project may be the parent of yet another project), and a project that
9524 inherits one project can also import other projects.
9526 As an example, suppose that directory @file{/seq} contains the project file
9527 @file{seq_proj.gpr} and the source files @file{pack.ads}, @file{pack.adb},
9528 and @file{proc.adb}:
9541 Note that the project file can simply be empty (that is, no attribute or
9542 package is defined):
9552 implying that its source files are all the Ada source files in the project
9555 Suppose we want to supply an alternate version of @file{pack.adb}, in
9556 directory @file{/tasking}, but use the existing versions of @file{pack.ads}
9557 and @file{proc.adb}. We can define a project @code{Tasking_Proj} that
9558 inherits @code{Seq_Proj}:
9568 project Tasking_Proj extends "/seq/seq_proj" is
9574 The version of @file{pack.adb} used in a build depends on which project file
9577 Note that we could have designed this using project import rather than
9578 project inheritance; a @code{base} project would contain the sources for
9579 @file{pack.ads} and @file{proc.adb}, a sequential project would import
9580 @code{base} and add @file{pack.adb}, and likewise a tasking project would
9581 import @code{base} and add a different version of @file{pack.adb}. The
9582 choice depends on whether other sources in the original project need to be
9583 overridden. If they do, then project extension is necessary, otherwise,
9584 importing is sufficient.
9587 @c ***********************
9588 @c * Project File Syntax *
9589 @c ***********************
9591 @node Project File Syntax
9592 @section Project File Syntax
9601 * Associative Array Attributes::
9602 * case Constructions::
9606 This section describes the structure of project files.
9608 A project may be an @emph{independent project}, entirely defined by a single
9609 project file. Any Ada source file in an independent project depends only
9610 on the predefined library and other Ada source files in the same project.
9613 A project may also @dfn{depend on} other projects, in either or both of the following ways:
9615 @item It may import any number of projects
9616 @item It may extend at most one other project
9620 The dependence relation is a directed acyclic graph (the subgraph reflecting
9621 the "extends" relation is a tree).
9623 A project's @dfn{immediate sources} are the source files directly defined by
9624 that project, either implicitly by residing in the project file's directory,
9625 or explicitly through any of the source-related attributes described below.
9626 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
9627 of @var{proj} together with the immediate sources (unless overridden) of any
9628 project on which @var{proj} depends (either directly or indirectly).
9631 @subsection Basic Syntax
9634 As seen in the earlier examples, project files have an Ada-like syntax.
9635 The minimal project file is:
9645 The identifier @code{Empty} is the name of the project.
9646 This project name must be present after the reserved
9647 word @code{end} at the end of the project file, followed by a semi-colon.
9649 Any name in a project file, such as the project name or a variable name,
9650 has the same syntax as an Ada identifier.
9652 The reserved words of project files are the Ada reserved words plus
9653 @code{extends}, @code{external}, and @code{project}. Note that the only Ada
9654 reserved words currently used in project file syntax are:
9682 Comments in project files have the same syntax as in Ada, two consecutives
9683 hyphens through the end of the line.
9686 @subsection Packages
9689 A project file may contain @emph{packages}. The name of a package must be one
9690 of the identifiers (case insensitive) from a predefined list, and a package
9691 with a given name may only appear once in a project file. The predefined list
9692 includes the following packages:
9708 @code{Cross_Reference}
9714 (The complete list of the package names and their attributes can be found
9715 in file @file{prj-attr.adb}).
9718 In its simplest form, a package may be empty:
9730 A package may contain @emph{attribute declarations},
9731 @emph{variable declarations} and @emph{case constructions}, as will be
9734 When there is ambiguity between a project name and a package name,
9735 the name always designates the project. To avoid possible confusion, it is
9736 always a good idea to avoid naming a project with one of the
9737 names allowed for packages or any name that starts with @code{gnat}.
9741 @subsection Expressions
9744 An @emph{expression} is either a @emph{string expression} or a
9745 @emph{string list expression}.
9747 A @emph{string expression} is either a @emph{simple string expression} or a
9748 @emph{compound string expression}.
9750 A @emph{simple string expression} is one of the following:
9752 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
9753 @item A string-valued variable reference (see @ref{Variables})
9754 @item A string-valued attribute reference (see @ref{Attributes})
9755 @item An external reference (see @ref{External References in Project Files})
9759 A @emph{compound string expression} is a concatenation of string expressions,
9762 Path & "/" & File_Name & ".ads"
9766 A @emph{string list expression} is either a
9767 @emph{simple string list expression} or a
9768 @emph{compound string list expression}.
9770 A @emph{simple string list expression} is one of the following:
9772 @item A parenthesized list of zero or more string expressions, separated by commas
9774 File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
9777 @item A string list-valued variable reference
9778 @item A string list-valued attribute reference
9782 A @emph{compound string list expression} is the concatenation (using
9783 @code{"&"}) of a simple string list expression and an expression. Note that
9784 each term in a compound string list expression, except the first, may be
9785 either a string expression or a string list expression.
9789 File_Name_List := () & File_Name; -- One string in this list
9790 Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
9792 Big_List := File_Name_List & Extended_File_Name_List;
9793 -- Concatenation of two string lists: three strings
9794 Illegal_List := "gnat.adc" & Extended_File_Name_List;
9795 -- Illegal: must start with a string list
9801 @subsection String Types
9804 The value of a variable may be restricted to a list of string literals.
9805 The restricted list of string literals is given in a
9806 @emph{string type declaration}.
9808 Here is an example of a string type declaration:
9811 type OS is ("NT, "nt", "Unix", "Linux", "other OS");
9815 Variables of a string type are called @emph{typed variables}; all other
9816 variables are called @emph{untyped variables}. Typed variables are
9817 particularly useful in @code{case} constructions
9818 (see @ref{case Constructions}).
9820 A string type declaration starts with the reserved word @code{type}, followed
9821 by the name of the string type (case-insensitive), followed by the reserved
9822 word @code{is}, followed by a parenthesized list of one or more string literals
9823 separated by commas, followed by a semicolon.
9825 The string literals in the list are case sensitive and must all be different.
9826 They may include any graphic characters allowed in Ada, including spaces.
9828 A string type may only be declared at the project level, not inside a package.
9830 A string type may be referenced by its name if it has been declared in the same
9831 project file, or by its project name, followed by a dot,
9832 followed by the string type name.
9836 @subsection Variables
9839 A variable may be declared at the project file level, or in a package.
9840 Here are some examples of variable declarations:
9844 This_OS : OS := external ("OS"); -- a typed variable declaration
9845 That_OS := "Linux"; -- an untyped variable declaration
9850 A @emph{typed variable declaration} includes the variable name, followed by a colon,
9851 followed by the name of a string type, followed by @code{:=}, followed by
9852 a simple string expression.
9854 An @emph{untyped variable declaration} includes the variable name,
9855 followed by @code{:=}, followed by an expression. Note that, despite the
9856 terminology, this form of "declaration" resembles more an assignment
9857 than a declaration in Ada. It is a declaration in several senses:
9860 The variable name does not need to be defined previously
9862 The declaration establishes the @emph{kind} (string versus string list) of the
9863 variable, and later declarations of the same variable need to be consistent
9868 A string variable declaration (typed or untyped) declares a variable
9869 whose value is a string. This variable may be used as a string expression.
9871 File_Name := "readme.txt";
9872 Saved_File_Name := File_Name & ".saved";
9876 A string list variable declaration declares a variable whose value is a list
9877 of strings. The list may contain any number (zero or more) of strings.
9881 List_With_One_Element := ("-gnaty");
9882 List_With_Two_Elements := List_With_One_Element & "-gnatg";
9883 Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
9884 "pack2.ada", "util_.ada", "util.ada");
9888 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.
9890 The same untyped variable may be declared several times.
9891 In this case, the new value replaces the old one,
9892 and any subsequent reference to the variable uses the new value.
9893 However, as noted above, if a variable has been declared as a string, all subsequent
9894 declarations must give it a string value. Similarly, if a variable has
9895 been declared as a string list, all subsequent declarations
9896 must give it a string list value.
9898 A @emph{variable reference} may take several forms:
9901 @item The simple variable name, for a variable in the current package (if any) or in the current project
9902 @item A context name, followed by a dot, followed by the variable name.
9906 A @emph{context} may be one of the following:
9909 @item The name of an existing package in the current project
9910 @item The name of an imported project of the current project
9911 @item The name of an ancestor project (i.e., a project extended by the current project, either directly or indirectly)
9912 @item An imported/parent project name, followed by a dot, followed by a package name
9916 A variable reference may be used in an expression.
9920 @subsection Attributes
9923 A project (and its packages) may have @emph{attributes} that define the project's properties.
9924 Some attributes have values that are strings;
9925 others have values that are string lists.
9927 There are two categories of attributes: @emph{simple attributes} and @emph{associative arrays}
9928 (see @ref{Associative Array Attributes}).
9930 The names of the attributes are restricted; there is a list of project
9931 attributes, and a list of package attributes for each package.
9932 The names are not case sensitive.
9934 The project attributes are as follows (all are simple attributes):
9936 @multitable @columnfractions .4 .3
9937 @item @emph{Attribute Name}
9939 @item @code{Source_Files}
9941 @item @code{Source_Dirs}
9943 @item @code{Source_List_File}
9945 @item @code{Object_Dir}
9947 @item @code{Exec_Dir}
9951 @item @code{Languages}
9953 @item @code{Library_Dir}
9955 @item @code{Library_Name}
9957 @item @code{Library_Kind}
9959 @item @code{Library_Elaboration}
9961 @item @code{Library_Version}
9966 The attributes for package @code{Naming} are as follows
9967 (see @ref{Naming Schemes}):
9969 @multitable @columnfractions .4 .2 .2 .2
9970 @item Attribute Name @tab Category @tab Index @tab Value
9971 @item @code{Specification_Suffix}
9972 @tab associative array
9975 @item @code{Implementation_Suffix}
9976 @tab associative array
9979 @item @code{Separate_Suffix}
9980 @tab simple attribute
9984 @tab simple attribute
9987 @item @code{Dot_Replacement}
9988 @tab simple attribute
9991 @item @code{Specification}
9992 @tab associative array
9995 @item @code{Implementation}
9996 @tab associative array
9999 @item @code{Specification_Exceptions}
10000 @tab associative array
10003 @item @code{Implementation_Exceptions}
10004 @tab associative array
10010 The attributes for package @code{Builder}, @code{Compiler}, @code{Binder},
10011 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
10012 are as follows (see @ref{Switches and Project Files}).
10014 @multitable @columnfractions .4 .2 .2 .2
10015 @item Attribute Name @tab Category @tab Index @tab Value
10016 @item @code{Default_Switches}
10017 @tab associative array
10020 @item @code{Switches}
10021 @tab associative array
10027 In addition, package @code{Builder} has a single string attribute
10028 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
10029 string attribute @code{Global_Configuration_Pragmas}.
10032 The attribute for package @code{Glide} are not documented: they are for
10036 Each simple attribute has a default value: the empty string (for string-valued
10037 attributes) and the empty list (for string list-valued attributes).
10039 Similar to variable declarations, an attribute declaration defines a new value
10042 Examples of simple attribute declarations:
10045 for Object_Dir use "objects";
10046 for Source_Dirs use ("units", "test/drivers");
10050 A @dfn{simple attribute declaration} starts with the reserved word @code{for},
10051 followed by the name of the attribute, followed by the reserved word
10052 @code{use}, followed by an expression (whose kind depends on the attribute),
10053 followed by a semicolon.
10055 Attributes may be referenced in expressions.
10056 The general form for such a reference is @code{<entity>'<attribute>}:
10057 the entity for which the attribute is defined,
10058 followed by an apostrophe, followed by the name of the attribute.
10059 For associative array attributes, a litteral string between parentheses
10060 need to be supplied as index.
10066 Naming'Dot_Replacement
10067 Imported_Project'Source_Dirs
10068 Imported_Project.Naming'Casing
10069 Builder'Default_Switches("Ada")
10075 @item @code{project} for an attribute of the current project
10076 @item The name of an existing package of the current project
10077 @item The name of an imported project
10078 @item The name of a parent project (extended by the current project)
10079 @item An imported/parent project name, followed by a dot,
10080 followed by a package name
10088 for Source_Dirs use project'Source_Dirs & "units";
10089 for Source_Dirs use project'Source_Dirs & "test/drivers"
10095 In the first attribute declaration, initially the attribute @code{Source_Dirs}
10096 has the default value: an empty string list. After this declaration,
10097 @code{Source_Dirs} is a string list of one element: "units".
10098 After the second attribute declaration @code{Source_Dirs} is a string list of
10099 two elements: "units" and "test/drivers".
10101 Note: this example is for illustration only. In practice,
10102 the project file would contain only one attribute declaration:
10105 for Source_Dirs use ("units", "test/drivers");
10109 @node Associative Array Attributes
10110 @subsection Associative Array Attributes
10113 Some attributes are defined as @emph{associative arrays}. An associative
10114 array may be regarded as a function that takes a string as a parameter
10115 and delivers a string or string list value as its result.
10117 Here are some examples of associative array attribute declarations:
10120 for Implementation ("main") use "Main.ada";
10121 for Switches ("main.ada") use ("-v", "-gnatv");
10122 for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g";
10126 Like untyped variables and simple attributes, associative array attributes may be declared several times. Each declaration supplies a new value for the
10127 attribute, replacing the previous setting.
10130 @node case Constructions
10131 @subsection @code{case} Constructions
10134 A @code{case} construction is used in a project file to effect conditional
10136 Here is a typical example:
10141 type OS_Type is ("Linux", "Unix", "NT", "VMS");
10143 OS : OS_Type := external ("OS", "Linux");
10147 package Compiler is
10149 when "Linux" | "Unix" =>
10150 for Default_Switches ("Ada") use ("-gnath");
10152 for Default_Switches ("Ada") use ("-gnatP");
10161 The syntax of a @code{case} construction is based on the Ada case statement
10162 (although there is no @code{null} construction for empty alternatives).
10164 Following the reserved word @code{case} there is the case variable (a typed
10165 string variable), the reserved word @code{is}, and then a sequence of one or
10167 Each alternative comprises the reserved word @code{when}, either a list of
10168 literal strings separated by the @code{"|"} character or the reserved word
10169 @code{others}, and the @code{"=>"} token.
10170 Each literal string must belong to the string type that is the type of the
10172 An @code{others} alternative, if present, must occur last.
10173 The @code{end case;} sequence terminates the case construction.
10175 After each @code{=>}, there are zero or more constructions. The only
10176 constructions allowed in a case construction are other case constructions and
10177 attribute declarations. String type declarations, variable declarations and
10178 package declarations are not allowed.
10180 The value of the case variable is often given by an external reference
10181 (see @ref{External References in Project Files}).
10184 @c ****************************************
10185 @c * Objects and Sources in Project Files *
10186 @c ****************************************
10188 @node Objects and Sources in Project Files
10189 @section Objects and Sources in Project Files
10192 * Object Directory::
10194 * Source Directories::
10195 * Source File Names::
10199 Each project has exactly one object directory and one or more source
10200 directories. The source directories must contain at least one source file,
10201 unless the project file explicitly specifies that no source files are present
10202 (see @ref{Source File Names}).
10205 @node Object Directory
10206 @subsection Object Directory
10209 The object directory for a project is the directory containing the compiler's
10210 output (such as @file{ALI} files and object files) for the project's immediate
10211 sources. Note that for inherited sources (when extending a parent project) the
10212 parent project's object directory is used.
10214 The object directory is given by the value of the attribute @code{Object_Dir}
10215 in the project file.
10218 for Object_Dir use "objects";
10222 The attribute @var{Object_Dir} has a string value, the path name of the object
10223 directory. The path name may be absolute or relative to the directory of the
10224 project file. This directory must already exist, and be readable and writable.
10226 By default, when the attribute @code{Object_Dir} is not given an explicit value
10227 or when its value is the empty string, the object directory is the same as the
10228 directory containing the project file.
10231 @node Exec Directory
10232 @subsection Exec Directory
10235 The exec directory for a project is the directory containing the executables
10236 for the project's main subprograms.
10238 The exec directory is given by the value of the attribute @code{Exec_Dir}
10239 in the project file.
10242 for Exec_Dir use "executables";
10246 The attribute @var{Exec_Dir} has a string value, the path name of the exec
10247 directory. The path name may be absolute or relative to the directory of the
10248 project file. This directory must already exist, and be writable.
10250 By default, when the attribute @code{Exec_Dir} is not given an explicit value
10251 or when its value is the empty string, the exec directory is the same as the
10252 object directory of the project file.
10255 @node Source Directories
10256 @subsection Source Directories
10259 The source directories of a project are specified by the project file
10260 attribute @code{Source_Dirs}.
10262 This attribute's value is a string list. If the attribute is not given an
10263 explicit value, then there is only one source directory, the one where the
10264 project file resides.
10266 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
10270 for Source_Dirs use ();
10274 indicates that the project contains no source files.
10276 Otherwise, each string in the string list designates one or more
10277 source directories.
10280 for Source_Dirs use ("sources", "test/drivers");
10284 If a string in the list ends with @code{"/**"}, then the directory whose path
10285 name precedes the two asterisks, as well as all its subdirectories
10286 (recursively), are source directories.
10289 for Source_Dirs use ("/system/sources/**");
10293 Here the directory @code{/system/sources} and all of its subdirectories
10294 (recursively) are source directories.
10296 To specify that the source directories are the directory of the project file
10297 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
10299 for Source_Dirs use ("./**");
10303 Each of the source directories must exist and be readable.
10306 @node Source File Names
10307 @subsection Source File Names
10310 In a project that contains source files, their names may be specified by the
10311 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
10312 (a string). Source file names never include any directory information.
10314 If the attribute @code{Source_Files} is given an explicit value, then each
10315 element of the list is a source file name.
10318 for Source_Files use ("main.adb");
10319 for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
10323 If the attribute @code{Source_Files} is not given an explicit value,
10324 but the attribute @code{Source_List_File} is given a string value,
10325 then the source file names are contained in the text file whose path name
10326 (absolute or relative to the directory of the project file) is the
10327 value of the attribute @code{Source_List_File}.
10329 Each line in the file that is not empty or is not a comment
10330 contains a source file name. A comment line starts with two hyphens.
10333 for Source_List_File use "source_list.txt";
10337 By default, if neither the attribute @code{Source_Files} nor the attribute
10338 @code{Source_List_File} is given an explicit value, then each file in the
10339 source directories that conforms to the project's naming scheme
10340 (see @ref{Naming Schemes}) is an immediate source of the project.
10342 A warning is issued if both attributes @code{Source_Files} and
10343 @code{Source_List_File} are given explicit values. In this case, the attribute
10344 @code{Source_Files} prevails.
10346 Each source file name must be the name of one and only one existing source file
10347 in one of the source directories.
10349 A @code{Source_Files} attribute defined with an empty list as its value
10350 indicates that there are no source files in the project.
10352 Except for projects that are clearly specified as containing no Ada source
10353 files (@code{Source_Dirs} or @code{Source_Files} specified as an empty list,
10354 or @code{Languages} specified without @code{"Ada"} in the list)
10356 for Source_Dirs use ();
10357 for Source_Files use ();
10358 for Languages use ("C", "C++");
10362 a project must contain at least one immediate source.
10364 Projects with no source files are useful as template packages
10365 (see @ref{Packages in Project Files}) for other projects; in particular to
10366 define a package @code{Naming} (see @ref{Naming Schemes}).
10369 @c ****************************
10370 @c * Importing Projects *
10371 @c ****************************
10373 @node Importing Projects
10374 @section Importing Projects
10377 An immediate source of a project P may depend on source files that
10378 are neither immediate sources of P nor in the predefined library.
10379 To get this effect, P must @emph{import} the projects that contain the needed
10384 with "project1", "utilities.gpr";
10385 with "/namings/apex.gpr";
10392 As can be seen in this example, the syntax for importing projects is similar
10393 to the syntax for importing compilation units in Ada. However, project files
10394 use literal strings instead of names, and the @code{with} clause identifies
10395 project files rather than packages.
10397 Each literal string is the file name or path name (absolute or relative) of a
10398 project file. If a string is simply a file name, with no path, then its
10399 location is determined by the @emph{project path}:
10403 If the environment variable @env{ADA_PROJECT_PATH} exists, then the project
10404 path includes all the directories in this environment variable, plus the
10405 directory of the project file.
10408 If the environment variable @env{ADA_PROJECT_PATH} does not exist,
10409 then the project path contains only one directory, namely the one where
10410 the project file is located.
10414 If a relative pathname is used as in
10421 then the path is relative to the directory where the importing project file is
10422 located. Any symbolic link will be fully resolved in the directory
10423 of the importing project file before the imported project file is looked up.
10425 When the @code{with}'ed project file name does not have an extension,
10426 the default is @file{.gpr}. If a file with this extension is not found, then
10427 the file name as specified in the @code{with} clause (no extension) will be
10428 used. In the above example, if a file @code{project1.gpr} is found, then it
10429 will be used; otherwise, if a file @code{project1} exists then it will be used;
10430 if neither file exists, this is an error.
10432 A warning is issued if the name of the project file does not match the
10433 name of the project; this check is case insensitive.
10435 Any source file that is an immediate source of the imported project can be
10436 used by the immediate sources of the importing project, and recursively. Thus
10437 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
10438 sources of @code{A} may depend on the immediate sources of @code{C}, even if
10439 @code{A} does not import @code{C} explicitly. However, this is not recommended,
10440 because if and when @code{B} ceases to import @code{C}, some sources in
10441 @code{A} will no longer compile.
10443 A side effect of this capability is that cyclic dependences are not permitted:
10444 if @code{A} imports @code{B} (directly or indirectly) then @code{B} is not
10445 allowed to import @code{A}.
10448 @c *********************
10449 @c * Project Extension *
10450 @c *********************
10452 @node Project Extension
10453 @section Project Extension
10456 During development of a large system, it is sometimes necessary to use
10457 modified versions of some of the source files without changing the original
10458 sources. This can be achieved through a facility known as
10459 @emph{project extension}.
10462 project Modified_Utilities extends "/baseline/utilities.gpr" is ...
10466 The project file for the project being extended (the @emph{parent}) is
10467 identified by the literal string that follows the reserved word @code{extends},
10468 which itself follows the name of the extending project (the @emph{child}).
10470 By default, a child project inherits all the sources of its parent.
10471 However, inherited sources can be overridden: a unit with the same name as one
10472 in the parent will hide the original unit.
10473 Inherited sources are considered to be sources (but not immediate sources)
10474 of the child project; see @ref{Project File Syntax}.
10476 An inherited source file retains any switches specified in the parent project.
10478 For example if the project @code{Utilities} contains the specification and the
10479 body of an Ada package @code{Util_IO}, then the project
10480 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
10481 The original body of @code{Util_IO} will not be considered in program builds.
10482 However, the package specification will still be found in the project
10485 A child project can have only one parent but it may import any number of other
10488 A project is not allowed to import directly or indirectly at the same time a
10489 child project and any of its ancestors.
10492 @c ****************************************
10493 @c * External References in Project Files *
10494 @c ****************************************
10496 @node External References in Project Files
10497 @section External References in Project Files
10500 A project file may contain references to external variables; such references
10501 are called @emph{external references}.
10503 An external variable is either defined as part of the environment (an
10504 environment variable in Unix, for example) or else specified on the command
10505 line via the @option{-X@emph{vbl}=@emph{value}} switch. If both, then the
10506 command line value is used.
10508 An external reference is denoted by the built-in function
10509 @code{external}, which returns a string value. This function has two forms:
10511 @item @code{external (external_variable_name)}
10512 @item @code{external (external_variable_name, default_value)}
10516 Each parameter must be a string literal. For example:
10520 external ("OS", "Linux")
10524 In the form with one parameter, the function returns the value of
10525 the external variable given as parameter. If this name is not present in the
10526 environment, then the returned value is an empty string.
10528 In the form with two string parameters, the second parameter is
10529 the value returned when the variable given as the first parameter is not
10530 present in the environment. In the example above, if @code{"OS"} is not
10531 the name of an environment variable and is not passed on the command line,
10532 then the returned value will be @code{"Linux"}.
10534 An external reference may be part of a string expression or of a string
10535 list expression, to define variables or attributes.
10539 type Mode_Type is ("Debug", "Release");
10540 Mode : Mode_Type := external ("MODE");
10548 @c *****************************
10549 @c * Packages in Project Files *
10550 @c *****************************
10552 @node Packages in Project Files
10553 @section Packages in Project Files
10556 The @emph{package} is the project file feature that defines the settings for
10557 project-aware tools.
10558 For each such tool you can declare a corresponding package; the names for these
10559 packages are preset (see @ref{Packages}) but are not case sensitive.
10560 A package may contain variable declarations, attribute declarations, and case
10566 package Builder is -- used by gnatmake
10567 for Default_Switches ("Ada") use ("-v", "-g");
10574 A package declaration starts with the reserved word @code{package},
10575 followed by the package name (case insensitive), followed by the reserved word
10576 @code{is}. It ends with the reserved word @code{end}, followed by the package
10577 name, finally followed by a semi-colon.
10579 Most of the packages have an attribute @code{Default_Switches}.
10580 This attribute is an associative array, and its value is a string list.
10581 The index of the associative array is the name of a programming language (case
10582 insensitive). This attribute indicates the switch or switches to be used
10583 with the corresponding tool.
10585 Some packages also have another attribute, @code{Switches}, an associative
10586 array whose value is a string list. The index is the name of a source file.
10587 This attribute indicates the switch or switches to be used by the corresponding
10588 tool when dealing with this specific file.
10590 Further information on these switch-related attributes is found in
10591 @ref{Switches and Project Files}.
10593 A package may be declared as a @emph{renaming} of another package; e.g., from
10594 the project file for an imported project.
10598 with "/global/apex.gpr";
10600 package Naming renames Apex.Naming;
10607 Packages that are renamed in other project files often come from project files
10608 that have no sources: they are just used as templates. Any modification in the
10609 template will be reflected automatically in all the project files that rename
10610 a package from the template.
10612 In addition to the tool-oriented packages, you can also declare a package
10613 named @code{Naming} to establish specialized source file naming conventions
10614 (see @ref{Naming Schemes}).
10617 @c ************************************
10618 @c * Variables from Imported Projects *
10619 @c ************************************
10621 @node Variables from Imported Projects
10622 @section Variables from Imported Projects
10625 An attribute or variable defined in an imported or parent project can
10626 be used in expressions in the importing / extending project.
10627 Such an attribute or variable is prefixed with the name of the project
10628 and (if relevant) the name of package where it is defined.
10633 project Main extends "base" is
10634 Var1 := Imported.Var;
10635 Var2 := Base.Var & ".new";
10640 for Default_Switches ("Ada") use Imported.Builder.Ada_Switches &
10646 package Compiler is
10647 for Default_Switches ("Ada") use Base.Compiler.Ada_Switches;
10658 @code{Var1} is a copy of the variable @code{Var} defined in the project file
10659 @file{"imported.gpr"}
10661 the value of @code{Var2} is a copy of the value of variable @code{Var}
10662 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
10664 attribute @code{Default_Switches ("Ada")} in package @code{Builder}
10665 is a string list that includes in its value a copy of variable
10666 @code{Ada_Switches} defined in the @code{Builder} package in project file
10667 @file{imported.gpr} plus two new elements: @option{"-gnatg"} and @option{"-v"};
10669 attribute @code{Default_Switches ("Ada")} in package @code{Compiler}
10670 is a copy of the variable @code{Ada_Switches} defined in the @code{Compiler}
10671 package in project file @file{base.gpr}, the project being extended.
10675 @c ******************
10676 @c * Naming Schemes *
10677 @c ******************
10679 @node Naming Schemes
10680 @section Naming Schemes
10683 Sometimes an Ada software system is ported from a foreign compilation
10684 environment to GNAT, with file names that do not use the default GNAT
10685 conventions. Instead of changing all the file names (which for a variety of
10686 reasons might not be possible), you can define the relevant file naming scheme
10687 in the @code{Naming} package in your project file. For example, the following
10688 package models the Apex file naming rules:
10693 for Casing use "lowercase";
10694 for Dot_Replacement use ".";
10695 for Specification_Suffix ("Ada") use ".1.ada";
10696 for Implementation_Suffix ("Ada") use ".2.ada";
10702 You can define the following attributes in package @code{Naming}:
10707 This must be a string with one of the three values @code{"lowercase"},
10708 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
10711 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
10713 @item @var{Dot_Replacement}
10714 This must be a string whose value satisfies the following conditions:
10717 @item It must not be empty
10718 @item It cannot start or end with an alphanumeric character
10719 @item It cannot be a single underscore
10720 @item It cannot start with an underscore followed by an alphanumeric
10721 @item It cannot contain a dot @code{'.'} except if it the entire string is @code{"."}
10725 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
10727 @item @var{Specification_Suffix}
10728 This is an associative array (indexed by the programming language name, case
10729 insensitive) whose value is a string that must satisfy the following
10733 @item It must not be empty
10734 @item It cannot start with an alphanumeric character
10735 @item It cannot start with an underscore followed by an alphanumeric character
10738 If @code{Specification_Suffix ("Ada")} is not specified, then the default is
10741 @item @var{Implementation_Suffix}
10742 This is an associative array (indexed by the programming language name, case
10743 insensitive) whose value is a string that must satisfy the following
10747 @item It must not be empty
10748 @item It cannot start with an alphanumeric character
10749 @item It cannot start with an underscore followed by an alphanumeric character
10750 @item It cannot be a suffix of @code{Specification_Suffix}
10753 If @code{Implementation_Suffix ("Ada")} is not specified, then the default is
10756 @item @var{Separate_Suffix}
10757 This must be a string whose value satisfies the same conditions as
10758 @code{Implementation_Suffix}.
10761 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
10762 value as @code{Implementation_Suffix ("Ada")}.
10764 @item @var{Specification}
10766 You can use the @code{Specification} attribute, an associative array, to define
10767 the source file name for an individual Ada compilation unit's spec. The array
10768 index must be a string literal that identifies the Ada unit (case insensitive).
10769 The value of this attribute must be a string that identifies the file that
10770 contains this unit's spec (case sensitive or insensitive depending on the
10774 for Specification ("MyPack.MyChild") use "mypack.mychild.spec";
10777 @item @var{Implementation}
10779 You can use the @code{Implementation} attribute, an associative array, to
10780 define the source file name for an individual Ada compilation unit's body
10781 (possibly a subunit). The array index must be a string literal that identifies
10782 the Ada unit (case insensitive). The value of this attribute must be a string
10783 that identifies the file that contains this unit's body or subunit (case
10784 sensitive or insensitive depending on the operating system).
10787 for Implementation ("MyPack.MyChild") use "mypack.mychild.body";
10792 @c ********************
10793 @c * Library Projects *
10794 @c ********************
10796 @node Library Projects
10797 @section Library Projects
10800 @emph{Library projects} are projects whose object code is placed in a library.
10801 (Note that this facility is not yet supported on all platforms)
10803 To create a library project, you need to define in its project file
10804 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
10805 Additionally, you may define the library-related attributes
10806 @code{Library_Kind}, @code{Library_Version} and @code{Library_Elaboration}.
10808 The @code{Library_Name} attribute has a string value that must start with a
10809 letter and include only letters and digits.
10811 The @code{Library_Dir} attribute has a string value that designates the path
10812 (absolute or relative) of the directory where the library will reside.
10813 It must designate an existing directory, and this directory needs to be
10814 different from the project's object directory. It also needs to be writable.
10816 If both @code{Library_Name} and @code{Library_Dir} are specified and
10817 are legal, then the project file defines a library project. The optional
10818 library-related attributes are checked only for such project files.
10820 The @code{Library_Kind} attribute has a string value that must be one of the
10821 following (case insensitive): @code{"static"}, @code{"dynamic"} or
10822 @code{"relocatable"}. If this attribute is not specified, the library is a
10823 static library. Otherwise, the library may be dynamic or relocatable.
10824 Depending on the operating system, there may or may not be a distinction
10825 between dynamic and relocatable libraries. For example, on Unix there is no
10828 The @code{Library_Version} attribute has a string value whose interpretation
10829 is platform dependent. On Unix, it is used only for dynamic/relocatable
10830 libraries as the internal name of the library (the @code{"soname"}). If the
10831 library file name (built from the @code{Library_Name}) is different from the
10832 @code{Library_Version}, then the library file will be a symbolic link to the
10833 actual file whose name will be @code{Library_Version}.
10843 for Library_Dir use "lib_dir";
10844 for Library_Name use "dummy";
10845 for Library_Kind use "relocatable";
10846 for Library_Version use "libdummy.so." & Version;
10853 Directory @file{lib_dir} will contain the internal library file whose name
10854 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
10855 @file{libdummy.so.1}.
10857 When @command{gnatmake} detects that a project file (not the main project file)
10858 is a library project file, it will check all immediate sources of the project
10859 and rebuild the library if any of the sources have been recompiled.
10860 All @file{ALI} files will also be copied from the object directory to the
10861 library directory. To build executables, @command{gnatmake} will use the
10862 library rather than the individual object files.
10865 @c *************************************
10866 @c * Switches Related to Project Files *
10867 @c *************************************
10868 @node Switches Related to Project Files
10869 @section Switches Related to Project Files
10872 The following switches are used by GNAT tools that support project files:
10876 @item @option{-P@var{project}}
10877 Indicates the name of a project file. This project file will be parsed with
10878 the verbosity indicated by @option{-vP@emph{x}}, if any, and using the external
10879 references indicated by @option{-X} switches, if any.
10882 There must be only one @option{-P} switch on the command line.
10885 Since the Project Manager parses the project file only after all the switches
10886 on the command line are checked, the order of the switches @option{-P},
10887 @option{-Vp@emph{x}} or @option{-X} is not significant.
10889 @item @option{-X@var{name=value}}
10890 Indicates that external variable @var{name} has the value @var{value}.
10891 The Project Manager will use this value for occurrences of
10892 @code{external(name)} when parsing the project file.
10895 If @var{name} or @var{value} includes a space, then @var{name=value} should be
10896 put between quotes.
10903 Several @option{-X} switches can be used simultaneously.
10904 If several @option{-X} switches specify the same @var{name}, only the last one
10908 An external variable specified with a @option{-X} switch takes precedence
10909 over the value of the same name in the environment.
10911 @item @option{-vP@emph{x}}
10912 Indicates the verbosity of the parsing of GNAT project files.
10913 @option{-vP0} means Default (no output for syntactically correct project
10915 @option{-vP1} means Medium;
10916 @option{-vP2} means High.
10918 The default is Default.
10920 If several @option{-vP@emph{x}} switches are present, only the last one is
10926 @c **********************************
10927 @c * Tools Supporting Project Files *
10928 @c **********************************
10930 @node Tools Supporting Project Files
10931 @section Tools Supporting Project Files
10934 * gnatmake and Project Files::
10935 * The GNAT Driver and Project Files::
10937 * Glide and Project Files::
10941 @node gnatmake and Project Files
10942 @subsection gnatmake and Project Files
10945 This section covers two topics related to @command{gnatmake} and project files:
10946 defining switches for @command{gnatmake} and for the tools that it invokes;
10947 and the use of the @code{Main} attribute.
10950 * Switches and Project Files::
10951 * Project Files and Main Subprograms::
10954 @node Switches and Project Files
10955 @subsubsection Switches and Project Files
10958 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
10959 @code{Linker}, you can specify a @code{Default_Switches} attribute, a
10960 @code{Switches} attribute, or both; as their names imply, these switch-related
10961 attributes affect which switches are used for which files when
10962 @command{gnatmake} is invoked. As will be explained below, these
10963 package-contributed switches precede the switches passed on the
10964 @command{gnatmake} command line.
10966 The @code{Default_Switches} attribute is an associative array indexed by
10967 language name (case insensitive) and returning a string list. For example:
10971 package Compiler is
10972 for Default_Switches ("Ada") use ("-gnaty", "-v");
10978 The @code{Switches} attribute is also an associative array, indexed by a file
10979 name (which may or may not be case sensitive, depending on the operating
10980 system) and returning a string list. For example:
10985 for Switches ("main1.adb") use ("-O2");
10986 for Switches ("main2.adb") use ("-g");
10992 For the @code{Builder} package, the file names should designate source files
10993 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
10994 file names should designate @file{ALI} or source files for main subprograms.
10995 In each case just the file name (without explicit extension) is acceptable.
10997 For each tool used in a program build (@command{gnatmake}, the compiler, the
10998 binder, and the linker), its corresponding package @dfn{contributes} a set of
10999 switches for each file on which the tool is invoked, based on the
11000 switch-related attributes defined in the package. In particular, the switches
11001 that each of these packages contributes for a given file @var{f} comprise:
11005 the value of attribute @code{Switches (@var{f})}, if it is specified in the
11006 package for the given file,
11008 otherwise, the value of @code{Default_Switches ("Ada")}, if it is specified in
11013 If neither of these attributes is defined in the package, then the package does
11014 not contribute any switches for the given file.
11016 When @command{gnatmake} is invoked on a file, the switches comprise two sets,
11017 in the following order: those contributed for the file by the @code{Builder}
11018 package; and the switches passed on the command line.
11020 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
11021 the switches passed to the tool comprise three sets, in the following order:
11025 the applicable switches contributed for the file by the @code{Builder} package
11026 in the project file supplied on the command line;
11029 those contributed for the file by the package (in the relevant project file --
11030 see below) corresponding to the tool; and
11033 the applicable switches passed on the command line.
11037 The term @emph{applicable switches} reflects the fact that @command{gnatmake}
11038 switches may or may not be passed to individual tools, depending on the
11041 @command{gnatmake} may invoke the compiler on source files from different
11042 projects. The Project Manager will use the appropriate project file to
11043 determine the @code{Compiler} package for each source file being compiled.
11044 Likewise for the @code{Binder} and @code{Linker} packages.
11046 As an example, consider the following package in a project file:
11051 package Compiler is
11052 for Default_Switches ("Ada") use ("-g");
11053 for Switches ("a.adb") use ("-O1");
11054 for Switches ("b.adb") use ("-O2", "-gnaty");
11061 If @command{gnatmake} is invoked with this project file, and it needs to
11062 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
11063 @file{a.adb} will be compiled with the switch @option{-O1}, @file{b.adb}
11064 with switches @option{-O2} and @option{-gnaty}, and @file{c.adb} with
11067 Another example illustrates the ordering of the switches contributed by
11068 different packages:
11074 for Switches ("main.adb") use ("-g", "-O1", "-f");
11079 package Compiler is
11080 for Switches ("main.adb") use ("-O2");
11087 If you issue the command:
11090 gnatmake -PProj2 -O0 main
11094 then the compiler will be invoked on @file{main.adb} with the following sequence of switches
11100 with the last @option{-O} switch having precedence over the earlier ones;
11101 several other switches (such as @option{-c}) are added implicitly.
11103 The switches @option{-g} and @option{-O1} are contributed by package
11104 @code{Builder}, @option{-O2} is contributed by the package @code{Compiler}
11105 and @option{-O0} comes from the command line.
11107 The @option{-g} switch will also be passed in the invocation of
11108 @command{gnatlink.}
11110 A final example illustrates switch contributions from packages in different
11116 for Source_Files use ("pack.ads", "pack.adb");
11117 package Compiler is
11118 for Default_Switches ("Ada") use ("-gnata");
11126 for Source_Files use ("foo_main.adb", "bar_main.adb");
11128 for Switches ("foo_main.adb") use ("-s", "-g");
11134 -- Ada source file:
11136 procedure Foo_Main is
11144 gnatmake -PProj4 foo_main.adb -cargs -gnato
11148 then the switches passed to the compiler for @file{foo_main.adb} are
11149 @option{-g} (contributed by the package @code{Proj4.Builder}) and
11150 @option{-gnato} (passed on the command line).
11151 When the imported package @code{Pack} is compiled, the switches used are
11152 @option{-g} from @code{Proj4.Builder}, @option{-gnata} (contributed from
11153 package @code{Proj3.Compiler}, and @option{-gnato} from the command line.
11156 @node Project Files and Main Subprograms
11157 @subsubsection Project Files and Main Subprograms
11160 When using a project file, you can invoke @command{gnatmake}
11161 with several main subprograms, by specifying their source files on the command
11162 line. Each of these needs to be an immediate source file of the project.
11165 gnatmake -Pprj main1 main2 main3
11169 When using a project file, you can also invoke @command{gnatmake} without
11170 explicitly specifying any main, and the effect depends on whether you have
11171 defined the @code{Main} attribute. This attribute has a string list value,
11172 where each element in the list is the name of a source file (the file
11173 extension is optional) containing a main subprogram.
11175 If the @code{Main} attribute is defined in a project file as a non-empty
11176 string list and the switch @option{-u} is not used on the command line, then
11177 invoking @command{gnatmake} with this project file but without any main on the
11178 command line is equivalent to invoking @command{gnatmake} with all the file
11179 names in the @code{Main} attribute on the command line.
11185 for Main use ("main1", "main2", "main3");
11191 With this project file, @code{"gnatmake -Pprj"} is equivalent to
11192 @code{"gnatmake -Pprj main1 main2 main3"}.
11194 When the project attribute @code{Main} is not specified, or is specified
11195 as an empty string list, or when the switch @option{-u} is used on the command
11196 line, then invoking @command{gnatmake} with no main on the command line will
11197 result in all immediate sources of the project file being checked, and
11198 potentially recompiled. Depending on the presence of the switch @option{-u},
11199 sources from other project files on which the immediate sources of the main
11200 project file depend are also checked and potentially recompiled. In other
11201 words, the @option{-u} switch is applied to all of the immediate sources of themain project file.
11204 @node The GNAT Driver and Project Files
11205 @subsection The GNAT Driver and Project Files
11208 A number of GNAT tools, other than @command{gnatmake} are project-aware:
11209 @command{gnatbind}, @command{gnatfind}, @command{gnatlink}, @command{gnatls}
11210 and @command{gnatxref}. However, none of these tools can be invoked directly
11211 with a project file switch (@code{-P}). They need to be invoke through the
11212 @command{gnat} driver.
11214 The @command{gnat} driver is a front-end that accepts a number of commands and
11215 call the corresponding tool. It has been designed initially for VMS to convert
11216 VMS style qualifiers to Unix style switches, but it is now available to all
11217 the GNAT supported platforms.
11219 On non VMS platforms, the @command{gnat} driver accepts the following commands
11220 (case insensitive):
11224 BIND to invoke @command{gnatbind}
11226 CHOP to invoke @command{gnatchop}
11228 COMP or COMPILE to invoke the compiler
11230 ELIM to invoke @command{gnatelim}
11232 FIND to invoke @command{gnatfind}
11234 KR or KRUNCH to invoke @command{gnatkr}
11236 LINK to invoke @command{gnatlink}
11238 LS or LIST to invoke @command{gnatls}
11240 MAKE to invoke @command{gnatmake}
11242 NAME to invoke @command{gnatname}
11244 PREP or PREPROCESS to invoke @command{gnatprep}
11246 PSTA or STANDARD to invoke @command{gnatpsta}
11248 STUB to invoke @command{gnatstub}
11250 XREF to invoke @command{gnatxref}
11254 Note that the compiler is invoked using the command @command{gnatmake -f -u}.
11257 Following the command, you may put switches and arguments for the invoked
11261 gnat bind -C main.ali
11267 In addition, for command BIND, FIND, LS or LIST, LINK and XREF, the project
11268 file related switches (@code{-P}, @code{-X} and @code{-vPx}) may be used in
11269 addition to the switches of the invoking tool.
11272 For each of these command, there is possibly a package in the main project that
11273 corresponds to the invoked tool.
11277 package @code{Binder} for command BIND (invoking @code{gnatbind})
11280 package @code{Finder} for command FIND (invoking @code{gnatfind})
11283 package @code{Gnatls} for command LS or LIST (invoking @code{gnatls})
11286 package @code{Linker} for command LINK (invoking @code{gnatlink})
11289 package @code{Cross_Reference} for command XREF (invoking @code{gnatlink})
11294 Package @code{Gnatls} has a unique attribute @code{Switches}, a simple variable
11295 with a string list value. It contains switches for the invocation of
11302 for Switches use ("-a", "-v");
11309 All other packages contains a switch @code{Default_Switches}, an associative
11310 array, indexed by the programming language (case insensitive) and having a
11311 string list value. @code{Default_Switches ("Ada")} contains the switches for
11312 the invocation of the tool corresponding to the package.
11318 for Source_Dirs use ("./**");
11321 for Switches use ("-a", "-v");
11327 for Default_Switches ("Ada") use ("-C", "-e");
11333 for Default_Switches ("Ada") use ("-C");
11339 for Default_Switches ("Ada") use ("-a", "-f");
11344 package Cross_Reference is
11345 for Default_Switches ("Ada") use ("-a", "-f", "-d", "-u");
11346 end Cross_Reference;
11352 With the above project file, commands such as
11355 gnat ls -Pproj main
11356 gnat xref -Pproj main
11357 gnat bind -Pproj main.ali
11361 will set up the environment properly and invoke the tool with the switches
11362 found in the package corresponding to the tool.
11366 @node Glide and Project Files
11367 @subsection Glide and Project Files
11370 Glide will automatically recognize the @file{.gpr} extension for
11371 project files, and will
11372 convert them to its own internal format automatically. However, it
11373 doesn't provide a syntax-oriented editor for modifying these
11375 The project file will be loaded as text when you select the menu item
11376 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
11377 You can edit this text and save the @file{gpr} file;
11378 when you next select this project file in Glide it
11379 will be automatically reloaded.
11382 Glide uses the @code{gnatlist} attribute in the @code{Ide} package, whose value
11383 is something like @code{powerpc-wrs-vxworks-gnatls}, to compute the
11384 cross-prefix. From this information the correct location for the
11385 GNAT runtime, and thus also the correct cross-references, can be
11391 @node An Extended Example
11392 @section An Extended Example
11395 Suppose that we have two programs, @var{prog1} and @var{prog2}, with the sources
11396 in the respective directories. We would like to build them with a single
11397 @command{gnatmake} command, and we would like to place their object files into
11398 @file{.build} subdirectories of the source directories. Furthermore, we would
11399 like to have to have two separate subdirectories in @file{.build} --
11400 @file{release} and @file{debug} -- which will contain the object files compiled with
11401 different set of compilation flags.
11403 In other words, we have the following structure:
11420 Here are the project files that we need to create in a directory @file{main}
11421 to maintain this structure:
11425 @item We create a @code{Common} project with a package @code{Compiler} that
11426 specifies the compilation switches:
11431 @b{project} Common @b{is}
11433 @b{for} Source_Dirs @b{use} (); -- No source files
11437 @b{type} Build_Type @b{is} ("release", "debug");
11438 Build : Build_Type := External ("BUILD", "debug");
11441 @b{package} Compiler @b{is}
11442 @b{case} Build @b{is}
11443 @b{when} "release" =>
11444 @b{for} Default_Switches ("Ada") @b{use} ("-O2");
11445 @b{when} "debug" =>
11446 @b{for} Default_Switches ("Ada") @b{use} ("-g");
11454 @item We create separate projects for the two programs:
11461 @b{project} Prog1 @b{is}
11463 @b{for} Source_Dirs @b{use} ("prog1");
11464 @b{for} Object_Dir @b{use} "prog1/.build/" & Common.Build;
11466 @b{package} Compiler @b{renames} Common.Compiler;
11477 @b{project} Prog2 @b{is}
11479 @b{for} Source_Dirs @b{use} ("prog2");
11480 @b{for} Object_Dir @b{use} "prog2/.build/" & Common.Build;
11482 @b{package} Compiler @b{renames} Common.Compiler;
11488 @item We create a wrapping project @var{Main}:
11497 @b{project} Main @b{is}
11499 @b{package} Compiler @b{renames} Common.Compiler;
11505 @item Finally we need to create a dummy procedure that @code{with}s (either
11506 explicitly or implicitly) all the sources of our two programs.
11511 Now we can build the programs using the command
11514 gnatmake -Pmain dummy
11518 for the Debug mode, or
11521 gnatmake -Pmain -XBUILD=release
11525 for the Release mode.
11528 @c ********************************
11529 @c * Project File Complete Syntax *
11530 @c ********************************
11532 @node Project File Complete Syntax
11533 @section Project File Complete Syntax
11537 context_clause project_declaration
11543 @b{with} literal_string @{ , literal_string @} ;
11545 project_declaration ::=
11546 @b{project} <project_>simple_name [ @b{extends} literal_string ] @b{is}
11547 @{declarative_item@}
11548 @b{end} <project_>simple_name;
11550 declarative_item ::=
11551 package_declaration |
11552 typed_string_declaration |
11553 other_declarative_item
11555 package_declaration ::=
11556 @b{package} <package_>simple_name package_completion
11558 package_completion ::=
11559 package_body | package_renaming
11563 @{other_declarative_item@}
11564 @b{end} <package_>simple_name ;
11566 package_renaming ::==
11567 @b{renames} <project_>simple_name.<package_>simple_name ;
11569 typed_string_declaration ::=
11570 @b{type} <typed_string_>_simple_name @b{is}
11571 ( literal_string @{, literal_string@} );
11573 other_declarative_item ::=
11574 attribute_declaration |
11575 typed_variable_declaration |
11576 variable_declaration |
11579 attribute_declaration ::=
11580 @b{for} attribute @b{use} expression ;
11583 <simple_attribute_>simple_name |
11584 <associative_array_attribute_>simple_name ( literal_string )
11586 typed_variable_declaration ::=
11587 <typed_variable_>simple_name : <typed_string_>name := string_expression ;
11589 variable_declaration ::=
11590 <variable_>simple_name := expression;
11600 attribute_reference
11606 ( <string_>expression @{ , <string_>expression @} )
11609 @b{external} ( literal_string [, literal_string] )
11611 attribute_reference ::=
11612 attribute_parent ' <simple_attribute_>simple_name [ ( literal_string ) ]
11614 attribute_parent ::=
11616 <project_or_package>simple_name |
11617 <project_>simple_name . <package_>simple_name
11619 case_construction ::=
11620 @b{case} <typed_variable_>name @b{is}
11625 @b{when} discrete_choice_list => @{case_construction | attribute_declaration@}
11627 discrete_choice_list ::=
11628 literal_string @{| literal_string@}
11631 simple_name @{. simple_name@}
11634 identifier (same as Ada)
11639 @node Elaboration Order Handling in GNAT
11640 @chapter Elaboration Order Handling in GNAT
11641 @cindex Order of elaboration
11642 @cindex Elaboration control
11645 * Elaboration Code in Ada 95::
11646 * Checking the Elaboration Order in Ada 95::
11647 * Controlling the Elaboration Order in Ada 95::
11648 * Controlling Elaboration in GNAT - Internal Calls::
11649 * Controlling Elaboration in GNAT - External Calls::
11650 * Default Behavior in GNAT - Ensuring Safety::
11651 * Elaboration Issues for Library Tasks::
11652 * Mixing Elaboration Models::
11653 * What to Do If the Default Elaboration Behavior Fails::
11654 * Elaboration for Access-to-Subprogram Values::
11655 * Summary of Procedures for Elaboration Control::
11656 * Other Elaboration Order Considerations::
11660 This chapter describes the handling of elaboration code in Ada 95 and
11661 in GNAT, and discusses how the order of elaboration of program units can
11662 be controlled in GNAT, either automatically or with explicit programming
11665 @node Elaboration Code in Ada 95
11666 @section Elaboration Code in Ada 95
11669 Ada 95 provides rather general mechanisms for executing code at elaboration
11670 time, that is to say before the main program starts executing. Such code arises
11674 @item Initializers for variables.
11675 Variables declared at the library level, in package specs or bodies, can
11676 require initialization that is performed at elaboration time, as in:
11679 Sqrt_Half : Float := Sqrt (0.5);
11683 @item Package initialization code
11684 Code in a @code{BEGIN-END} section at the outer level of a package body is
11685 executed as part of the package body elaboration code.
11687 @item Library level task allocators
11688 Tasks that are declared using task allocators at the library level
11689 start executing immediately and hence can execute at elaboration time.
11693 Subprogram calls are possible in any of these contexts, which means that
11694 any arbitrary part of the program may be executed as part of the elaboration
11695 code. It is even possible to write a program which does all its work at
11696 elaboration time, with a null main program, although stylistically this
11697 would usually be considered an inappropriate way to structure
11700 An important concern arises in the context of elaboration code:
11701 we have to be sure that it is executed in an appropriate order. What we
11702 have is a series of elaboration code sections, potentially one section
11703 for each unit in the program. It is important that these execute
11704 in the correct order. Correctness here means that, taking the above
11705 example of the declaration of @code{Sqrt_Half},
11706 if some other piece of
11707 elaboration code references @code{Sqrt_Half},
11708 then it must run after the
11709 section of elaboration code that contains the declaration of
11712 There would never be any order of elaboration problem if we made a rule
11713 that whenever you @code{with} a unit, you must elaborate both the spec and body
11714 of that unit before elaborating the unit doing the @code{with}'ing:
11720 @b{package} Unit_2 @b{is} ...
11726 would require that both the body and spec of @code{Unit_1} be elaborated
11727 before the spec of @code{Unit_2}. However, a rule like that would be far too
11728 restrictive. In particular, it would make it impossible to have routines
11729 in separate packages that were mutually recursive.
11731 You might think that a clever enough compiler could look at the actual
11732 elaboration code and determine an appropriate correct order of elaboration,
11733 but in the general case, this is not possible. Consider the following
11736 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
11738 the variable @code{Sqrt_1}, which is declared in the elaboration code
11739 of the body of @code{Unit_1}:
11743 Sqrt_1 : Float := Sqrt (0.1);
11748 The elaboration code of the body of @code{Unit_1} also contains:
11753 @b{if} expression_1 = 1 @b{then}
11754 Q := Unit_2.Func_2;
11761 @code{Unit_2} is exactly parallel,
11762 it has a procedure @code{Func_2} that references
11763 the variable @code{Sqrt_2}, which is declared in the elaboration code of
11764 the body @code{Unit_2}:
11768 Sqrt_2 : Float := Sqrt (0.1);
11773 The elaboration code of the body of @code{Unit_2} also contains:
11778 @b{if} expression_2 = 2 @b{then}
11779 Q := Unit_1.Func_1;
11786 Now the question is, which of the following orders of elaboration is
11811 If you carefully analyze the flow here, you will see that you cannot tell
11812 at compile time the answer to this question.
11813 If @code{expression_1} is not equal to 1,
11814 and @code{expression_2} is not equal to 2,
11815 then either order is acceptable, because neither of the function calls is
11816 executed. If both tests evaluate to true, then neither order is acceptable
11817 and in fact there is no correct order.
11819 If one of the two expressions is true, and the other is false, then one
11820 of the above orders is correct, and the other is incorrect. For example,
11821 if @code{expression_1} = 1 and @code{expression_2} /= 2,
11822 then the call to @code{Func_2}
11823 will occur, but not the call to @code{Func_1.}
11824 This means that it is essential
11825 to elaborate the body of @code{Unit_1} before
11826 the body of @code{Unit_2}, so the first
11827 order of elaboration is correct and the second is wrong.
11829 By making @code{expression_1} and @code{expression_2}
11830 depend on input data, or perhaps
11831 the time of day, we can make it impossible for the compiler or binder
11832 to figure out which of these expressions will be true, and hence it
11833 is impossible to guarantee a safe order of elaboration at run time.
11835 @node Checking the Elaboration Order in Ada 95
11836 @section Checking the Elaboration Order in Ada 95
11839 In some languages that involve the same kind of elaboration problems,
11840 e.g. Java and C++, the programmer is expected to worry about these
11841 ordering problems himself, and it is common to
11842 write a program in which an incorrect elaboration order gives
11843 surprising results, because it references variables before they
11845 Ada 95 is designed to be a safe language, and a programmer-beware approach is
11846 clearly not sufficient. Consequently, the language provides three lines
11850 @item Standard rules
11851 Some standard rules restrict the possible choice of elaboration
11852 order. In particular, if you @code{with} a unit, then its spec is always
11853 elaborated before the unit doing the @code{with}. Similarly, a parent
11854 spec is always elaborated before the child spec, and finally
11855 a spec is always elaborated before its corresponding body.
11857 @item Dynamic elaboration checks
11858 @cindex Elaboration checks
11859 @cindex Checks, elaboration
11860 Dynamic checks are made at run time, so that if some entity is accessed
11861 before it is elaborated (typically by means of a subprogram call)
11862 then the exception (@code{Program_Error}) is raised.
11864 @item Elaboration control
11865 Facilities are provided for the programmer to specify the desired order
11869 Let's look at these facilities in more detail. First, the rules for
11870 dynamic checking. One possible rule would be simply to say that the
11871 exception is raised if you access a variable which has not yet been
11872 elaborated. The trouble with this approach is that it could require
11873 expensive checks on every variable reference. Instead Ada 95 has two
11874 rules which are a little more restrictive, but easier to check, and
11878 @item Restrictions on calls
11879 A subprogram can only be called at elaboration time if its body
11880 has been elaborated. The rules for elaboration given above guarantee
11881 that the spec of the subprogram has been elaborated before the
11882 call, but not the body. If this rule is violated, then the
11883 exception @code{Program_Error} is raised.
11885 @item Restrictions on instantiations
11886 A generic unit can only be instantiated if the body of the generic
11887 unit has been elaborated. Again, the rules for elaboration given above
11888 guarantee that the spec of the generic unit has been elaborated
11889 before the instantiation, but not the body. If this rule is
11890 violated, then the exception @code{Program_Error} is raised.
11894 The idea is that if the body has been elaborated, then any variables
11895 it references must have been elaborated; by checking for the body being
11896 elaborated we guarantee that none of its references causes any
11897 trouble. As we noted above, this is a little too restrictive, because a
11898 subprogram that has no non-local references in its body may in fact be safe
11899 to call. However, it really would be unsafe to rely on this, because
11900 it would mean that the caller was aware of details of the implementation
11901 in the body. This goes against the basic tenets of Ada.
11903 A plausible implementation can be described as follows.
11904 A Boolean variable is associated with each subprogram
11905 and each generic unit. This variable is initialized to False, and is set to
11906 True at the point body is elaborated. Every call or instantiation checks the
11907 variable, and raises @code{Program_Error} if the variable is False.
11909 Note that one might think that it would be good enough to have one Boolean
11910 variable for each package, but that would not deal with cases of trying
11911 to call a body in the same package as the call
11912 that has not been elaborated yet.
11913 Of course a compiler may be able to do enough analysis to optimize away
11914 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
11915 does such optimizations, but still the easiest conceptual model is to
11916 think of there being one variable per subprogram.
11918 @node Controlling the Elaboration Order in Ada 95
11919 @section Controlling the Elaboration Order in Ada 95
11922 In the previous section we discussed the rules in Ada 95 which ensure
11923 that @code{Program_Error} is raised if an incorrect elaboration order is
11924 chosen. This prevents erroneous executions, but we need mechanisms to
11925 specify a correct execution and avoid the exception altogether.
11926 To achieve this, Ada 95 provides a number of features for controlling
11927 the order of elaboration. We discuss these features in this section.
11929 First, there are several ways of indicating to the compiler that a given
11930 unit has no elaboration problems:
11933 @item packages that do not require a body
11934 In Ada 95, a library package that does not require a body does not permit
11935 a body. This means that if we have a such a package, as in:
11940 @b{package} Definitions @b{is}
11942 @b{type} m @b{is new} integer;
11943 @b{package} Subp @b{is}
11944 @b{type} a @b{is array} (1 .. 10) @b{of} m;
11945 @b{type} b @b{is array} (1 .. 20) @b{of} m;
11947 @b{end} Definitions;
11953 A package that @code{with}'s @code{Definitions} may safely instantiate
11954 @code{Definitions.Subp} because the compiler can determine that there
11955 definitely is no package body to worry about in this case
11958 @cindex pragma Pure
11960 Places sufficient restrictions on a unit to guarantee that
11961 no call to any subprogram in the unit can result in an
11962 elaboration problem. This means that the compiler does not need
11963 to worry about the point of elaboration of such units, and in
11964 particular, does not need to check any calls to any subprograms
11967 @item pragma Preelaborate
11968 @findex Preelaborate
11969 @cindex pragma Preelaborate
11970 This pragma places slightly less stringent restrictions on a unit than
11972 but these restrictions are still sufficient to ensure that there
11973 are no elaboration problems with any calls to the unit.
11975 @item pragma Elaborate_Body
11976 @findex Elaborate_Body
11977 @cindex pragma Elaborate_Body
11978 This pragma requires that the body of a unit be elaborated immediately
11979 after its spec. Suppose a unit @code{A} has such a pragma,
11980 and unit @code{B} does
11981 a @code{with} of unit @code{A}. Recall that the standard rules require
11982 the spec of unit @code{A}
11983 to be elaborated before the @code{with}'ing unit; given the pragma in
11984 @code{A}, we also know that the body of @code{A}
11985 will be elaborated before @code{B}, so
11986 that calls to @code{A} are safe and do not need a check.
11991 unlike pragma @code{Pure} and pragma @code{Preelaborate},
11993 @code{Elaborate_Body} does not guarantee that the program is
11994 free of elaboration problems, because it may not be possible
11995 to satisfy the requested elaboration order.
11996 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
11998 marks @code{Unit_1} as @code{Elaborate_Body},
11999 and not @code{Unit_2,} then the order of
12000 elaboration will be:
12012 Now that means that the call to @code{Func_1} in @code{Unit_2}
12013 need not be checked,
12014 it must be safe. But the call to @code{Func_2} in
12015 @code{Unit_1} may still fail if
12016 @code{Expression_1} is equal to 1,
12017 and the programmer must still take
12018 responsibility for this not being the case.
12020 If all units carry a pragma @code{Elaborate_Body}, then all problems are
12021 eliminated, except for calls entirely within a body, which are
12022 in any case fully under programmer control. However, using the pragma
12023 everywhere is not always possible.
12024 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
12025 we marked both of them as having pragma @code{Elaborate_Body}, then
12026 clearly there would be no possible elaboration order.
12028 The above pragmas allow a server to guarantee safe use by clients, and
12029 clearly this is the preferable approach. Consequently a good rule in
12030 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
12031 and if this is not possible,
12032 mark them as @code{Elaborate_Body} if possible.
12033 As we have seen, there are situations where neither of these
12034 three pragmas can be used.
12035 So we also provide methods for clients to control the
12036 order of elaboration of the servers on which they depend:
12039 @item pragma Elaborate (unit)
12041 @cindex pragma Elaborate
12042 This pragma is placed in the context clause, after a @code{with} clause,
12043 and it requires that the body of the named unit be elaborated before
12044 the unit in which the pragma occurs. The idea is to use this pragma
12045 if the current unit calls at elaboration time, directly or indirectly,
12046 some subprogram in the named unit.
12048 @item pragma Elaborate_All (unit)
12049 @findex Elaborate_All
12050 @cindex pragma Elaborate_All
12051 This is a stronger version of the Elaborate pragma. Consider the
12055 Unit A @code{with}'s unit B and calls B.Func in elab code
12056 Unit B @code{with}'s unit C, and B.Func calls C.Func
12060 Now if we put a pragma @code{Elaborate (B)}
12061 in unit @code{A}, this ensures that the
12062 body of @code{B} is elaborated before the call, but not the
12063 body of @code{C}, so
12064 the call to @code{C.Func} could still cause @code{Program_Error} to
12067 The effect of a pragma @code{Elaborate_All} is stronger, it requires
12068 not only that the body of the named unit be elaborated before the
12069 unit doing the @code{with}, but also the bodies of all units that the
12070 named unit uses, following @code{with} links transitively. For example,
12071 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
12073 not only that the body of @code{B} be elaborated before @code{A},
12075 body of @code{C}, because @code{B} @code{with}'s @code{C}.
12079 We are now in a position to give a usage rule in Ada 95 for avoiding
12080 elaboration problems, at least if dynamic dispatching and access to
12081 subprogram values are not used. We will handle these cases separately
12084 The rule is simple. If a unit has elaboration code that can directly or
12085 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
12086 a generic unit in a @code{with}'ed unit,
12087 then if the @code{with}'ed unit does not have
12088 pragma @code{Pure} or @code{Preelaborate}, then the client should have
12089 a pragma @code{Elaborate_All}
12090 for the @code{with}'ed unit. By following this rule a client is
12091 assured that calls can be made without risk of an exception.
12092 If this rule is not followed, then a program may be in one of four
12096 @item No order exists
12097 No order of elaboration exists which follows the rules, taking into
12098 account any @code{Elaborate}, @code{Elaborate_All},
12099 or @code{Elaborate_Body} pragmas. In
12100 this case, an Ada 95 compiler must diagnose the situation at bind
12101 time, and refuse to build an executable program.
12103 @item One or more orders exist, all incorrect
12104 One or more acceptable elaboration orders exists, and all of them
12105 generate an elaboration order problem. In this case, the binder
12106 can build an executable program, but @code{Program_Error} will be raised
12107 when the program is run.
12109 @item Several orders exist, some right, some incorrect
12110 One or more acceptable elaboration orders exists, and some of them
12111 work, and some do not. The programmer has not controlled
12112 the order of elaboration, so the binder may or may not pick one of
12113 the correct orders, and the program may or may not raise an
12114 exception when it is run. This is the worst case, because it means
12115 that the program may fail when moved to another compiler, or even
12116 another version of the same compiler.
12118 @item One or more orders exists, all correct
12119 One ore more acceptable elaboration orders exist, and all of them
12120 work. In this case the program runs successfully. This state of
12121 affairs can be guaranteed by following the rule we gave above, but
12122 may be true even if the rule is not followed.
12126 Note that one additional advantage of following our Elaborate_All rule
12127 is that the program continues to stay in the ideal (all orders OK) state
12128 even if maintenance
12129 changes some bodies of some subprograms. Conversely, if a program that does
12130 not follow this rule happens to be safe at some point, this state of affairs
12131 may deteriorate silently as a result of maintenance changes.
12133 You may have noticed that the above discussion did not mention
12134 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
12135 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
12136 code in the body makes calls to some other unit, so it is still necessary
12137 to use @code{Elaborate_All} on such units.
12139 @node Controlling Elaboration in GNAT - Internal Calls
12140 @section Controlling Elaboration in GNAT - Internal Calls
12143 In the case of internal calls, i.e. calls within a single package, the
12144 programmer has full control over the order of elaboration, and it is up
12145 to the programmer to elaborate declarations in an appropriate order. For
12151 @b{function} One @b{return} Float;
12155 @b{function} One @b{return} Float @b{is}
12164 will obviously raise @code{Program_Error} at run time, because function
12165 One will be called before its body is elaborated. In this case GNAT will
12166 generate a warning that the call will raise @code{Program_Error}:
12172 2. function One return Float;
12174 4. Q : Float := One;
12176 >>> warning: cannot call "One" before body is elaborated
12177 >>> warning: Program_Error will be raised at run time
12180 6. function One return Float is
12193 Note that in this particular case, it is likely that the call is safe, because
12194 the function @code{One} does not access any global variables.
12195 Nevertheless in Ada 95, we do not want the validity of the check to depend on
12196 the contents of the body (think about the separate compilation case), so this
12197 is still wrong, as we discussed in the previous sections.
12199 The error is easily corrected by rearranging the declarations so that the
12200 body of One appears before the declaration containing the call
12201 (note that in Ada 95,
12202 declarations can appear in any order, so there is no restriction that
12203 would prevent this reordering, and if we write:
12208 @b{function} One @b{return} Float;
12210 @b{function} One @b{return} Float @b{is}
12221 then all is well, no warning is generated, and no
12222 @code{Program_Error} exception
12224 Things are more complicated when a chain of subprograms is executed:
12229 @b{function} A @b{return} Integer;
12230 @b{function} B @b{return} Integer;
12231 @b{function} C @b{return} Integer;
12233 @b{function} B @b{return} Integer @b{is begin return} A; @b{end};
12234 @b{function} C @b{return} Integer @b{is begin return} B; @b{end};
12238 @b{function} A @b{return} Integer @b{is begin return} 1; @b{end};
12244 Now the call to @code{C}
12245 at elaboration time in the declaration of @code{X} is correct, because
12246 the body of @code{C} is already elaborated,
12247 and the call to @code{B} within the body of
12248 @code{C} is correct, but the call
12249 to @code{A} within the body of @code{B} is incorrect, because the body
12250 of @code{A} has not been elaborated, so @code{Program_Error}
12251 will be raised on the call to @code{A}.
12252 In this case GNAT will generate a
12253 warning that @code{Program_Error} may be
12254 raised at the point of the call. Let's look at the warning:
12260 2. function A return Integer;
12261 3. function B return Integer;
12262 4. function C return Integer;
12264 6. function B return Integer is begin return A; end;
12266 >>> warning: call to "A" before body is elaborated may
12267 raise Program_Error
12268 >>> warning: "B" called at line 7
12269 >>> warning: "C" called at line 9
12271 7. function C return Integer is begin return B; end;
12273 9. X : Integer := C;
12275 11. function A return Integer is begin return 1; end;
12285 Note that the message here says "may raise", instead of the direct case,
12286 where the message says "will be raised". That's because whether
12288 actually called depends in general on run-time flow of control.
12289 For example, if the body of @code{B} said
12294 @b{function} B @b{return} Integer @b{is}
12296 @b{if} some-condition-depending-on-input-data @b{then}
12307 then we could not know until run time whether the incorrect call to A would
12308 actually occur, so @code{Program_Error} might
12309 or might not be raised. It is possible for a compiler to
12310 do a better job of analyzing bodies, to
12311 determine whether or not @code{Program_Error}
12312 might be raised, but it certainly
12313 couldn't do a perfect job (that would require solving the halting problem
12314 and is provably impossible), and because this is a warning anyway, it does
12315 not seem worth the effort to do the analysis. Cases in which it
12316 would be relevant are rare.
12318 In practice, warnings of either of the forms given
12319 above will usually correspond to
12320 real errors, and should be examined carefully and eliminated.
12321 In the rare case where a warning is bogus, it can be suppressed by any of
12322 the following methods:
12326 Compile with the @option{-gnatws} switch set
12329 Suppress @code{Elaboration_Checks} for the called subprogram
12332 Use pragma @code{Warnings_Off} to turn warnings off for the call
12336 For the internal elaboration check case,
12337 GNAT by default generates the
12338 necessary run-time checks to ensure
12339 that @code{Program_Error} is raised if any
12340 call fails an elaboration check. Of course this can only happen if a
12341 warning has been issued as described above. The use of pragma
12342 @code{Suppress (Elaboration_Checks)} may (but is not guaranteed to) suppress
12343 some of these checks, meaning that it may be possible (but is not
12344 guaranteed) for a program to be able to call a subprogram whose body
12345 is not yet elaborated, without raising a @code{Program_Error} exception.
12347 @node Controlling Elaboration in GNAT - External Calls
12348 @section Controlling Elaboration in GNAT - External Calls
12351 The previous section discussed the case in which the execution of a
12352 particular thread of elaboration code occurred entirely within a
12353 single unit. This is the easy case to handle, because a programmer
12354 has direct and total control over the order of elaboration, and
12355 furthermore, checks need only be generated in cases which are rare
12356 and which the compiler can easily detect.
12357 The situation is more complex when separate compilation is taken into account.
12358 Consider the following:
12363 @b{package} Math @b{is}
12364 @b{function} Sqrt (Arg : Float) @b{return} Float;
12367 @b{package body} Math @b{is}
12368 @b{function} Sqrt (Arg : Float) @b{return} Float @b{is}
12376 @b{package} Stuff @b{is}
12377 X : Float := Math.Sqrt (0.5);
12381 @b{procedure} Main @b{is}
12390 where @code{Main} is the main program. When this program is executed, the
12391 elaboration code must first be executed, and one of the jobs of the
12392 binder is to determine the order in which the units of a program are
12393 to be elaborated. In this case we have four units: the spec and body
12395 the spec of @code{Stuff} and the body of @code{Main}).
12396 In what order should the four separate sections of elaboration code
12399 There are some restrictions in the order of elaboration that the binder
12400 can choose. In particular, if unit U has a @code{with}
12401 for a package @code{X}, then you
12402 are assured that the spec of @code{X}
12403 is elaborated before U , but you are
12404 not assured that the body of @code{X}
12405 is elaborated before U.
12406 This means that in the above case, the binder is allowed to choose the
12417 but that's not good, because now the call to @code{Math.Sqrt}
12418 that happens during
12419 the elaboration of the @code{Stuff}
12420 spec happens before the body of @code{Math.Sqrt} is
12421 elaborated, and hence causes @code{Program_Error} exception to be raised.
12422 At first glance, one might say that the binder is misbehaving, because
12423 obviously you want to elaborate the body of something you @code{with}
12425 that is not a general rule that can be followed in all cases. Consider
12430 @b{package} X @b{is} ...
12432 @b{package} Y @b{is} ...
12435 @b{package body} Y @b{is} ...
12438 @b{package body} X @b{is} ...
12444 This is a common arrangement, and, apart from the order of elaboration
12445 problems that might arise in connection with elaboration code, this works fine.
12446 A rule that says that you must first elaborate the body of anything you
12447 @code{with} cannot work in this case:
12448 the body of @code{X} @code{with}'s @code{Y},
12449 which means you would have to
12450 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
12452 you have to elaborate the body of @code{X} first, but ... and we have a
12453 loop that cannot be broken.
12455 It is true that the binder can in many cases guess an order of elaboration
12456 that is unlikely to cause a @code{Program_Error}
12457 exception to be raised, and it tries to do so (in the
12458 above example of @code{Math/Stuff/Spec}, the GNAT binder will
12460 elaborate the body of @code{Math} right after its spec, so all will be well).
12462 However, a program that blindly relies on the binder to be helpful can
12463 get into trouble, as we discussed in the previous sections, so
12465 provides a number of facilities for assisting the programmer in
12466 developing programs that are robust with respect to elaboration order.
12468 @node Default Behavior in GNAT - Ensuring Safety
12469 @section Default Behavior in GNAT - Ensuring Safety
12472 The default behavior in GNAT ensures elaboration safety. In its
12473 default mode GNAT implements the
12474 rule we previously described as the right approach. Let's restate it:
12478 @emph{If a unit has elaboration code that can directly or indirectly make a
12479 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
12480 in a @code{with}'ed unit, then if the @code{with}'ed unit
12481 does not have pragma @code{Pure} or
12482 @code{Preelaborate}, then the client should have an
12483 @code{Elaborate_All} for the @code{with}'ed unit.}
12487 By following this rule a client
12488 is assured that calls and instantiations can be made without risk of an exception.
12490 In this mode GNAT traces all calls that are potentially made from
12491 elaboration code, and puts in any missing implicit @code{Elaborate_All}
12493 The advantage of this approach is that no elaboration problems
12494 are possible if the binder can find an elaboration order that is
12495 consistent with these implicit @code{Elaborate_All} pragmas. The
12496 disadvantage of this approach is that no such order may exist.
12498 If the binder does not generate any diagnostics, then it means that it
12499 has found an elaboration order that is guaranteed to be safe. However,
12500 the binder may still be relying on implicitly generated
12501 @code{Elaborate_All} pragmas so portability to other compilers than
12502 GNAT is not guaranteed.
12504 If it is important to guarantee portability, then the compilations should
12507 (warn on elaboration problems) switch. This will cause warning messages
12508 to be generated indicating the missing @code{Elaborate_All} pragmas.
12509 Consider the following source program:
12515 @b{package} j @b{is}
12516 m : integer := k.r;
12523 where it is clear that there
12524 should be a pragma @code{Elaborate_All}
12525 for unit @code{k}. An implicit pragma will be generated, and it is
12526 likely that the binder will be able to honor it. However,
12527 it is safer to include the pragma explicitly in the source. If this
12528 unit is compiled with the
12530 switch, then the compiler outputs a warning:
12537 3. m : integer := k.r;
12539 >>> warning: call to "r" may raise Program_Error
12540 >>> warning: missing pragma Elaborate_All for "k"
12548 and these warnings can be used as a guide for supplying manually
12549 the missing pragmas.
12551 This default mode is more restrictive than the Ada Reference
12552 Manual, and it is possible to construct programs which will compile
12553 using the dynamic model described there, but will run into a
12554 circularity using the safer static model we have described.
12556 Of course any Ada compiler must be able to operate in a mode
12557 consistent with the requirements of the Ada Reference Manual,
12558 and in particular must have the capability of implementing the
12559 standard dynamic model of elaboration with run-time checks.
12561 In GNAT, this standard mode can be achieved either by the use of
12562 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
12563 command, or by the use of the configuration pragma:
12566 pragma Elaboration_Checks (RM);
12570 Either approach will cause the unit affected to be compiled using the
12571 standard dynamic run-time elaboration checks described in the Ada
12572 Reference Manual. The static model is generally preferable, since it
12573 is clearly safer to rely on compile and link time checks rather than
12574 run-time checks. However, in the case of legacy code, it may be
12575 difficult to meet the requirements of the static model. This
12576 issue is further discussed in
12577 @ref{What to Do If the Default Elaboration Behavior Fails}.
12579 Note that the static model provides a strict subset of the allowed
12580 behavior and programs of the Ada Reference Manual, so if you do
12581 adhere to the static model and no circularities exist,
12582 then you are assured that your program will
12583 work using the dynamic model.
12585 @node Elaboration Issues for Library Tasks
12586 @section Elaboration Issues for Library Tasks
12587 @cindex Library tasks, elaboration issues
12588 @cindex Elaboration of library tasks
12591 In this section we examine special elaboration issues that arise for
12592 programs that declare library level tasks.
12594 Generally the model of execution of an Ada program is that all units are
12595 elaborated, and then execution of the program starts. However, the
12596 declaration of library tasks definitely does not fit this model. The
12597 reason for this is that library tasks start as soon as they are declared
12598 (more precisely, as soon as the statement part of the enclosing package
12599 body is reached), that is to say before elaboration
12600 of the program is complete. This means that if such a task calls a
12601 subprogram, or an entry in another task, the callee may or may not be
12602 elaborated yet, and in the standard
12603 Reference Manual model of dynamic elaboration checks, you can even
12604 get timing dependent Program_Error exceptions, since there can be
12605 a race between the elaboration code and the task code.
12607 The static model of elaboration in GNAT seeks to avoid all such
12608 dynamic behavior, by being conservative, and the conservative
12609 approach in this particular case is to assume that all the code
12610 in a task body is potentially executed at elaboration time if
12611 a task is declared at the library level.
12613 This can definitely result in unexpected circularities. Consider
12614 the following example
12622 type My_Int is new Integer;
12624 function Ident (M : My_Int) return My_Int;
12628 package body Decls is
12629 task body Lib_Task is
12635 function Ident (M : My_Int) return My_Int is
12643 procedure Put_Val (Arg : Decls.My_Int);
12647 package body Utils is
12648 procedure Put_Val (Arg : Decls.My_Int) is
12650 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
12657 Decls.Lib_Task.Start;
12662 If the above example is compiled in the default static elaboration
12663 mode, then a circularity occurs. The circularity comes from the call
12664 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
12665 this call occurs in elaboration code, we need an implicit pragma
12666 @code{Elaborate_All} for @code{Utils}. This means that not only must
12667 the spec and body of @code{Utils} be elaborated before the body
12668 of @code{Decls}, but also the spec and body of any unit that is
12669 @code{with'ed} by the body of @code{Utils} must also be elaborated before
12670 the body of @code{Decls}. This is the transitive implication of
12671 pragma @code{Elaborate_All} and it makes sense, because in general
12672 the body of @code{Put_Val} might have a call to something in a
12673 @code{with'ed} unit.
12675 In this case, the body of Utils (actually its spec) @code{with's}
12676 @code{Decls}. Unfortunately this means that the body of @code{Decls}
12677 must be elaborated before itself, in case there is a call from the
12678 body of @code{Utils}.
12680 Here is the exact chain of events we are worrying about:
12684 In the body of @code{Decls} a call is made from within the body of a library
12685 task to a subprogram in the package @code{Utils}. Since this call may
12686 occur at elaboration time (given that the task is activated at elaboration
12687 time), we have to assume the worst, i.e. that the
12688 call does happen at elaboration time.
12691 This means that the body and spec of @code{Util} must be elaborated before
12692 the body of @code{Decls} so that this call does not cause an access before
12696 Within the body of @code{Util}, specifically within the body of
12697 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
12701 One such @code{with}'ed package is package @code{Decls}, so there
12702 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
12703 In fact there is such a call in this example, but we would have to
12704 assume that there was such a call even if it were not there, since
12705 we are not supposed to write the body of @code{Decls} knowing what
12706 is in the body of @code{Utils}; certainly in the case of the
12707 static elaboration model, the compiler does not know what is in
12708 other bodies and must assume the worst.
12711 This means that the spec and body of @code{Decls} must also be
12712 elaborated before we elaborate the unit containing the call, but
12713 that unit is @code{Decls}! This means that the body of @code{Decls}
12714 must be elaborated before itself, and that's a circularity.
12718 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
12719 the body of @code{Decls} you will get a true Ada Reference Manual
12720 circularity that makes the program illegal.
12722 In practice, we have found that problems with the static model of
12723 elaboration in existing code often arise from library tasks, so
12724 we must address this particular situation.
12726 Note that if we compile and run the program above, using the dynamic model of
12727 elaboration (that is to say use the @option{-gnatE} switch),
12728 then it compiles, binds,
12729 links, and runs, printing the expected result of 2. Therefore in some sense
12730 the circularity here is only apparent, and we need to capture
12731 the properties of this program that distinguish it from other library-level
12732 tasks that have real elaboration problems.
12734 We have four possible answers to this question:
12739 Use the dynamic model of elaboration.
12741 If we use the @option{-gnatE} switch, then as noted above, the program works.
12742 Why is this? If we examine the task body, it is apparent that the task cannot
12744 @code{accept} statement until after elaboration has been completed, because
12745 the corresponding entry call comes from the main program, not earlier.
12746 This is why the dynamic model works here. But that's really giving
12747 up on a precise analysis, and we prefer to take this approach only if we cannot
12749 problem in any other manner. So let us examine two ways to reorganize
12750 the program to avoid the potential elaboration problem.
12753 Split library tasks into separate packages.
12755 Write separate packages, so that library tasks are isolated from
12756 other declarations as much as possible. Let us look at a variation on
12767 package body Decls1 is
12768 task body Lib_Task is
12776 type My_Int is new Integer;
12777 function Ident (M : My_Int) return My_Int;
12781 package body Decls2 is
12782 function Ident (M : My_Int) return My_Int is
12790 procedure Put_Val (Arg : Decls2.My_Int);
12794 package body Utils is
12795 procedure Put_Val (Arg : Decls2.My_Int) is
12797 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
12804 Decls1.Lib_Task.Start;
12809 All we have done is to split @code{Decls} into two packages, one
12810 containing the library task, and one containing everything else. Now
12811 there is no cycle, and the program compiles, binds, links and executes
12812 using the default static model of elaboration.
12815 Declare separate task types.
12817 A significant part of the problem arises because of the use of the
12818 single task declaration form. This means that the elaboration of
12819 the task type, and the elaboration of the task itself (i.e. the
12820 creation of the task) happen at the same time. A good rule
12821 of style in Ada 95 is to always create explicit task types. By
12822 following the additional step of placing task objects in separate
12823 packages from the task type declaration, many elaboration problems
12824 are avoided. Here is another modified example of the example program:
12828 task type Lib_Task_Type is
12832 type My_Int is new Integer;
12834 function Ident (M : My_Int) return My_Int;
12838 package body Decls is
12839 task body Lib_Task_Type is
12845 function Ident (M : My_Int) return My_Int is
12853 procedure Put_Val (Arg : Decls.My_Int);
12857 package body Utils is
12858 procedure Put_Val (Arg : Decls.My_Int) is
12860 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
12866 Lib_Task : Decls.Lib_Task_Type;
12872 Declst.Lib_Task.Start;
12877 What we have done here is to replace the @code{task} declaration in
12878 package @code{Decls} with a @code{task type} declaration. Then we
12879 introduce a separate package @code{Declst} to contain the actual
12880 task object. This separates the elaboration issues for
12881 the @code{task type}
12882 declaration, which causes no trouble, from the elaboration issues
12883 of the task object, which is also unproblematic, since it is now independent
12884 of the elaboration of @code{Utils}.
12885 This separation of concerns also corresponds to
12886 a generally sound engineering principle of separating declarations
12887 from instances. This version of the program also compiles, binds, links,
12888 and executes, generating the expected output.
12891 Use No_Entry_Calls_In_Elaboration_Code restriction.
12892 @cindex No_Entry_Calls_In_Elaboration_Code
12894 The previous two approaches described how a program can be restructured
12895 to avoid the special problems caused by library task bodies. in practice,
12896 however, such restructuring may be difficult to apply to existing legacy code,
12897 so we must consider solutions that do not require massive rewriting.
12899 Let us consider more carefully why our original sample program works
12900 under the dynamic model of elaboration. The reason is that the code
12901 in the task body blocks immediately on the @code{accept}
12902 statement. Now of course there is nothing to prohibit elaboration
12903 code from making entry calls (for example from another library level task),
12904 so we cannot tell in isolation that
12905 the task will not execute the accept statement during elaboration.
12907 However, in practice it is very unusual to see elaboration code
12908 make any entry calls, and the pattern of tasks starting
12909 at elaboration time and then immediately blocking on @code{accept} or
12910 @code{select} statements is very common. What this means is that
12911 the compiler is being too pessimistic when it analyzes the
12912 whole package body as though it might be executed at elaboration
12915 If we know that the elaboration code contains no entry calls, (a very safe
12916 assumption most of the time, that could almost be made the default
12917 behavior), then we can compile all units of the program under control
12918 of the following configuration pragma:
12921 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
12925 This pragma can be placed in the @file{gnat.adc} file in the usual
12926 manner. If we take our original unmodified program and compile it
12927 in the presence of a @file{gnat.adc} containing the above pragma,
12928 then once again, we can compile, bind, link, and execute, obtaining
12929 the expected result. In the presence of this pragma, the compiler does
12930 not trace calls in a task body, that appear after the first @code{accept}
12931 or @code{select} statement, and therefore does not report a potential
12932 circularity in the original program.
12934 The compiler will check to the extent it can that the above
12935 restriction is not violated, but it is not always possible to do a
12936 complete check at compile time, so it is important to use this
12937 pragma only if the stated restriction is in fact met, that is to say
12938 no task receives an entry call before elaboration of all units is completed.
12942 @node Mixing Elaboration Models
12943 @section Mixing Elaboration Models
12945 So far, we have assumed that the entire program is either compiled
12946 using the dynamic model or static model, ensuring consistency. It
12947 is possible to mix the two models, but rules have to be followed
12948 if this mixing is done to ensure that elaboration checks are not
12951 The basic rule is that @emph{a unit compiled with the static model cannot
12952 be @code{with'ed} by a unit compiled with the dynamic model}. The
12953 reason for this is that in the static model, a unit assumes that
12954 its clients guarantee to use (the equivalent of) pragma
12955 @code{Elaborate_All} so that no elaboration checks are required
12956 in inner subprograms, and this assumption is violated if the
12957 client is compiled with dynamic checks.
12959 The precise rule is as follows. A unit that is compiled with dynamic
12960 checks can only @code{with} a unit that meets at least one of the
12961 following criteria:
12966 The @code{with'ed} unit is itself compiled with dynamic elaboration
12967 checks (that is with the @option{-gnatE} switch.
12970 The @code{with'ed} unit is an internal GNAT implementation unit from
12971 the System, Interfaces, Ada, or GNAT hierarchies.
12974 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
12977 The @code{with'ing} unit (that is the client) has an explicit pragma
12978 @code{Elaborate_All} for the @code{with'ed} unit.
12983 If this rule is violated, that is if a unit with dynamic elaboration
12984 checks @code{with's} a unit that does not meet one of the above four
12985 criteria, then the binder (@code{gnatbind}) will issue a warning
12986 similar to that in the following example:
12989 warning: "x.ads" has dynamic elaboration checks and with's
12990 warning: "y.ads" which has static elaboration checks
12994 These warnings indicate that the rule has been violated, and that as a result
12995 elaboration checks may be missed in the resulting executable file.
12996 This warning may be suppressed using the @code{-ws} binder switch
12997 in the usual manner.
12999 One useful application of this mixing rule is in the case of a subsystem
13000 which does not itself @code{with} units from the remainder of the
13001 application. In this case, the entire subsystem can be compiled with
13002 dynamic checks to resolve a circularity in the subsystem, while
13003 allowing the main application that uses this subsystem to be compiled
13004 using the more reliable default static model.
13006 @node What to Do If the Default Elaboration Behavior Fails
13007 @section What to Do If the Default Elaboration Behavior Fails
13010 If the binder cannot find an acceptable order, it outputs detailed
13011 diagnostics. For example:
13017 error: elaboration circularity detected
13018 info: "proc (body)" must be elaborated before "pack (body)"
13019 info: reason: Elaborate_All probably needed in unit "pack (body)"
13020 info: recompile "pack (body)" with -gnatwl
13021 info: for full details
13022 info: "proc (body)"
13023 info: is needed by its spec:
13024 info: "proc (spec)"
13025 info: which is withed by:
13026 info: "pack (body)"
13027 info: "pack (body)" must be elaborated before "proc (body)"
13028 info: reason: pragma Elaborate in unit "proc (body)"
13034 In this case we have a cycle that the binder cannot break. On the one
13035 hand, there is an explicit pragma Elaborate in @code{proc} for
13036 @code{pack}. This means that the body of @code{pack} must be elaborated
13037 before the body of @code{proc}. On the other hand, there is elaboration
13038 code in @code{pack} that calls a subprogram in @code{proc}. This means
13039 that for maximum safety, there should really be a pragma
13040 Elaborate_All in @code{pack} for @code{proc} which would require that
13041 the body of @code{proc} be elaborated before the body of
13042 @code{pack}. Clearly both requirements cannot be satisfied.
13043 Faced with a circularity of this kind, you have three different options.
13046 @item Fix the program
13047 The most desirable option from the point of view of long-term maintenance
13048 is to rearrange the program so that the elaboration problems are avoided.
13049 One useful technique is to place the elaboration code into separate
13050 child packages. Another is to move some of the initialization code to
13051 explicitly called subprograms, where the program controls the order
13052 of initialization explicitly. Although this is the most desirable option,
13053 it may be impractical and involve too much modification, especially in
13054 the case of complex legacy code.
13056 @item Perform dynamic checks
13057 If the compilations are done using the
13059 (dynamic elaboration check) switch, then GNAT behaves in
13060 a quite different manner. Dynamic checks are generated for all calls
13061 that could possibly result in raising an exception. With this switch,
13062 the compiler does not generate implicit @code{Elaborate_All} pragmas.
13063 The behavior then is exactly as specified in the Ada 95 Reference Manual.
13064 The binder will generate an executable program that may or may not
13065 raise @code{Program_Error}, and then it is the programmer's job to ensure
13066 that it does not raise an exception. Note that it is important to
13067 compile all units with the switch, it cannot be used selectively.
13069 @item Suppress checks
13070 The drawback of dynamic checks is that they generate a
13071 significant overhead at run time, both in space and time. If you
13072 are absolutely sure that your program cannot raise any elaboration
13073 exceptions, and you still want to use the dynamic elaboration model,
13074 then you can use the configuration pragma
13075 @code{Suppress (Elaboration_Checks)} to suppress all such checks. For
13076 example this pragma could be placed in the @file{gnat.adc} file.
13078 @item Suppress checks selectively
13079 When you know that certain calls in elaboration code cannot possibly
13080 lead to an elaboration error, and the binder nevertheless generates warnings
13081 on those calls and inserts Elaborate_All pragmas that lead to elaboration
13082 circularities, it is possible to remove those warnings locally and obtain
13083 a program that will bind. Clearly this can be unsafe, and it is the
13084 responsibility of the programmer to make sure that the resulting program has
13085 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
13086 be used with different granularity to suppress warnings and break
13087 elaboration circularities:
13091 Place the pragma that names the called subprogram in the declarative part
13092 that contains the call.
13095 Place the pragma in the declarative part, without naming an entity. This
13096 disables warnings on all calls in the corresponding declarative region.
13099 Place the pragma in the package spec that declares the called subprogram,
13100 and name the subprogram. This disables warnings on all elaboration calls to
13104 Place the pragma in the package spec that declares the called subprogram,
13105 without naming any entity. This disables warnings on all elaboration calls to
13106 all subprograms declared in this spec.
13110 These four cases are listed in order of decreasing safety, and therefore
13111 require increasing programmer care in their application. Consider the
13116 function F1 return Integer;
13121 function F2 return Integer;
13122 function Pure (x : integer) return integer;
13123 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
13124 -- pragma Suppress (Elaboration_Check); -- (4)
13128 package body Pack1 is
13129 function F1 return Integer is
13133 Val : integer := Pack2.Pure (11); -- Elab. call (1)
13136 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
13137 -- pragma Suppress(Elaboration_Check); -- (2)
13139 X1 := Pack2.F2 + 1; -- Elab. call (2)
13144 package body Pack2 is
13145 function F2 return Integer is
13149 function Pure (x : integer) return integer is
13151 return x ** 3 - 3 * x;
13155 with Pack1, Ada.Text_IO;
13158 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
13161 In the absence of any pragmas, an attempt to bind this program produces
13162 the following diagnostics:
13168 error: elaboration circularity detected
13169 info: "pack1 (body)" must be elaborated before "pack1 (body)"
13170 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
13171 info: recompile "pack1 (body)" with -gnatwl for full details
13172 info: "pack1 (body)"
13173 info: must be elaborated along with its spec:
13174 info: "pack1 (spec)"
13175 info: which is withed by:
13176 info: "pack2 (body)"
13177 info: which must be elaborated along with its spec:
13178 info: "pack2 (spec)"
13179 info: which is withed by:
13180 info: "pack1 (body)"
13183 The sources of the circularity are the two calls to @code{Pack2.Pure} and
13184 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
13185 F2 is safe, even though F2 calls F1, because the call appears after the
13186 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
13187 remove the warning on the call. It is also possible to use pragma (2)
13188 because there are no other potentially unsafe calls in the block.
13191 The call to @code{Pure} is safe because this function does not depend on the
13192 state of @code{Pack2}. Therefore any call to this function is safe, and it
13193 is correct to place pragma (3) in the corresponding package spec.
13196 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
13197 warnings on all calls to functions declared therein. Note that this is not
13198 necessarily safe, and requires more detailed examination of the subprogram
13199 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
13200 be already elaborated.
13204 It is hard to generalize on which of these four approaches should be
13205 taken. Obviously if it is possible to fix the program so that the default
13206 treatment works, this is preferable, but this may not always be practical.
13207 It is certainly simple enough to use
13209 but the danger in this case is that, even if the GNAT binder
13210 finds a correct elaboration order, it may not always do so,
13211 and certainly a binder from another Ada compiler might not. A
13212 combination of testing and analysis (for which the warnings generated
13215 switch can be useful) must be used to ensure that the program is free
13216 of errors. One switch that is useful in this testing is the
13217 @code{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
13220 Normally the binder tries to find an order that has the best chance of
13221 of avoiding elaboration problems. With this switch, the binder
13222 plays a devil's advocate role, and tries to choose the order that
13223 has the best chance of failing. If your program works even with this
13224 switch, then it has a better chance of being error free, but this is still
13227 For an example of this approach in action, consider the C-tests (executable
13228 tests) from the ACVC suite. If these are compiled and run with the default
13229 treatment, then all but one of them succeed without generating any error
13230 diagnostics from the binder. However, there is one test that fails, and
13231 this is not surprising, because the whole point of this test is to ensure
13232 that the compiler can handle cases where it is impossible to determine
13233 a correct order statically, and it checks that an exception is indeed
13234 raised at run time.
13236 This one test must be compiled and run using the
13238 switch, and then it passes. Alternatively, the entire suite can
13239 be run using this switch. It is never wrong to run with the dynamic
13240 elaboration switch if your code is correct, and we assume that the
13241 C-tests are indeed correct (it is less efficient, but efficiency is
13242 not a factor in running the ACVC tests.)
13244 @node Elaboration for Access-to-Subprogram Values
13245 @section Elaboration for Access-to-Subprogram Values
13246 @cindex Access-to-subprogram
13249 The introduction of access-to-subprogram types in Ada 95 complicates
13250 the handling of elaboration. The trouble is that it becomes
13251 impossible to tell at compile time which procedure
13252 is being called. This means that it is not possible for the binder
13253 to analyze the elaboration requirements in this case.
13255 If at the point at which the access value is created
13256 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
13257 the body of the subprogram is
13258 known to have been elaborated, then the access value is safe, and its use
13259 does not require a check. This may be achieved by appropriate arrangement
13260 of the order of declarations if the subprogram is in the current unit,
13261 or, if the subprogram is in another unit, by using pragma
13262 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
13263 on the referenced unit.
13265 If the referenced body is not known to have been elaborated at the point
13266 the access value is created, then any use of the access value must do a
13267 dynamic check, and this dynamic check will fail and raise a
13268 @code{Program_Error} exception if the body has not been elaborated yet.
13269 GNAT will generate the necessary checks, and in addition, if the
13271 switch is set, will generate warnings that such checks are required.
13273 The use of dynamic dispatching for tagged types similarly generates
13274 a requirement for dynamic checks, and premature calls to any primitive
13275 operation of a tagged type before the body of the operation has been elaborated,
13276 will result in the raising of @code{Program_Error}.
13278 @node Summary of Procedures for Elaboration Control
13279 @section Summary of Procedures for Elaboration Control
13280 @cindex Elaboration control
13283 First, compile your program with the default options, using none of
13284 the special elaboration control switches. If the binder successfully
13285 binds your program, then you can be confident that, apart from issues
13286 raised by the use of access-to-subprogram types and dynamic dispatching,
13287 the program is free of elaboration errors. If it is important that the
13288 program be portable, then use the
13290 switch to generate warnings about missing @code{Elaborate_All}
13291 pragmas, and supply the missing pragmas.
13293 If the program fails to bind using the default static elaboration
13294 handling, then you can fix the program to eliminate the binder
13295 message, or recompile the entire program with the
13296 @option{-gnatE} switch to generate dynamic elaboration checks,
13297 and, if you are sure there really are no elaboration problems,
13298 use a global pragma @code{Suppress (Elaboration_Checks)}.
13300 @node Other Elaboration Order Considerations
13301 @section Other Elaboration Order Considerations
13303 This section has been entirely concerned with the issue of finding a valid
13304 elaboration order, as defined by the Ada Reference Manual. In a case
13305 where several elaboration orders are valid, the task is to find one
13306 of the possible valid elaboration orders (and the static model in GNAT
13307 will ensure that this is achieved).
13309 The purpose of the elaboration rules in the Ada Reference Manual is to
13310 make sure that no entity is accessed before it has been elaborated. For
13311 a subprogram, this means that the spec and body must have been elaborated
13312 before the subprogram is called. For an object, this means that the object
13313 must have been elaborated before its value is read or written. A violation
13314 of either of these two requirements is an access before elaboration order,
13315 and this section has been all about avoiding such errors.
13317 In the case where more than one order of elaboration is possible, in the
13318 sense that access before elaboration errors are avoided, then any one of
13319 the orders is "correct" in the sense that it meets the requirements of
13320 the Ada Reference Manual, and no such error occurs.
13322 However, it may be the case for a given program, that there are
13323 constraints on the order of elaboration that come not from consideration
13324 of avoiding elaboration errors, but rather from extra-lingual logic
13325 requirements. Consider this example:
13328 with Init_Constants;
13329 package Constants is
13334 package Init_Constants is
13336 end Init_Constants;
13339 package body Init_Constants is
13340 procedure Calc is begin null; end;
13344 end Init_Constants;
13348 Z : Integer := Constants.X + Constants.Y;
13352 with Text_IO; use Text_IO;
13355 Put_Line (Calc.Z'Img);
13360 In this example, there is more than one valid order of elaboration. For
13361 example both the following are correct orders:
13364 Init_Constants spec
13368 Init_Constants body
13372 Init_Constants spec
13373 Init_Constants body
13380 There is no language rule to prefer one or the other, both are correct
13381 from an order of elaboration point of view. But the programmatic effects
13382 of the two orders are very different. In the first, the elaboration routine
13383 of @code{Calc} initializes @code{Z} to zero, and then the main program
13384 runs with this value of zero. But in the second order, the elaboration
13385 routine of @code{Calc} runs after the body of Init_Constants has set
13386 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
13389 One could perhaps by applying pretty clever non-artificial intelligence
13390 to the situation guess that it is more likely that the second order of
13391 elaboration is the one desired, but there is no formal linguistic reason
13392 to prefer one over the other. In fact in this particular case, GNAT will
13393 prefer the second order, because of the rule that bodies are elaborated
13394 as soon as possible, but it's just luck that this is what was wanted
13395 (if indeed the second order was preferred).
13397 If the program cares about the order of elaboration routines in a case like
13398 this, it is important to specify the order required. In this particular
13399 case, that could have been achieved by adding to the spec of Calc:
13402 pragma Elaborate_All (Constants);
13406 which requires that the body (if any) and spec of @code{Constants},
13407 as well as the body and spec of any unit @code{with}'ed by
13408 @code{Constants} be elaborated before @code{Calc} is elaborated.
13410 Clearly no automatic method can always guess which alternative you require,
13411 and if you are working with legacy code that had constraints of this kind
13412 which were not properly specified by adding @code{Elaborate} or
13413 @code{Elaborate_All} pragmas, then indeed it is possible that two different
13414 compilers can choose different orders.
13416 The @code{gnatbind}
13417 @code{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
13418 out problems. This switch causes bodies to be elaborated as late as possible
13419 instead of as early as possible. In the example above, it would have forced
13420 the choice of the first elaboration order. If you get different results
13421 when using this switch, and particularly if one set of results is right,
13422 and one is wrong as far as you are concerned, it shows that you have some
13423 missing @code{Elaborate} pragmas. For the example above, we have the
13427 gnatmake -f -q main
13430 gnatmake -f -q main -bargs -p
13436 It is of course quite unlikely that both these results are correct, so
13437 it is up to you in a case like this to investigate the source of the
13438 difference, by looking at the two elaboration orders that are chosen,
13439 and figuring out which is correct, and then adding the necessary
13440 @code{Elaborate_All} pragmas to ensure the desired order.
13442 @node The Cross-Referencing Tools gnatxref and gnatfind
13443 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13448 The compiler generates cross-referencing information (unless
13449 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13450 This information indicates where in the source each entity is declared and
13451 referenced. Note that entities in package Standard are not included, but
13452 entities in all other predefined units are included in the output.
13454 Before using any of these two tools, you need to compile successfully your
13455 application, so that GNAT gets a chance to generate the cross-referencing
13458 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13459 information to provide the user with the capability to easily locate the
13460 declaration and references to an entity. These tools are quite similar,
13461 the difference being that @code{gnatfind} is intended for locating
13462 definitions and/or references to a specified entity or entities, whereas
13463 @code{gnatxref} is oriented to generating a full report of all
13466 To use these tools, you must not compile your application using the
13467 @option{-gnatx} switch on the @file{gnatmake} command line (@inforef{The
13468 GNAT Make Program gnatmake,,gnat_ug}). Otherwise, cross-referencing
13469 information will not be generated.
13472 * gnatxref Switches::
13473 * gnatfind Switches::
13474 * Project Files for gnatxref and gnatfind::
13475 * Regular Expressions in gnatfind and gnatxref::
13476 * Examples of gnatxref Usage::
13477 * Examples of gnatfind Usage::
13480 @node gnatxref Switches
13481 @section @code{gnatxref} Switches
13484 The command lines for @code{gnatxref} is:
13486 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13493 @item sourcefile1, sourcefile2
13494 identifies the source files for which a report is to be generated. The
13495 'with'ed units will be processed too. You must provide at least one file.
13497 These file names are considered to be regular expressions, so for instance
13498 specifying 'source*.adb' is the same as giving every file in the current
13499 directory whose name starts with 'source' and whose extension is 'adb'.
13504 The switches can be :
13506 @item ^-a^/ALL_FILES^
13507 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13508 the read-only files found in the library search path. Otherwise, these files
13509 will be ignored. This option can be used to protect Gnat sources or your own
13510 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13511 much faster, and their output much smaller.
13514 When looking for source files also look in directory DIR. The order in which
13515 source file search is undertaken is the same as for @file{gnatmake}.
13518 When searching for library and object files, look in directory
13519 DIR. The order in which library files are searched is the same as for
13523 Do not look for sources in the system default directory.
13526 Do not look for library files in the system default directory.
13528 @item --RTS=@var{rts-path}
13529 @cindex @code{--RTS} (@code{gnatxref})
13530 Specifies the default location of the runtime library. Same meaning as the
13531 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13534 If this switch is set @code{gnatxref} will output the parent type
13535 reference for each matching derived types.
13537 @item ^-f^/FULL_PATHNAME^
13538 If this switch is set, the output file names will be preceded by their
13539 directory (if the file was found in the search path). If this switch is
13540 not set, the directory will not be printed.
13542 @item ^-g^/IGNORE_LOCALS^
13543 If this switch is set, information is output only for library-level
13544 entities, ignoring local entities. The use of this switch may accelerate
13545 @code{gnatfind} and @code{gnatxref}.
13548 Equivalent to @samp{-aODIR -aIDIR}.
13551 Specify a project file to use @xref{Project Files}.
13552 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13553 project file in the current directory.
13555 If a project file is either specified or found by the tools, then the content
13556 of the source directory and object directory lines are added as if they
13557 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13558 and @samp{^-aO^OBJECT_SEARCH^}.
13560 Output only unused symbols. This may be really useful if you give your
13561 main compilation unit on the command line, as @code{gnatxref} will then
13562 display every unused entity and 'with'ed package.
13566 Instead of producing the default output, @code{gnatxref} will generate a
13567 @file{tags} file that can be used by vi. For examples how to use this
13568 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
13569 to the standard output, thus you will have to redirect it to a file.
13574 All these switches may be in any order on the command line, and may even
13575 appear after the file names. They need not be separated by spaces, thus
13576 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13577 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13579 @node gnatfind Switches
13580 @section @code{gnatfind} Switches
13583 The command line for @code{gnatfind} is:
13586 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
13595 An entity will be output only if it matches the regular expression found
13596 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
13598 Omitting the pattern is equivalent to specifying @samp{*}, which
13599 will match any entity. Note that if you do not provide a pattern, you
13600 have to provide both a sourcefile and a line.
13602 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13603 for matching purposes. At the current time there is no support for
13604 8-bit codes other than Latin-1, or for wide characters in identifiers.
13607 @code{gnatfind} will look for references, bodies or declarations
13608 of symbols referenced in @file{sourcefile}, at line @samp{line}
13609 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
13610 for syntax examples.
13613 is a decimal integer identifying the line number containing
13614 the reference to the entity (or entities) to be located.
13617 is a decimal integer identifying the exact location on the
13618 line of the first character of the identifier for the
13619 entity reference. Columns are numbered from 1.
13621 @item file1 file2 ...
13622 The search will be restricted to these files. If none are given, then
13623 the search will be done for every library file in the search path.
13624 These file must appear only after the pattern or sourcefile.
13626 These file names are considered to be regular expressions, so for instance
13627 specifying 'source*.adb' is the same as giving every file in the current
13628 directory whose name starts with 'source' and whose extension is 'adb'.
13630 Not that if you specify at least one file in this part, @code{gnatfind} may
13631 sometimes not be able to find the body of the subprograms...
13635 At least one of 'sourcefile' or 'pattern' has to be present on
13638 The following switches are available:
13641 @item ^-a^/ALL_FILES^
13642 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13643 the read-only files found in the library search path. Otherwise, these files
13644 will be ignored. This option can be used to protect Gnat sources or your own
13645 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13646 much faster, and their output much smaller.
13649 When looking for source files also look in directory DIR. The order in which
13650 source file search is undertaken is the same as for @file{gnatmake}.
13653 When searching for library and object files, look in directory
13654 DIR. The order in which library files are searched is the same as for
13658 Do not look for sources in the system default directory.
13661 Do not look for library files in the system default directory.
13663 @item --RTS=@var{rts-path}
13664 @cindex @code{--RTS} (@code{gnatfind})
13665 Specifies the default location of the runtime library. Same meaning as the
13666 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13669 If this switch is set, then @code{gnatfind} will output the parent type
13670 reference for each matching derived types.
13672 @item ^-e^/EXPRESSIONS^
13673 By default, @code{gnatfind} accept the simple regular expression set for
13674 @samp{pattern}. If this switch is set, then the pattern will be
13675 considered as full Unix-style regular expression.
13677 @item ^-f^/FULL_PATHNAME^
13678 If this switch is set, the output file names will be preceded by their
13679 directory (if the file was found in the search path). If this switch is
13680 not set, the directory will not be printed.
13682 @item ^-g^/IGNORE_LOCALS^
13683 If this switch is set, information is output only for library-level
13684 entities, ignoring local entities. The use of this switch may accelerate
13685 @code{gnatfind} and @code{gnatxref}.
13688 Equivalent to @samp{-aODIR -aIDIR}.
13691 Specify a project file (@pxref{Project Files}) to use.
13692 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13693 project file in the current directory.
13695 If a project file is either specified or found by the tools, then the content
13696 of the source directory and object directory lines are added as if they
13697 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13698 @samp{^-aO^/OBJECT_SEARCH^}.
13700 @item ^-r^/REFERENCES^
13701 By default, @code{gnatfind} will output only the information about the
13702 declaration, body or type completion of the entities. If this switch is
13703 set, the @code{gnatfind} will locate every reference to the entities in
13704 the files specified on the command line (or in every file in the search
13705 path if no file is given on the command line).
13707 @item ^-s^/PRINT_LINES^
13708 If this switch is set, then @code{gnatfind} will output the content
13709 of the Ada source file lines were the entity was found.
13712 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13713 the specified type. It act like -d option but recursively from parent
13714 type to parent type. When this switch is set it is not possible to
13715 specify more than one file.
13719 All these switches may be in any order on the command line, and may even
13720 appear after the file names. They need not be separated by spaces, thus
13721 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13722 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13724 As stated previously, gnatfind will search in every directory in the
13725 search path. You can force it to look only in the current directory if
13726 you specify @code{*} at the end of the command line.
13729 @node Project Files for gnatxref and gnatfind
13730 @section Project Files for @command{gnatxref} and @command{gnatfind}
13733 Project files allow a programmer to specify how to compile its
13734 application, where to find sources,... These files are used primarily by
13735 the Glide Ada mode, but they can also be used by the two tools
13736 @code{gnatxref} and @code{gnatfind}.
13738 A project file name must end with @file{.adp}. If a single one is
13739 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13740 extract the information from it. If multiple project files are found, none of
13741 them is read, and you have to use the @samp{-p} switch to specify the one
13744 The following lines can be included, even though most of them have default
13745 values which can be used in most cases.
13746 The lines can be entered in any order in the file.
13747 Except for @samp{src_dir} and @samp{obj_dir}, you can only have one instance of
13748 each line. If you have multiple instances, only the last one is taken into
13752 @item src_dir=DIR [default: "^./^[]^"]
13753 specifies a directory where to look for source files. Multiple src_dir lines
13754 can be specified and they will be searched in the order they
13757 @item obj_dir=DIR [default: "^./^[]^"]
13758 specifies a directory where to look for object and library files. Multiple
13759 obj_dir lines can be specified and they will be searched in the order they
13762 @item comp_opt=SWITCHES [default: ""]
13763 creates a variable which can be referred to subsequently by using
13764 the @samp{$@{comp_opt@}} notation. This is intended to store the default
13765 switches given to @file{gnatmake} and @file{gcc}.
13767 @item bind_opt=SWITCHES [default: ""]
13768 creates a variable which can be referred to subsequently by using
13769 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13770 switches given to @file{gnatbind}.
13772 @item link_opt=SWITCHES [default: ""]
13773 creates a variable which can be referred to subsequently by using
13774 the @samp{$@{link_opt@}} notation. This is intended to store the default
13775 switches given to @file{gnatlink}.
13777 @item main=EXECUTABLE [default: ""]
13778 specifies the name of the executable for the application. This variable can
13779 be referred to in the following lines by using the @samp{$@{main@}} notation.
13782 @item comp_cmd=COMMAND [default: "GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"]
13785 @item comp_cmd=COMMAND [default: "gcc -c -I$@{src_dir@} -g -gnatq"]
13787 specifies the command used to compile a single file in the application.
13790 @item make_cmd=COMMAND [default: "GNAT MAKE $@{main@} /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@} /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@} /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"]
13793 @item make_cmd=COMMAND [default: "gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"]
13795 specifies the command used to recompile the whole application.
13797 @item run_cmd=COMMAND [default: "$@{main@}"]
13798 specifies the command used to run the application.
13800 @item debug_cmd=COMMAND [default: "gdb $@{main@}"]
13801 specifies the command used to debug the application
13805 @code{gnatxref} and @code{gnatfind} only take into account the @samp{src_dir}
13806 and @samp{obj_dir} lines, and ignore the others.
13808 @node Regular Expressions in gnatfind and gnatxref
13809 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
13812 As specified in the section about @code{gnatfind}, the pattern can be a
13813 regular expression. Actually, there are to set of regular expressions
13814 which are recognized by the program :
13817 @item globbing patterns
13818 These are the most usual regular expression. They are the same that you
13819 generally used in a Unix shell command line, or in a DOS session.
13821 Here is a more formal grammar :
13828 term ::= elmt -- matches elmt
13829 term ::= elmt elmt -- concatenation (elmt then elmt)
13830 term ::= * -- any string of 0 or more characters
13831 term ::= ? -- matches any character
13832 term ::= [char @{char@}] -- matches any character listed
13833 term ::= [char - char] -- matches any character in range
13837 @item full regular expression
13838 The second set of regular expressions is much more powerful. This is the
13839 type of regular expressions recognized by utilities such a @file{grep}.
13841 The following is the form of a regular expression, expressed in Ada
13842 reference manual style BNF is as follows
13849 regexp ::= term @{| term@} -- alternation (term or term ...)
13851 term ::= item @{item@} -- concatenation (item then item)
13853 item ::= elmt -- match elmt
13854 item ::= elmt * -- zero or more elmt's
13855 item ::= elmt + -- one or more elmt's
13856 item ::= elmt ? -- matches elmt or nothing
13859 elmt ::= nschar -- matches given character
13860 elmt ::= [nschar @{nschar@}] -- matches any character listed
13861 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
13862 elmt ::= [char - char] -- matches chars in given range
13863 elmt ::= \ char -- matches given character
13864 elmt ::= . -- matches any single character
13865 elmt ::= ( regexp ) -- parens used for grouping
13867 char ::= any character, including special characters
13868 nschar ::= any character except ()[].*+?^^^
13872 Following are a few examples :
13876 will match any of the two strings 'abcde' and 'fghi'.
13879 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
13882 will match any string which has only lowercase characters in it (and at
13883 least one character
13888 @node Examples of gnatxref Usage
13889 @section Examples of @code{gnatxref} Usage
13891 @subsection General Usage
13894 For the following examples, we will consider the following units :
13901 2: @b{package} Main @b{is}
13902 3: @b{procedure} Foo (B : @b{in} Integer);
13909 1: @b{package body} Main @b{is}
13910 2: @b{procedure} Foo (B : @b{in} Integer) @b{is}
13920 1: @b{package} Bar @b{is}
13921 2: @b{procedure} Print (B : Integer);
13930 The first thing to do is to recompile your application (for instance, in
13931 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13932 the cross-referencing information.
13933 You can then issue any of the following commands:
13935 @item gnatxref main.adb
13936 @code{gnatxref} generates cross-reference information for main.adb
13937 and every unit 'with'ed by main.adb.
13939 The output would be:
13947 Decl: main.ads 3:20
13948 Body: main.adb 2:20
13949 Ref: main.adb 4:13 5:13 6:19
13952 Ref: main.adb 6:8 7:8
13962 Decl: main.ads 3:15
13963 Body: main.adb 2:15
13966 Body: main.adb 1:14
13969 Ref: main.adb 6:12 7:12
13973 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13974 its body is in main.adb, line 1, column 14 and is not referenced any where.
13976 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13977 it referenced in main.adb, line 6 column 12 and line 7 column 12.
13979 @item gnatxref package1.adb package2.ads
13980 @code{gnatxref} will generates cross-reference information for
13981 package1.adb, package2.ads and any other package 'with'ed by any
13987 @subsection Using gnatxref with vi
13989 @code{gnatxref} can generate a tags file output, which can be used
13990 directly from @file{vi}. Note that the standard version of @file{vi}
13991 will not work properly with overloaded symbols. Consider using another
13992 free implementation of @file{vi}, such as @file{vim}.
13995 $ gnatxref -v gnatfind.adb > tags
13999 will generate the tags file for @code{gnatfind} itself (if the sources
14000 are in the search path!).
14002 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14003 (replacing @i{entity} by whatever you are looking for), and vi will
14004 display a new file with the corresponding declaration of entity.
14007 @node Examples of gnatfind Usage
14008 @section Examples of @code{gnatfind} Usage
14012 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14013 Find declarations for all entities xyz referenced at least once in
14014 main.adb. The references are search in every library file in the search
14017 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14020 The output will look like:
14022 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14023 ^directory/^[directory]^main.adb:24:10: xyz <= body
14024 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14028 that is to say, one of the entities xyz found in main.adb is declared at
14029 line 12 of main.ads (and its body is in main.adb), and another one is
14030 declared at line 45 of foo.ads
14032 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14033 This is the same command as the previous one, instead @code{gnatfind} will
14034 display the content of the Ada source file lines.
14036 The output will look like:
14039 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14041 ^directory/^[directory]^main.adb:24:10: xyz <= body
14043 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14048 This can make it easier to find exactly the location your are looking
14051 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14052 Find references to all entities containing an x that are
14053 referenced on line 123 of main.ads.
14054 The references will be searched only in main.adb and foo.adb.
14056 @item gnatfind main.ads:123
14057 Find declarations and bodies for all entities that are referenced on
14058 line 123 of main.ads.
14060 This is the same as @code{gnatfind "*":main.adb:123}.
14062 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14063 Find the declaration for the entity referenced at column 45 in
14064 line 123 of file main.adb in directory mydir. Note that it
14065 is usual to omit the identifier name when the column is given,
14066 since the column position identifies a unique reference.
14068 The column has to be the beginning of the identifier, and should not
14069 point to any character in the middle of the identifier.
14073 @node File Name Krunching Using gnatkr
14074 @chapter File Name Krunching Using @code{gnatkr}
14078 This chapter discusses the method used by the compiler to shorten
14079 the default file names chosen for Ada units so that they do not
14080 exceed the maximum length permitted. It also describes the
14081 @code{gnatkr} utility that can be used to determine the result of
14082 applying this shortening.
14086 * Krunching Method::
14087 * Examples of gnatkr Usage::
14091 @section About @code{gnatkr}
14094 The default file naming rule in GNAT
14095 is that the file name must be derived from
14096 the unit name. The exact default rule is as follows:
14099 Take the unit name and replace all dots by hyphens.
14101 If such a replacement occurs in the
14102 second character position of a name, and the first character is
14103 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
14104 ^~ (tilde)^$ (dollar sign)^
14105 instead of a minus.
14107 The reason for this exception is to avoid clashes
14108 with the standard names for children of System, Ada, Interfaces,
14109 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
14112 The @code{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
14113 switch of the compiler activates a "krunching"
14114 circuit that limits file names to nn characters (where nn is a decimal
14115 integer). For example, using OpenVMS,
14116 where the maximum file name length is
14117 39, the value of nn is usually set to 39, but if you want to generate
14118 a set of files that would be usable if ported to a system with some
14119 different maximum file length, then a different value can be specified.
14120 The default value of 39 for OpenVMS need not be specified.
14122 The @code{gnatkr} utility can be used to determine the krunched name for
14123 a given file, when krunched to a specified maximum length.
14126 @section Using @code{gnatkr}
14129 The @code{gnatkr} command has the form
14133 $ gnatkr @var{name} [@var{length}]
14139 $ gnatkr @var{name} /COUNT=nn
14144 @var{name} can be an Ada name with dots or the GNAT name of the unit,
14145 where the dots representing child units or subunit are replaced by
14146 hyphens. The only confusion arises if a name ends in @code{.ads} or
14147 @code{.adb}. @code{gnatkr} takes this to be an extension if there are
14148 no other dots in the name^ and the whole name is in lowercase^^.
14150 @var{length} represents the length of the krunched name. The default
14151 when no argument is given is ^8^39^ characters. A length of zero stands for
14152 unlimited, in other words do not chop except for system files which are
14156 The output is the krunched name. The output has an extension only if the
14157 original argument was a file name with an extension.
14159 @node Krunching Method
14160 @section Krunching Method
14163 The initial file name is determined by the name of the unit that the file
14164 contains. The name is formed by taking the full expanded name of the
14165 unit and replacing the separating dots with hyphens and
14166 using ^lowercase^uppercase^
14167 for all letters, except that a hyphen in the second character position is
14168 replaced by a ^tilde^dollar sign^ if the first character is
14169 ^a, i, g, or s^A, I, G, or S^.
14170 The extension is @code{.ads} for a
14171 specification and @code{.adb} for a body.
14172 Krunching does not affect the extension, but the file name is shortened to
14173 the specified length by following these rules:
14177 The name is divided into segments separated by hyphens, tildes or
14178 underscores and all hyphens, tildes, and underscores are
14179 eliminated. If this leaves the name short enough, we are done.
14182 If the name is too long, the longest segment is located (left-most if there are two
14183 of equal length), and shortened by dropping its last character. This is
14184 repeated until the name is short enough.
14186 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
14187 to fit the name into 8 characters as required by some operating systems.
14190 our-strings-wide_fixed 22
14191 our strings wide fixed 19
14192 our string wide fixed 18
14193 our strin wide fixed 17
14194 our stri wide fixed 16
14195 our stri wide fixe 15
14196 our str wide fixe 14
14197 our str wid fixe 13
14203 Final file name: oustwifi.adb
14207 The file names for all predefined units are always krunched to eight
14208 characters. The krunching of these predefined units uses the following
14209 special prefix replacements:
14213 replaced by @file{^a^A^-}
14216 replaced by @file{^g^G^-}
14219 replaced by @file{^i^I^-}
14222 replaced by @file{^s^S^-}
14225 These system files have a hyphen in the second character position. That
14226 is why normal user files replace such a character with a
14227 ^tilde^dollar sign^, to
14228 avoid confusion with system file names.
14230 As an example of this special rule, consider
14231 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
14234 ada-strings-wide_fixed 22
14235 a- strings wide fixed 18
14236 a- string wide fixed 17
14237 a- strin wide fixed 16
14238 a- stri wide fixed 15
14239 a- stri wide fixe 14
14240 a- str wide fixe 13
14246 Final file name: a-stwifi.adb
14250 Of course no file shortening algorithm can guarantee uniqueness over all
14251 possible unit names, and if file name krunching is used then it is your
14252 responsibility to ensure that no name clashes occur. The utility
14253 program @code{gnatkr} is supplied for conveniently determining the
14254 krunched name of a file.
14256 @node Examples of gnatkr Usage
14257 @section Examples of @code{gnatkr} Usage
14264 $ gnatkr very_long_unit_name.ads --> velounna.ads
14265 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
14266 $ gnatkr Grandparent.Parent.Child --> grparchi
14268 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
14269 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
14272 @node Preprocessing Using gnatprep
14273 @chapter Preprocessing Using @code{gnatprep}
14277 The @code{gnatprep} utility provides
14278 a simple preprocessing capability for Ada programs.
14279 It is designed for use with GNAT, but is not dependent on any special
14284 * Switches for gnatprep::
14285 * Form of Definitions File::
14286 * Form of Input Text for gnatprep::
14289 @node Using gnatprep
14290 @section Using @code{gnatprep}
14293 To call @code{gnatprep} use
14296 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
14303 is the full name of the input file, which is an Ada source
14304 file containing preprocessor directives.
14307 is the full name of the output file, which is an Ada source
14308 in standard Ada form. When used with GNAT, this file name will
14309 normally have an ads or adb suffix.
14312 is the full name of a text file containing definitions of
14313 symbols to be referenced by the preprocessor. This argument is
14314 optional, and can be replaced by the use of the @code{-D} switch.
14317 is an optional sequence of switches as described in the next section.
14320 @node Switches for gnatprep
14321 @section Switches for @code{gnatprep}
14325 @item ^-b^/BLANK_LINES^
14326 Causes both preprocessor lines and the lines deleted by
14327 preprocessing to be replaced by blank lines in the output source file,
14328 preserving line numbers in the output file.
14330 @item ^-c^/COMMENTS^
14331 Causes both preprocessor lines and the lines deleted
14332 by preprocessing to be retained in the output source as comments marked
14333 with the special string "--! ". This option will result in line numbers
14334 being preserved in the output file.
14336 @item -Dsymbol=value
14337 Defines a new symbol, associated with value. If no value is given on the
14338 command line, then symbol is considered to be @code{True}. This switch
14339 can be used in place of a definition file.
14342 @item /REMOVE (default)
14343 This is the default setting which causes lines deleted by preprocessing
14344 to be entirely removed from the output file.
14347 @item ^-r^/REFERENCE^
14348 Causes a @code{Source_Reference} pragma to be generated that
14349 references the original input file, so that error messages will use
14350 the file name of this original file. The use of this switch implies
14351 that preprocessor lines are not to be removed from the file, so its
14352 use will force @code{^-b^/BLANK_LINES^} mode if
14353 @code{^-c^/COMMENTS^}
14354 has not been specified explicitly.
14356 Note that if the file to be preprocessed contains multiple units, then
14357 it will be necessary to @code{gnatchop} the output file from
14358 @code{gnatprep}. If a @code{Source_Reference} pragma is present
14359 in the preprocessed file, it will be respected by
14360 @code{gnatchop ^-r^/REFERENCE^}
14361 so that the final chopped files will correctly refer to the original
14362 input source file for @code{gnatprep}.
14364 @item ^-s^/SYMBOLS^
14365 Causes a sorted list of symbol names and values to be
14366 listed on the standard output file.
14368 @item ^-u^/UNDEFINED^
14369 Causes undefined symbols to be treated as having the value FALSE in the context
14370 of a preprocessor test. In the absence of this option, an undefined symbol in
14371 a @code{#if} or @code{#elsif} test will be treated as an error.
14377 Note: if neither @code{-b} nor @code{-c} is present,
14378 then preprocessor lines and
14379 deleted lines are completely removed from the output, unless -r is
14380 specified, in which case -b is assumed.
14383 @node Form of Definitions File
14384 @section Form of Definitions File
14387 The definitions file contains lines of the form
14394 where symbol is an identifier, following normal Ada (case-insensitive)
14395 rules for its syntax, and value is one of the following:
14399 Empty, corresponding to a null substitution
14401 A string literal using normal Ada syntax
14403 Any sequence of characters from the set
14404 (letters, digits, period, underline).
14408 Comment lines may also appear in the definitions file, starting with
14409 the usual @code{--},
14410 and comments may be added to the definitions lines.
14412 @node Form of Input Text for gnatprep
14413 @section Form of Input Text for @code{gnatprep}
14416 The input text may contain preprocessor conditional inclusion lines,
14417 as well as general symbol substitution sequences.
14419 The preprocessor conditional inclusion commands have the form
14424 #if @i{expression} [then]
14426 #elsif @i{expression} [then]
14428 #elsif @i{expression} [then]
14439 In this example, @i{expression} is defined by the following grammar:
14441 @i{expression} ::= <symbol>
14442 @i{expression} ::= <symbol> = "<value>"
14443 @i{expression} ::= <symbol> = <symbol>
14444 @i{expression} ::= <symbol> 'Defined
14445 @i{expression} ::= not @i{expression}
14446 @i{expression} ::= @i{expression} and @i{expression}
14447 @i{expression} ::= @i{expression} or @i{expression}
14448 @i{expression} ::= @i{expression} and then @i{expression}
14449 @i{expression} ::= @i{expression} or else @i{expression}
14450 @i{expression} ::= ( @i{expression} )
14454 For the first test (@i{expression} ::= <symbol>) the symbol must have
14455 either the value true or false, that is to say the right-hand of the
14456 symbol definition must be one of the (case-insensitive) literals
14457 @code{True} or @code{False}. If the value is true, then the
14458 corresponding lines are included, and if the value is false, they are
14461 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
14462 the symbol has been defined in the definition file or by a @code{-D}
14463 switch on the command line. Otherwise, the test is false.
14465 The equality tests are case insensitive, as are all the preprocessor lines.
14467 If the symbol referenced is not defined in the symbol definitions file,
14468 then the effect depends on whether or not switch @code{-u}
14469 is specified. If so, then the symbol is treated as if it had the value
14470 false and the test fails. If this switch is not specified, then
14471 it is an error to reference an undefined symbol. It is also an error to
14472 reference a symbol that is defined with a value other than @code{True}
14475 The use of the @code{not} operator inverts the sense of this logical test, so
14476 that the lines are included only if the symbol is not defined.
14477 The @code{then} keyword is optional as shown
14479 The @code{#} must be the first non-blank character on a line, but
14480 otherwise the format is free form. Spaces or tabs may appear between
14481 the @code{#} and the keyword. The keywords and the symbols are case
14482 insensitive as in normal Ada code. Comments may be used on a
14483 preprocessor line, but other than that, no other tokens may appear on a
14484 preprocessor line. Any number of @code{elsif} clauses can be present,
14485 including none at all. The @code{else} is optional, as in Ada.
14487 The @code{#} marking the start of a preprocessor line must be the first
14488 non-blank character on the line, i.e. it must be preceded only by
14489 spaces or horizontal tabs.
14491 Symbol substitution outside of preprocessor lines is obtained by using
14499 anywhere within a source line, except in a comment or within a
14500 string literal. The identifier
14501 following the @code{$} must match one of the symbols defined in the symbol
14502 definition file, and the result is to substitute the value of the
14503 symbol in place of @code{$symbol} in the output file.
14505 Note that although the substitution of strings within a string literal
14506 is not possible, it is possible to have a symbol whose defined value is
14507 a string literal. So instead of setting XYZ to @code{hello} and writing:
14510 Header : String := "$XYZ";
14514 you should set XYZ to @code{"hello"} and write:
14517 Header : String := $XYZ;
14521 and then the substitution will occur as desired.
14524 @node The GNAT Run-Time Library Builder gnatlbr
14525 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
14527 @cindex Library builder
14530 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
14531 supplied configuration pragmas.
14534 * Running gnatlbr::
14535 * Switches for gnatlbr::
14536 * Examples of gnatlbr Usage::
14539 @node Running gnatlbr
14540 @section Running @code{gnatlbr}
14543 The @code{gnatlbr} command has the form
14546 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
14549 @node Switches for gnatlbr
14550 @section Switches for @code{gnatlbr}
14553 @code{gnatlbr} recognizes the following switches:
14556 @item /CREATE=directory
14557 @cindex @code{/CREATE=directory} (@code{gnatlbr})
14558 Create the new run-time library in the specified directory.
14560 @item /SET=directory
14561 @cindex @code{/SET=directory} (@code{gnatlbr})
14562 Make the library in the specified directory the current run-time
14565 @item /DELETE=directory
14566 @cindex @code{/DELETE=directory} (@code{gnatlbr})
14567 Delete the run-time library in the specified directory.
14570 @cindex @code{/CONFIG=file} (@code{gnatlbr})
14572 Use the configuration pragmas in the specified file when building
14576 Use the configuration pragmas in the specified file when compiling.
14580 @node Examples of gnatlbr Usage
14581 @section Example of @code{gnatlbr} Usage
14584 Contents of VAXFLOAT.ADC:
14585 pragma Float_Representation (VAX_Float);
14587 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
14589 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
14594 @node The GNAT Library Browser gnatls
14595 @chapter The GNAT Library Browser @code{gnatls}
14597 @cindex Library browser
14600 @code{gnatls} is a tool that outputs information about compiled
14601 units. It gives the relationship between objects, unit names and source
14602 files. It can also be used to check the source dependencies of a unit
14603 as well as various characteristics.
14607 * Switches for gnatls::
14608 * Examples of gnatls Usage::
14611 @node Running gnatls
14612 @section Running @code{gnatls}
14615 The @code{gnatls} command has the form
14618 $ gnatls switches @var{object_or_ali_file}
14622 The main argument is the list of object or @file{ali} files
14623 (@pxref{The Ada Library Information Files})
14624 for which information is requested.
14626 In normal mode, without additional option, @code{gnatls} produces a
14627 four-column listing. Each line represents information for a specific
14628 object. The first column gives the full path of the object, the second
14629 column gives the name of the principal unit in this object, the third
14630 column gives the status of the source and the fourth column gives the
14631 full path of the source representing this unit.
14632 Here is a simple example of use:
14636 ^./^[]^demo1.o demo1 DIF demo1.adb
14637 ^./^[]^demo2.o demo2 OK demo2.adb
14638 ^./^[]^hello.o h1 OK hello.adb
14639 ^./^[]^instr-child.o instr.child MOK instr-child.adb
14640 ^./^[]^instr.o instr OK instr.adb
14641 ^./^[]^tef.o tef DIF tef.adb
14642 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
14643 ^./^[]^tgef.o tgef DIF tgef.adb
14647 The first line can be interpreted as follows: the main unit which is
14649 object file @file{demo1.o} is demo1, whose main source is in
14650 @file{demo1.adb}. Furthermore, the version of the source used for the
14651 compilation of demo1 has been modified (DIF). Each source file has a status
14652 qualifier which can be:
14655 @item OK (unchanged)
14656 The version of the source file used for the compilation of the
14657 specified unit corresponds exactly to the actual source file.
14659 @item MOK (slightly modified)
14660 The version of the source file used for the compilation of the
14661 specified unit differs from the actual source file but not enough to
14662 require recompilation. If you use gnatmake with the qualifier
14663 @code{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
14664 MOK will not be recompiled.
14666 @item DIF (modified)
14667 No version of the source found on the path corresponds to the source
14668 used to build this object.
14670 @item ??? (file not found)
14671 No source file was found for this unit.
14673 @item HID (hidden, unchanged version not first on PATH)
14674 The version of the source that corresponds exactly to the source used
14675 for compilation has been found on the path but it is hidden by another
14676 version of the same source that has been modified.
14680 @node Switches for gnatls
14681 @section Switches for @code{gnatls}
14684 @code{gnatls} recognizes the following switches:
14687 @item ^-a^/ALL_UNITS^
14688 @cindex @code{^-a^/ALL_UNITS^} (@code{gnatls})
14689 Consider all units, including those of the predefined Ada library.
14690 Especially useful with @code{^-d^/DEPENDENCIES^}.
14692 @item ^-d^/DEPENDENCIES^
14693 @cindex @code{^-d^/DEPENDENCIES^} (@code{gnatls})
14694 List sources from which specified units depend on.
14696 @item ^-h^/OUTPUT=OPTIONS^
14697 @cindex @code{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
14698 Output the list of options.
14700 @item ^-o^/OUTPUT=OBJECTS^
14701 @cindex @code{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
14702 Only output information about object files.
14704 @item ^-s^/OUTPUT=SOURCES^
14705 @cindex @code{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
14706 Only output information about source files.
14708 @item ^-u^/OUTPUT=UNITS^
14709 @cindex @code{^-u^/OUTPUT=UNITS^} (@code{gnatls})
14710 Only output information about compilation units.
14712 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
14713 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
14714 @itemx ^-I^/SEARCH=^@var{dir}
14715 @itemx ^-I-^/NOCURRENT_DIRECTORY^
14717 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
14718 (see @ref{Switches for gnatmake}).
14720 @item --RTS=@var{rts-path}
14721 @cindex @code{--RTS} (@code{gnatls})
14722 Specifies the default location of the runtime library. Same meaning as the
14723 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
14725 @item ^-v^/OUTPUT=VERBOSE^
14726 @cindex @code{^-s^/OUTPUT=VERBOSE^} (@code{gnatls})
14727 Verbose mode. Output the complete source and object paths. Do not use
14728 the default column layout but instead use long format giving as much as
14729 information possible on each requested units, including special
14730 characteristics such as:
14733 @item Preelaborable
14734 The unit is preelaborable in the Ada 95 sense.
14737 No elaboration code has been produced by the compiler for this unit.
14740 The unit is pure in the Ada 95 sense.
14742 @item Elaborate_Body
14743 The unit contains a pragma Elaborate_Body.
14746 The unit contains a pragma Remote_Types.
14748 @item Shared_Passive
14749 The unit contains a pragma Shared_Passive.
14752 This unit is part of the predefined environment and cannot be modified
14755 @item Remote_Call_Interface
14756 The unit contains a pragma Remote_Call_Interface.
14762 @node Examples of gnatls Usage
14763 @section Example of @code{gnatls} Usage
14767 Example of using the verbose switch. Note how the source and
14768 object paths are affected by the -I switch.
14771 $ gnatls -v -I.. demo1.o
14773 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
14775 Source Search Path:
14776 <Current_Directory>
14778 /home/comar/local/adainclude/
14780 Object Search Path:
14781 <Current_Directory>
14783 /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
14788 Kind => subprogram body
14789 Flags => No_Elab_Code
14790 Source => demo1.adb modified
14794 The following is an example of use of the dependency list.
14795 Note the use of the -s switch
14796 which gives a straight list of source files. This can be useful for
14797 building specialized scripts.
14800 $ gnatls -d demo2.o
14801 ./demo2.o demo2 OK demo2.adb
14807 $ gnatls -d -s -a demo1.o
14809 /home/comar/local/adainclude/ada.ads
14810 /home/comar/local/adainclude/a-finali.ads
14811 /home/comar/local/adainclude/a-filico.ads
14812 /home/comar/local/adainclude/a-stream.ads
14813 /home/comar/local/adainclude/a-tags.ads
14816 /home/comar/local/adainclude/gnat.ads
14817 /home/comar/local/adainclude/g-io.ads
14819 /home/comar/local/adainclude/system.ads
14820 /home/comar/local/adainclude/s-exctab.ads
14821 /home/comar/local/adainclude/s-finimp.ads
14822 /home/comar/local/adainclude/s-finroo.ads
14823 /home/comar/local/adainclude/s-secsta.ads
14824 /home/comar/local/adainclude/s-stalib.ads
14825 /home/comar/local/adainclude/s-stoele.ads
14826 /home/comar/local/adainclude/s-stratt.ads
14827 /home/comar/local/adainclude/s-tasoli.ads
14828 /home/comar/local/adainclude/s-unstyp.ads
14829 /home/comar/local/adainclude/unchconv.ads
14835 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
14837 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
14838 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
14839 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
14840 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
14841 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
14845 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
14846 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
14848 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
14849 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
14850 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
14851 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
14852 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
14853 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
14854 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
14855 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
14856 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
14857 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
14858 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
14863 @node GNAT and Libraries
14864 @chapter GNAT and Libraries
14865 @cindex Library, building, installing
14868 This chapter addresses some of the issues related to building and using
14869 a library with GNAT. It also shows how the GNAT run-time library can be
14873 * Creating an Ada Library::
14874 * Installing an Ada Library::
14875 * Using an Ada Library::
14876 * Creating an Ada Library to be Used in a Non-Ada Context::
14877 * Rebuilding the GNAT Run-Time Library::
14880 @node Creating an Ada Library
14881 @section Creating an Ada Library
14884 In the GNAT environment, a library has two components:
14889 Compiled code and Ali files. See @ref{The Ada Library Information Files}.
14893 In order to use other packages @ref{The GNAT Compilation Model}
14894 requires a certain number of sources to be available to the compiler.
14896 sources required includes the specs of all the packages that make up the
14897 visible part of the library as well as all the sources upon which they
14898 depend. The bodies of all visible generic units must also be provided.
14900 Although it is not strictly mandatory, it is recommended that all sources
14901 needed to recompile the library be provided, so that the user can make
14902 full use of inter-unit inlining and source-level debugging. This can also
14903 make the situation easier for users that need to upgrade their compilation
14904 toolchain and thus need to recompile the library from sources.
14907 The compiled code can be provided in different ways. The simplest way is
14908 to provide directly the set of objects produced by the compiler during
14909 the compilation of the library. It is also possible to group the objects
14910 into an archive using whatever commands are provided by the operating
14911 system. Finally, it is also possible to create a shared library (see
14912 option -shared in the GCC manual).
14915 There are various possibilities for compiling the units that make up the
14916 library: for example with a Makefile @ref{Using the GNU make Utility},
14917 or with a conventional script.
14918 For simple libraries, it is also possible to create a
14919 dummy main program which depends upon all the packages that comprise the
14920 interface of the library. This dummy main program can then be given to
14921 gnatmake, in order to build all the necessary objects. Here is an example
14922 of such a dummy program and the generic commands used to build an
14923 archive or a shared library.
14929 @b{with} My_Lib.Service1;
14930 @b{with} My_Lib.Service2;
14931 @b{with} My_Lib.Service3;
14932 @b{procedure} My_Lib_Dummy @b{is}
14937 # compiling the library
14938 $ gnatmake -c my_lib_dummy.adb
14940 # we don't need the dummy object itself
14941 $ rm my_lib_dummy.o my_lib_dummy.ali
14943 # create an archive with the remaining objects
14944 $ ar rc libmy_lib.a *.o
14945 # some systems may require "ranlib" to be run as well
14947 # or create a shared library
14948 $ gcc -shared -o libmy_lib.so *.o
14949 # some systems may require the code to have been compiled with -fPIC
14953 When the objects are grouped in an archive or a shared library, the user
14954 needs to specify the desired library at link time, unless a pragma
14955 linker_options has been used in one of the sources:
14957 @b{pragma} Linker_Options ("-lmy_lib");
14960 @node Installing an Ada Library
14961 @section Installing an Ada Library
14964 In the GNAT model, installing a library consists in copying into a specific
14965 location the files that make up this library. It is possible to install
14966 the sources in a different directory from the other files (ALI, objects,
14967 archives) since the source path and the object path can easily be
14968 specified separately.
14971 For general purpose libraries, it is possible for the system
14972 administrator to put those libraries in the default compiler paths. To
14973 achieve this, he must specify their location in the configuration files
14974 "ada_source_path" and "ada_object_path" that must be located in the GNAT
14975 installation tree at the same place as the gcc spec file. The location of
14976 the gcc spec file can be determined as follows:
14982 The configuration files mentioned above have simple format: each line in them
14983 must contain one unique
14984 directory name. Those names are added to the corresponding path
14985 in their order of appearance in the file. The names can be either absolute
14986 or relative, in the latter case, they are relative to where theses files
14990 "ada_source_path" and "ada_object_path" might actually not be present in a
14991 GNAT installation, in which case, GNAT will look for its run-time library in
14992 the directories "adainclude" for the sources and "adalib" for the
14993 objects and ALI files. When the files exist, the compiler does not
14994 look in "adainclude" and "adalib" at all, and thus the "ada_source_path" file
14995 must contain the location for the GNAT run-time sources (which can simply
14996 be "adainclude"). In the same way, the "ada_object_path" file must contain
14997 the location for the GNAT run-time objects (which can simply
15001 You can also specify a new default path to the runtime library at compilation
15002 time with the switch "--RTS=@var{rts-path}". You can easily choose and change
15003 the runtime you want your program to be compiled with. This switch is
15004 recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref.
15007 It is possible to install a library before or after the standard GNAT
15008 library, by reordering the lines in the configuration files. In general, a
15009 library must be installed before the GNAT library if it redefines any part of it.
15011 @node Using an Ada Library
15012 @section Using an Ada Library
15015 In order to use a Ada library, you need to make sure that this
15016 library is on both your source and object path
15017 @ref{Search Paths and the Run-Time Library (RTL)}
15018 and @ref{Search Paths for gnatbind}. For
15019 instance, you can use the library "mylib" installed in "/dir/my_lib_src"
15020 and "/dir/my_lib_obj" with the following commands:
15023 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
15028 This can be simplified down to the following:
15032 when the following conditions are met:
15035 "/dir/my_lib_src" has been added by the user to the environment
15036 variable "ADA_INCLUDE_PATH", or by the administrator to the file
15039 "/dir/my_lib_obj" has been added by the user to the environment
15040 variable "ADA_OBJECTS_PATH", or by the administrator to the file
15043 a pragma linker_options, as mentioned in @ref{Creating an Ada Library}
15044 as been added to the sources.
15048 @node Creating an Ada Library to be Used in a Non-Ada Context
15049 @section Creating an Ada Library to be Used in a Non-Ada Context
15052 The previous sections detailed how to create and install a library that
15053 was usable from an Ada main program. Using this library in a non-Ada
15054 context is not possible, because the elaboration of the library is
15055 automatically done as part of the main program elaboration.
15057 GNAT also provides the ability to build libraries that can be used both
15058 in an Ada and non-Ada context. This section describes how to build such
15059 a library, and then how to use it from a C program. The method for
15060 interfacing with the library from other languages such as Fortran for
15061 instance remains the same.
15063 @subsection Creating the Library
15066 @item Identify the units representing the interface of the library.
15068 Here is an example of simple library interface:
15071 package Interface is
15073 procedure Do_Something;
15075 procedure Do_Something_Else;
15080 @item Use @code{pragma Export} or @code{pragma Convention} for the
15083 Our package @code{Interface} is then updated as follow:
15085 package Interface is
15087 procedure Do_Something;
15088 pragma Export (C, Do_Something, "do_something");
15090 procedure Do_Something_Else;
15091 pragma Export (C, Do_Something_Else, "do_something_else");
15096 @item Compile all the units composing the library.
15098 @item Bind the library objects.
15100 This step is performed by invoking gnatbind with the @code{-L<prefix>}
15101 switch. @code{gnatbind} will then generate the library elaboration
15102 procedure (named @code{<prefix>init}) and the run-time finalization
15103 procedure (named @code{<prefix>final}).
15106 # generate the binder file in Ada
15107 $ gnatbind -Lmylib interface
15109 # generate the binder file in C
15110 $ gnatbind -C -Lmylib interface
15113 @item Compile the files generated by the binder
15116 $ gcc -c b~interface.adb
15119 @item Create the library;
15121 The procedure is identical to the procedure explained in
15122 @ref{Creating an Ada Library},
15123 except that @file{b~interface.o} needs to be added to
15124 the list of objects.
15127 # create an archive file
15128 $ ar cr libmylib.a b~interface.o <other object files>
15130 # create a shared library
15131 $ gcc -shared -o libmylib.so b~interface.o <other object files>
15134 @item Provide a "foreign" view of the library interface;
15136 The example below shows the content of @code{mylib_interface.h} (note
15137 that there is no rule for the naming of this file, any name can be used)
15139 /* the library elaboration procedure */
15140 extern void mylibinit (void);
15142 /* the library finalization procedure */
15143 extern void mylibfinal (void);
15145 /* the interface exported by the library */
15146 extern void do_something (void);
15147 extern void do_something_else (void);
15151 @subsection Using the Library
15154 Libraries built as explained above can be used from any program, provided
15155 that the elaboration procedures (named @code{mylibinit} in the previous
15156 example) are called before the library services are used. Any number of
15157 libraries can be used simultaneously, as long as the elaboration
15158 procedure of each library is called.
15160 Below is an example of C program that uses our @code{mylib} library.
15163 #include "mylib_interface.h"
15168 /* First, elaborate the library before using it */
15171 /* Main program, using the library exported entities */
15173 do_something_else ();
15175 /* Library finalization at the end of the program */
15182 Note that this same library can be used from an equivalent Ada main
15183 program. In addition, if the libraries are installed as detailed in
15184 @ref{Installing an Ada Library}, it is not necessary to invoke the
15185 library elaboration and finalization routines. The binder will ensure
15186 that this is done as part of the main program elaboration and
15187 finalization phases.
15189 @subsection The Finalization Phase
15192 Invoking any library finalization procedure generated by @code{gnatbind}
15193 shuts down the Ada run time permanently. Consequently, the finalization
15194 of all Ada libraries must be performed at the end of the program. No
15195 call to these libraries nor the Ada run time should be made past the
15196 finalization phase.
15198 @subsection Restrictions in Libraries
15201 The pragmas listed below should be used with caution inside libraries,
15202 as they can create incompatibilities with other Ada libraries:
15204 @item pragma @code{Locking_Policy}
15205 @item pragma @code{Queuing_Policy}
15206 @item pragma @code{Task_Dispatching_Policy}
15207 @item pragma @code{Unreserve_All_Interrupts}
15209 When using a library that contains such pragmas, the user must make sure
15210 that all libraries use the same pragmas with the same values. Otherwise,
15211 a @code{Program_Error} will
15212 be raised during the elaboration of the conflicting
15213 libraries. The usage of these pragmas and its consequences for the user
15214 should therefore be well documented.
15216 Similarly, the traceback in exception occurrences mechanism should be
15217 enabled or disabled in a consistent manner across all libraries.
15218 Otherwise, a Program_Error will be raised during the elaboration of the
15219 conflicting libraries.
15221 If the @code{'Version} and @code{'Body_Version}
15222 attributes are used inside a library, then it is necessary to
15223 perform a @code{gnatbind} step that mentions all ali files in all
15224 libraries, so that version identifiers can be properly computed.
15225 In practice these attributes are rarely used, so this is unlikely
15226 to be a consideration.
15228 @node Rebuilding the GNAT Run-Time Library
15229 @section Rebuilding the GNAT Run-Time Library
15232 It may be useful to recompile the GNAT library in various contexts, the
15233 most important one being the use of partition-wide configuration pragmas
15234 such as Normalize_Scalar. A special Makefile called
15235 @code{Makefile.adalib} is provided to that effect and can be found in
15236 the directory containing the GNAT library. The location of this
15237 directory depends on the way the GNAT environment has been installed and can
15238 be determined by means of the command:
15245 The last entry in the object search path usually contains the
15246 gnat library. This Makefile contains its own documentation and in
15247 particular the set of instructions needed to rebuild a new library and
15250 @node Using the GNU make Utility
15251 @chapter Using the GNU @code{make} Utility
15255 This chapter offers some examples of makefiles that solve specific
15256 problems. It does not explain how to write a makefile (see the GNU make
15257 documentation), nor does it try to replace the @code{gnatmake} utility
15258 (@pxref{The GNAT Make Program gnatmake}).
15260 All the examples in this section are specific to the GNU version of
15261 make. Although @code{make} is a standard utility, and the basic language
15262 is the same, these examples use some advanced features found only in
15266 * Using gnatmake in a Makefile::
15267 * Automatically Creating a List of Directories::
15268 * Generating the Command Line Switches::
15269 * Overcoming Command Line Length Limits::
15272 @node Using gnatmake in a Makefile
15273 @section Using gnatmake in a Makefile
15278 Complex project organizations can be handled in a very powerful way by
15279 using GNU make combined with gnatmake. For instance, here is a Makefile
15280 which allows you to build each subsystem of a big project into a separate
15281 shared library. Such a makefile allows you to significantly reduce the link
15282 time of very big applications while maintaining full coherence at
15283 each step of the build process.
15285 The list of dependencies are handled automatically by
15286 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
15287 the appropriate directories.
15289 Note that you should also read the example on how to automatically
15290 create the list of directories (@pxref{Automatically Creating a List of Directories})
15291 which might help you in case your project has a lot of
15297 @font@heightrm=cmr8
15300 ## This Makefile is intended to be used with the following directory
15302 ## - The sources are split into a series of csc (computer software components)
15303 ## Each of these csc is put in its own directory.
15304 ## Their name are referenced by the directory names.
15305 ## They will be compiled into shared library (although this would also work
15306 ## with static libraries
15307 ## - The main program (and possibly other packages that do not belong to any
15308 ## csc is put in the top level directory (where the Makefile is).
15309 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
15310 ## \_ second_csc (sources) __ lib (will contain the library)
15312 ## Although this Makefile is build for shared library, it is easy to modify
15313 ## to build partial link objects instead (modify the lines with -shared and
15316 ## With this makefile, you can change any file in the system or add any new
15317 ## file, and everything will be recompiled correctly (only the relevant shared
15318 ## objects will be recompiled, and the main program will be re-linked).
15320 # The list of computer software component for your project. This might be
15321 # generated automatically.
15324 # Name of the main program (no extension)
15327 # If we need to build objects with -fPIC, uncomment the following line
15330 # The following variable should give the directory containing libgnat.so
15331 # You can get this directory through 'gnatls -v'. This is usually the last
15332 # directory in the Object_Path.
15335 # The directories for the libraries
15336 # (This macro expands the list of CSC to the list of shared libraries, you
15337 # could simply use the expanded form :
15338 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
15339 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
15341 $@{MAIN@}: objects $@{LIB_DIR@}
15342 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
15343 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
15346 # recompile the sources
15347 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
15349 # Note: In a future version of GNAT, the following commands will be simplified
15350 # by a new tool, gnatmlib
15352 mkdir -p $@{dir $@@ @}
15353 cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
15354 cd $@{dir $@@ @}; cp -f ../*.ali .
15356 # The dependencies for the modules
15357 # Note that we have to force the expansion of *.o, since in some cases make won't
15358 # be able to do it itself.
15359 aa/lib/libaa.so: $@{wildcard aa/*.o@}
15360 bb/lib/libbb.so: $@{wildcard bb/*.o@}
15361 cc/lib/libcc.so: $@{wildcard cc/*.o@}
15363 # Make sure all of the shared libraries are in the path before starting the
15366 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
15369 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
15370 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
15371 $@{RM@} $@{CSC_LIST:%=%/*.o@}
15372 $@{RM@} *.o *.ali $@{MAIN@}
15375 @node Automatically Creating a List of Directories
15376 @section Automatically Creating a List of Directories
15379 In most makefiles, you will have to specify a list of directories, and
15380 store it in a variable. For small projects, it is often easier to
15381 specify each of them by hand, since you then have full control over what
15382 is the proper order for these directories, which ones should be
15385 However, in larger projects, which might involve hundreds of
15386 subdirectories, it might be more convenient to generate this list
15389 The example below presents two methods. The first one, although less
15390 general, gives you more control over the list. It involves wildcard
15391 characters, that are automatically expanded by @code{make}. Its
15392 shortcoming is that you need to explicitly specify some of the
15393 organization of your project, such as for instance the directory tree
15394 depth, whether some directories are found in a separate tree,...
15396 The second method is the most general one. It requires an external
15397 program, called @code{find}, which is standard on all Unix systems. All
15398 the directories found under a given root directory will be added to the
15404 @font@heightrm=cmr8
15407 # The examples below are based on the following directory hierarchy:
15408 # All the directories can contain any number of files
15409 # ROOT_DIRECTORY -> a -> aa -> aaa
15412 # -> b -> ba -> baa
15415 # This Makefile creates a variable called DIRS, that can be reused any time
15416 # you need this list (see the other examples in this section)
15418 # The root of your project's directory hierarchy
15422 # First method: specify explicitly the list of directories
15423 # This allows you to specify any subset of all the directories you need.
15426 DIRS := a/aa/ a/ab/ b/ba/
15429 # Second method: use wildcards
15430 # Note that the argument(s) to wildcard below should end with a '/'.
15431 # Since wildcards also return file names, we have to filter them out
15432 # to avoid duplicate directory names.
15433 # We thus use make's @code{dir} and @code{sort} functions.
15434 # It sets DIRs to the following value (note that the directories aaa and baa
15435 # are not given, unless you change the arguments to wildcard).
15436 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
15439 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/ $@{ROOT_DIRECTORY@}/*/*/@}@}@}
15442 # Third method: use an external program
15443 # This command is much faster if run on local disks, avoiding NFS slowdowns.
15444 # This is the most complete command: it sets DIRs to the following value:
15445 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
15448 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
15452 @node Generating the Command Line Switches
15453 @section Generating the Command Line Switches
15456 Once you have created the list of directories as explained in the
15457 previous section (@pxref{Automatically Creating a List of Directories}),
15458 you can easily generate the command line arguments to pass to gnatmake.
15460 For the sake of completeness, this example assumes that the source path
15461 is not the same as the object path, and that you have two separate lists
15465 # see "Automatically creating a list of directories" to create
15470 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
15471 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
15474 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
15477 @node Overcoming Command Line Length Limits
15478 @section Overcoming Command Line Length Limits
15481 One problem that might be encountered on big projects is that many
15482 operating systems limit the length of the command line. It is thus hard to give
15483 gnatmake the list of source and object directories.
15485 This example shows how you can set up environment variables, which will
15486 make @code{gnatmake} behave exactly as if the directories had been
15487 specified on the command line, but have a much higher length limit (or
15488 even none on most systems).
15490 It assumes that you have created a list of directories in your Makefile,
15491 using one of the methods presented in
15492 @ref{Automatically Creating a List of Directories}.
15493 For the sake of completeness, we assume that the object
15494 path (where the ALI files are found) is different from the sources patch.
15496 Note a small trick in the Makefile below: for efficiency reasons, we
15497 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
15498 expanded immediately by @code{make}. This way we overcome the standard
15499 make behavior which is to expand the variables only when they are
15505 @font@heightrm=cmr8
15508 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
15509 # This is the same thing as putting the -I arguments on the command line.
15510 # (the equivalent of using -aI on the command line would be to define
15511 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
15512 # You can of course have different values for these variables.
15514 # Note also that we need to keep the previous values of these variables, since
15515 # they might have been set before running 'make' to specify where the GNAT
15516 # library is installed.
15518 # see "Automatically creating a list of directories" to create these
15524 space:=$@{empty@} $@{empty@}
15525 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
15526 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
15527 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
15528 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
15529 export ADA_INCLUDE_PATH
15530 export ADA_OBJECT_PATH
15537 @node Finding Memory Problems with gnatmem
15538 @chapter Finding Memory Problems with @code{gnatmem}
15542 @code{gnatmem}, is a tool that monitors dynamic allocation and
15543 deallocation activity in a program, and displays information about
15544 incorrect deallocations and possible sources of memory leaks. Gnatmem
15545 provides three type of information:
15548 General information concerning memory management, such as the total
15549 number of allocations and deallocations, the amount of allocated
15550 memory and the high water mark, i.e. the largest amount of allocated
15551 memory in the course of program execution.
15554 Backtraces for all incorrect deallocations, that is to say deallocations
15555 which do not correspond to a valid allocation.
15558 Information on each allocation that is potentially the origin of a memory
15562 The @code{gnatmem} command has two modes. It can be used with @code{gdb}
15563 or with instrumented allocation and deallocation routines. The later
15564 mode is called the @code{GMEM} mode. Both modes produce the very same
15568 * Running gnatmem (GDB Mode)::
15569 * Running gnatmem (GMEM Mode)::
15570 * Switches for gnatmem::
15571 * Examples of gnatmem Usage::
15572 * GDB and GMEM Modes::
15573 * Implementation Note::
15576 @node Running gnatmem (GDB Mode)
15577 @section Running @code{gnatmem} (GDB Mode)
15580 The @code{gnatmem} command has the form
15583 $ gnatmem [-q] [n] [-o file] user_program [program_arg]*
15585 $ gnatmem [-q] [n] -i file
15589 Gnatmem must be supplied with the executable to examine, followed by its
15590 run-time inputs. For example, if a program is executed with the command:
15592 $ my_program arg1 arg2
15594 then it can be run under @code{gnatmem} control using the command:
15596 $ gnatmem my_program arg1 arg2
15599 The program is transparently executed under the control of the debugger
15600 @ref{The GNAT Debugger GDB}. This does not affect the behavior
15601 of the program, except for sensitive real-time programs. When the program
15602 has completed execution, @code{gnatmem} outputs a report containing general
15603 allocation/deallocation information and potential memory leak.
15604 For better results, the user program should be compiled with
15605 debugging options @ref{Switches for gcc}.
15607 Here is a simple example of use:
15609 *************** debut cc
15615 Total number of allocations : 45
15616 Total number of deallocations : 6
15617 Final Water Mark (non freed mem) : 11.29 Kilobytes
15618 High Water Mark : 11.40 Kilobytes
15623 Allocation Root # 2
15624 -------------------
15625 Number of non freed allocations : 11
15626 Final Water Mark (non freed mem) : 1.16 Kilobytes
15627 High Water Mark : 1.27 Kilobytes
15629 test_gm.adb:23 test_gm.alloc
15635 The first block of output give general information. In this case, the
15636 Ada construct "@b{new}" was executed 45 times, and only 6 calls to an
15637 unchecked deallocation routine occurred.
15639 Subsequent paragraphs display information on all allocation roots.
15640 An allocation root is a specific point in the execution of the program
15641 that generates some dynamic allocation, such as a "@b{new}" construct. This
15642 root is represented by an execution backtrace (or subprogram call
15643 stack). By default the backtrace depth for allocations roots is 1, so
15644 that a root corresponds exactly to a source location. The backtrace can
15645 be made deeper, to make the root more specific.
15647 @node Running gnatmem (GMEM Mode)
15648 @section Running @code{gnatmem} (GMEM Mode)
15649 @cindex @code{GMEM} (@code{gnatmem})
15652 The @code{gnatmem} command has the form
15655 $ gnatmem [-q] [n] -i gmem.out user_program [program_arg]*
15658 The program must have been linked with the instrumented version of the
15659 allocation and deallocation routines. This is done with linking with the
15660 @file{libgmem.a} library. For better results, the user program should be
15661 compiled with debugging options @ref{Switches for gcc}. For example to
15662 build @file{my_program}:
15665 $ gnatmake -g my_program -largs -lgmem
15669 When running @file{my_program} the file @file{gmem.out} is produced. This file
15670 contains information about all allocations and deallocations done by the
15671 program. It is produced by the instrumented allocations and
15672 deallocations routines and will be used by @code{gnatmem}.
15675 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
15676 examine followed by its run-time inputs. For example, if a program is
15677 executed with the command:
15679 $ my_program arg1 arg2
15681 then @file{gmem.out} can be analysed by @code{gnatmem} using the command:
15683 $ gnatmem -i gmem.out my_program arg1 arg2
15686 @node Switches for gnatmem
15687 @section Switches for @code{gnatmem}
15690 @code{gnatmem} recognizes the following switches:
15695 @cindex @code{-q} (@code{gnatmem})
15696 Quiet. Gives the minimum output needed to identify the origin of the
15697 memory leaks. Omit statistical information.
15700 @cindex @code{n} (@code{gnatmem})
15701 N is an integer literal (usually between 1 and 10) which controls the
15702 depth of the backtraces defining allocation root. The default value for
15703 N is 1. The deeper the backtrace, the more precise the localization of
15704 the root. Note that the total number of roots can depend on this
15707 @item @code{-o file}
15708 @cindex @code{-o} (@code{gnatmem})
15709 Direct the gdb output to the specified file. The @code{gdb} script used
15710 to generate this output is also saved in the file @file{gnatmem.tmp}.
15712 @item @code{-i file}
15713 @cindex @code{-i} (@code{gnatmem})
15714 Do the @code{gnatmem} processing starting from @file{file} which has
15715 been generated by a previous call to @code{gnatmem} with the -o
15716 switch or @file{gmem.out} produced by @code{GMEM} mode. This is useful
15717 for post mortem processing.
15721 @node Examples of gnatmem Usage
15722 @section Example of @code{gnatmem} Usage
15725 This section is based on the @code{GDB} mode of @code{gnatmem}. The same
15726 results can be achieved using @code{GMEM} mode. See section
15727 @ref{Running gnatmem (GMEM Mode)}.
15730 The first example shows the use of @code{gnatmem}
15731 on a simple leaking program.
15732 Suppose that we have the following Ada program:
15737 @b{with} Unchecked_Deallocation;
15738 @b{procedure} Test_Gm @b{is}
15740 @b{type} T @b{is array} (1..1000) @b{of} Integer;
15741 @b{type} Ptr @b{is access} T;
15742 @b{procedure} Free @b{is new} Unchecked_Deallocation (T, Ptr);
15745 @b{procedure} My_Alloc @b{is}
15750 @b{procedure} My_DeAlloc @b{is}
15754 @b{end} My_DeAlloc;
15758 @b{for} I @b{in} 1 .. 5 @b{loop}
15759 @b{for} J @b{in} I .. 5 @b{loop}
15770 The program needs to be compiled with debugging option:
15773 $ gnatmake -g test_gm
15776 @code{gnatmem} is invoked simply with
15782 which produces the following output:
15787 Total number of allocations : 18
15788 Total number of deallocations : 5
15789 Final Water Mark (non freed mem) : 53.00 Kilobytes
15790 High Water Mark : 56.90 Kilobytes
15792 Allocation Root # 1
15793 -------------------
15794 Number of non freed allocations : 11
15795 Final Water Mark (non freed mem) : 42.97 Kilobytes
15796 High Water Mark : 46.88 Kilobytes
15798 test_gm.adb:11 test_gm.my_alloc
15800 Allocation Root # 2
15801 -------------------
15802 Number of non freed allocations : 1
15803 Final Water Mark (non freed mem) : 10.02 Kilobytes
15804 High Water Mark : 10.02 Kilobytes
15806 s-secsta.adb:81 system.secondary_stack.ss_init
15808 Allocation Root # 3
15809 -------------------
15810 Number of non freed allocations : 1
15811 Final Water Mark (non freed mem) : 12 Bytes
15812 High Water Mark : 12 Bytes
15814 s-secsta.adb:181 system.secondary_stack.ss_init
15818 Note that the GNAT run time contains itself a certain number of
15819 allocations that have no corresponding deallocation,
15820 as shown here for root #2 and root
15821 #1. This is a normal behavior when the number of non freed allocations
15822 is one, it locates dynamic data structures that the run time needs for
15823 the complete lifetime of the program. Note also that there is only one
15824 allocation root in the user program with a single line back trace:
15825 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
15826 program shows that 'My_Alloc' is called at 2 different points in the
15827 source (line 21 and line 24). If those two allocation roots need to be
15828 distinguished, the backtrace depth parameter can be used:
15831 $ gnatmem 3 test_gm
15835 which will give the following output:
15840 Total number of allocations : 18
15841 Total number of deallocations : 5
15842 Final Water Mark (non freed mem) : 53.00 Kilobytes
15843 High Water Mark : 56.90 Kilobytes
15845 Allocation Root # 1
15846 -------------------
15847 Number of non freed allocations : 10
15848 Final Water Mark (non freed mem) : 39.06 Kilobytes
15849 High Water Mark : 42.97 Kilobytes
15851 test_gm.adb:11 test_gm.my_alloc
15852 test_gm.adb:24 test_gm
15853 b_test_gm.c:52 main
15855 Allocation Root # 2
15856 -------------------
15857 Number of non freed allocations : 1
15858 Final Water Mark (non freed mem) : 10.02 Kilobytes
15859 High Water Mark : 10.02 Kilobytes
15861 s-secsta.adb:81 system.secondary_stack.ss_init
15862 s-secsta.adb:283 <system__secondary_stack___elabb>
15863 b_test_gm.c:33 adainit
15865 Allocation Root # 3
15866 -------------------
15867 Number of non freed allocations : 1
15868 Final Water Mark (non freed mem) : 3.91 Kilobytes
15869 High Water Mark : 3.91 Kilobytes
15871 test_gm.adb:11 test_gm.my_alloc
15872 test_gm.adb:21 test_gm
15873 b_test_gm.c:52 main
15875 Allocation Root # 4
15876 -------------------
15877 Number of non freed allocations : 1
15878 Final Water Mark (non freed mem) : 12 Bytes
15879 High Water Mark : 12 Bytes
15881 s-secsta.adb:181 system.secondary_stack.ss_init
15882 s-secsta.adb:283 <system__secondary_stack___elabb>
15883 b_test_gm.c:33 adainit
15887 The allocation root #1 of the first example has been split in 2 roots #1
15888 and #3 thanks to the more precise associated backtrace.
15890 @node GDB and GMEM Modes
15891 @section GDB and GMEM Modes
15894 The main advantage of the @code{GMEM} mode is that it is a lot faster than the
15895 @code{GDB} mode where the application must be monitored by a @code{GDB} script.
15896 But the @code{GMEM} mode is available only for DEC Unix, Linux x86,
15897 Solaris (sparc and x86) and Windows 95/98/NT/2000 (x86).
15900 The main advantage of the @code{GDB} mode is that it is available on all
15901 supported platforms. But it can be very slow if the application does a
15902 lot of allocations and deallocations.
15904 @node Implementation Note
15905 @section Implementation Note
15908 * gnatmem Using GDB Mode::
15909 * gnatmem Using GMEM Mode::
15912 @node gnatmem Using GDB Mode
15913 @subsection @code{gnatmem} Using @code{GDB} Mode
15916 @code{gnatmem} executes the user program under the control of @code{GDB} using
15917 a script that sets breakpoints and gathers information on each dynamic
15918 allocation and deallocation. The output of the script is then analyzed
15920 in order to locate memory leaks and their origin in the
15921 program. Gnatmem works by recording each address returned by the
15922 allocation procedure (@code{__gnat_malloc})
15923 along with the backtrace at the
15924 allocation point. On each deallocation, the deallocated address is
15925 matched with the corresponding allocation. At the end of the processing,
15926 the unmatched allocations are considered potential leaks. All the
15927 allocations associated with the same backtrace are grouped together and
15928 form an allocation root. The allocation roots are then sorted so that
15929 those with the biggest number of unmatched allocation are printed
15930 first. A delicate aspect of this technique is to distinguish between the
15931 data produced by the user program and the data produced by the gdb
15932 script. Currently, on systems that allow probing the terminal, the gdb
15933 command "tty" is used to force the program output to be redirected to the
15934 current terminal while the @code{gdb} output is directed to a file or to a
15935 pipe in order to be processed subsequently by @code{gnatmem}.
15937 @node gnatmem Using GMEM Mode
15938 @subsection @code{gnatmem} Using @code{GMEM} Mode
15941 This mode use the same algorithm to detect memory leak as the @code{GDB}
15942 mode of @code{gnatmem}, the only difference is in the way data are
15943 gathered. In @code{GMEM} mode the program is linked with instrumented
15944 version of @code{__gnat_malloc} and @code{__gnat_free}
15945 routines. Information needed to find memory leak are recorded by these
15946 routines in file @file{gmem.out}. This mode also require that the stack
15947 traceback be available, this is only implemented on some platforms
15948 @ref{GDB and GMEM Modes}.
15953 @node Finding Memory Problems with GNAT Debug Pool
15954 @chapter Finding Memory Problems with GNAT Debug Pool
15956 @cindex storage, pool, memory corruption
15959 The use of unchecked deallocation and unchecked conversion can easily
15960 lead to incorrect memory references. The problems generated by such
15961 references are usually difficult to tackle because the symptoms can be
15962 very remote from the origin of the problem. In such cases, it is
15963 very helpful to detect the problem as early as possible. This is the
15964 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
15967 In order to use the GNAT specific debugging pool, the user must
15968 associate a debug pool object with each of the access types that may be
15969 related to suspected memory problems. See Ada Reference Manual
15972 @b{type} Ptr @b{is} @b{access} Some_Type;
15973 Pool : GNAT.Debug_Pools.Debug_Pool;
15974 @b{for} Ptr'Storage_Pool @b{use} Pool;
15977 @code{GNAT.Debug_Pools} is derived from of a GNAT-specific kind of
15978 pool: the Checked_Pool. Such pools, like standard Ada storage pools,
15979 allow the user to redefine allocation and deallocation strategies. They
15980 also provide a checkpoint for each dereference, through the use of
15981 the primitive operation @code{Dereference} which is implicitly called at
15982 each dereference of an access value.
15984 Once an access type has been associated with a debug pool, operations on
15985 values of the type may raise four distinct exceptions,
15986 which correspond to four potential kinds of memory corruption:
15989 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
15991 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
15993 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
15995 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
15999 For types associated with a Debug_Pool, dynamic allocation is performed using
16001 GNAT allocation routine. References to all allocated chunks of memory
16002 are kept in an internal dictionary. The deallocation strategy consists
16003 in not releasing the memory to the underlying system but rather to fill
16004 it with a memory pattern easily recognizable during debugging sessions:
16005 The memory pattern is the old IBM hexadecimal convention: 16#DEADBEEF#.
16006 Upon each dereference, a check is made that the access value denotes a properly
16007 allocated memory location. Here is a complete example of use of
16008 @code{Debug_Pools}, that includes typical instances of memory corruption:
16013 @b{with} Gnat.Io; @b{use} Gnat.Io;
16014 @b{with} Unchecked_Deallocation;
16015 @b{with} Unchecked_Conversion;
16016 @b{with} GNAT.Debug_Pools;
16017 @b{with} System.Storage_Elements;
16018 @b{with} Ada.Exceptions; @b{use} Ada.Exceptions;
16019 @b{procedure} Debug_Pool_Test @b{is}
16021 @b{type} T @b{is} @b{access} Integer;
16022 @b{type} U @b{is} @b{access} @b{all} T;
16024 P : GNAT.Debug_Pools.Debug_Pool;
16025 @b{for} T'Storage_Pool @b{use} P;
16027 @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T);
16028 @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T);
16029 A, B : @b{aliased} T;
16031 @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line);
16035 A := @b{new} Integer;
16036 B := @b{new} Integer;
16041 Put_Line (Integer'Image(B.@b{all}));
16043 @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
16048 @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
16052 Put_Line (Integer'Image(B.@b{all}));
16054 @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
16059 @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
16062 @b{end} Debug_Pool_Test;
16065 The debug pool mechanism provides the following precise diagnostics on the
16066 execution of this erroneous program:
16069 Total allocated bytes : 0
16070 Total deallocated bytes : 0
16071 Current Water Mark: 0
16075 Total allocated bytes : 8
16076 Total deallocated bytes : 0
16077 Current Water Mark: 8
16080 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16081 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16082 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16083 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16085 Total allocated bytes : 8
16086 Total deallocated bytes : 4
16087 Current Water Mark: 4
16092 @node Creating Sample Bodies Using gnatstub
16093 @chapter Creating Sample Bodies Using @code{gnatstub}
16097 @code{gnatstub} creates body stubs, that is, empty but compilable bodies
16098 for library unit declarations.
16100 To create a body stub, @code{gnatstub} has to compile the library
16101 unit declaration. Therefore, bodies can be created only for legal
16102 library units. Moreover, if a library unit depends semantically upon
16103 units located outside the current directory, you have to provide
16104 the source search path when calling @code{gnatstub}, see the description
16105 of @code{gnatstub} switches below.
16108 * Running gnatstub::
16109 * Switches for gnatstub::
16112 @node Running gnatstub
16113 @section Running @code{gnatstub}
16116 @code{gnatstub} has the command-line interface of the form
16119 $ gnatstub [switches] filename [directory]
16126 is the name of the source file that contains a library unit declaration
16127 for which a body must be created. This name should follow the GNAT file name
16128 conventions. No crunching is allowed for this file name. The file
16129 name may contain the path information.
16132 indicates the directory to place a body stub (default is the
16136 is an optional sequence of switches as described in the next section
16139 @node Switches for gnatstub
16140 @section Switches for @code{gnatstub}
16145 If the destination directory already contains a file with a name of the body file
16146 for the argument spec file, replace it with the generated body stub.
16148 @item ^-hs^/HEADER=SPEC^
16149 Put the comment header (i.e. all the comments preceding the
16150 compilation unit) from the source of the library unit declaration
16151 into the body stub.
16153 @item ^-hg^/HEADER=GENERAL^
16154 Put a sample comment header into the body stub.
16157 @itemx ^-I-^/NOCURRENT_DIRECTORY^
16158 These switches have the same meaning as in calls to gcc.
16159 They define the source search path in the call to gcc issued
16160 by @code{gnatstub} to compile an argument source file.
16162 @item ^-i^/INDENTATION=^@var{n}
16163 (@var{n} is a decimal natural number). Set the indentation level in the
16164 generated body sample to n, '^-i0^/INDENTATION=0^' means "no indentation",
16165 the default indentation is 3.
16167 @item ^-k^/TREE_FILE=SAVE^
16168 Do not remove the tree file (i.e. the snapshot of the compiler internal
16169 structures used by @code{gnatstub}) after creating the body stub.
16171 @item ^-l^/LINE_LENGTH=^@var{n}
16172 (@var{n} is a decimal positive number) Set the maximum line length in the
16173 body stub to n, the default is 78.
16176 Quiet mode: do not generate a confirmation when a body is
16177 successfully created or a message when a body is not required for an
16180 @item ^-r^/TREE_FILE=REUSE^
16181 Reuse the tree file (if it exists) instead of creating it: instead of
16182 creating the tree file for the library unit declaration, gnatstub
16183 tries to find it in the current directory and use it for creating
16184 a body. If the tree file is not found, no body is created. @code{^-r^/REUSE^}
16185 also implies @code{^-k^/SAVE^}, whether or not
16186 @code{^-k^/SAVE^} is set explicitly.
16188 @item ^-t^/TREE_FILE=OVERWRITE^
16189 Overwrite the existing tree file: if the current directory already
16190 contains the file which, according to the GNAT file name rules should
16191 be considered as a tree file for the argument source file, gnatstub
16192 will refuse to create the tree file needed to create a body sampler,
16193 unless @code{-t} option is set
16195 @item ^-v^/VERBOSE^
16196 Verbose mode: generate version information.
16200 @node Reducing the Size of Ada Executables with gnatelim
16201 @chapter Reducing the Size of Ada Executables with @code{gnatelim}
16206 * Eliminate Pragma::
16208 * Preparing Tree and Bind Files for gnatelim::
16209 * Running gnatelim::
16210 * Correcting the List of Eliminate Pragmas::
16211 * Making Your Executables Smaller::
16212 * Summary of the gnatelim Usage Cycle::
16215 @node About gnatelim
16216 @section About @code{gnatelim}
16219 When a program shares a set of Ada
16220 packages with other programs, it may happen that this program uses
16221 only a fraction of the subprograms defined in these packages. The code
16222 created for these unused subprograms increases the size of the executable.
16224 @code{gnatelim} tracks unused subprograms in an Ada program and
16225 outputs a list of GNAT-specific @code{Eliminate} pragmas (see next
16226 section) marking all the subprograms that are declared but never called.
16227 By placing the list of @code{Eliminate} pragmas in the GNAT configuration
16228 file @file{gnat.adc} and recompiling your program, you may decrease the
16229 size of its executable, because the compiler will not generate the code
16230 for 'eliminated' subprograms.
16232 @code{gnatelim} needs as its input data a set of tree files
16233 (see @ref{Tree Files}) representing all the components of a program to
16234 process and a bind file for a main subprogram (see
16235 @ref{Preparing Tree and Bind Files for gnatelim}).
16237 @node Eliminate Pragma
16238 @section @code{Eliminate} Pragma
16242 The simplified syntax of the Eliminate pragma used by @code{gnatelim} is:
16246 @b{pragma} Eliminate (Library_Unit_Name, Subprogram_Name);
16253 @item Library_Unit_Name
16254 full expanded Ada name of a library unit
16256 @item Subprogram_Name
16257 a simple or expanded name of a subprogram declared within this
16263 The effect of an @code{Eliminate} pragma placed in the GNAT configuration
16264 file @file{gnat.adc} is:
16269 If the subprogram @code{Subprogram_Name} is declared within
16270 the library unit @code{Library_Unit_Name}, the compiler will not generate
16271 code for this subprogram. This applies to all overloaded subprograms denoted
16272 by @code{Subprogram_Name}.
16275 If a subprogram marked by the pragma @code{Eliminate} is used (called)
16276 in a program, the compiler will produce an error message in the place where
16281 @section Tree Files
16285 A tree file stores a snapshot of the compiler internal data
16286 structures at the very end of a successful compilation. It contains all the
16287 syntactic and semantic information for the compiled unit and all the
16288 units upon which it depends semantically.
16289 To use tools that make use of tree files, you
16290 need to first produce the right set of tree files.
16292 GNAT produces correct tree files when -gnatt -gnatc options are set
16293 in a gcc call. The tree files have an .adt extension.
16294 Therefore, to produce a tree file for the compilation unit contained in a file
16295 named @file{foo.adb}, you must use the command
16298 $ gcc -c -gnatc -gnatt foo.adb
16302 and you will get the tree file @file{foo.adt}.
16305 @node Preparing Tree and Bind Files for gnatelim
16306 @section Preparing Tree and Bind Files for @code{gnatelim}
16309 A set of tree files covering the program to be analyzed with
16310 @code{gnatelim} and
16311 the bind file for the main subprogram does not have to
16312 be in the current directory.
16313 '-T' gnatelim option may be used to provide
16314 the search path for tree files, and '-b'
16315 option may be used to point to the bind
16316 file to process (see @ref{Running gnatelim})
16318 If you do not have the appropriate set of tree
16319 files and the right bind file, you
16320 may create them in the current directory using the following procedure.
16322 Let @code{Main_Prog} be the name of a main subprogram, and suppose
16323 this subprogram is in a file named @file{main_prog.adb}.
16325 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
16326 the main subprogram. @code{gnatelim} can work with both Ada and C
16327 bind files; when both are present, it uses the Ada bind file.
16328 The following commands will build the program and create the bind file:
16331 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
16332 $ gnatbind main_prog
16336 To create a minimal set of tree files covering the whole program, call
16337 @code{gnatmake} for this program as follows:
16341 $ GNAT MAKE /FORCE_COMPILE /ACTIONS=COMPILE /NOLOAD /TREE_OUTPUT MAIN_PROG
16344 $ gnatmake -f -c -gnatc -gnatt Main_Prog
16349 The @code{^-c^/ACTIONS=COMPILE^} gnatmake option turns off the bind and link
16350 steps, that are useless anyway because the sources are compiled with
16351 @option{-gnatc} option which turns off code generation.
16353 The @code{^-f^/FORCE_COMPILE^} gnatmake option forces
16354 recompilation of all the needed sources.
16356 This sequence of actions will create all the data needed by @code{gnatelim}
16357 from scratch and therefore guarantee its consistency. If you would like to
16358 use some existing set of files as @code{gnatelim} output, you must make
16359 sure that the set of files is complete and consistent. You can use the
16360 @code{-m} switch to check if there are missed tree files
16362 Note, that @code{gnatelim} needs neither object nor ALI files.
16364 @node Running gnatelim
16365 @section Running @code{gnatelim}
16368 @code{gnatelim} has the following command-line interface:
16371 $ gnatelim [options] name
16375 @code{name} should be a full expanded Ada name of a main subprogram
16376 of a program (partition).
16378 @code{gnatelim} options:
16382 Quiet mode: by default @code{gnatelim} generates to the standard error
16383 stream a trace of the source file names of the compilation units being
16384 processed. This option turns this trace off.
16386 @item ^-v^/VERBOSE^
16387 Verbose mode: @code{gnatelim} version information is printed as Ada
16388 comments to the standard output stream.
16391 Also look for subprograms from the GNAT run time that can be eliminated.
16394 Check if any tree files are missing for an accurate result.
16396 @item ^-T^/TREE_DIRS=^@var{dir}
16397 When looking for tree files also look in directory @var{dir}
16399 @item ^-b^/BIND_FILE=^@var{bind_file}
16400 Specifies @var{bind_file} as the bind file to process. If not set, the name
16401 of the bind file is computed from the full expanded Ada name of a main subprogram.
16404 Activate internal debugging switches. @var{x} is a letter or digit, or
16405 string of letters or digits, which specifies the type of debugging
16406 mode desired. Normally these are used only for internal development
16407 or system debugging purposes. You can find full documentation for these
16408 switches in the body of the @code{Gnatelim.Options} unit in the compiler
16409 source file @file{gnatelim-options.adb}.
16413 @code{gnatelim} sends its output to the standard output stream, and all the
16414 tracing and debug information is sent to the standard error stream.
16415 In order to produce a proper GNAT configuration file
16416 @file{gnat.adc}, redirection must be used:
16420 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
16423 $ gnatelim Main_Prog > gnat.adc
16432 $ gnatelim Main_Prog >> gnat.adc
16437 In order to append the @code{gnatelim} output to the existing contents of
16440 @node Correcting the List of Eliminate Pragmas
16441 @section Correcting the List of Eliminate Pragmas
16444 In some rare cases it may happen that @code{gnatelim} will try to eliminate
16445 subprograms which are actually called in the program. In this case, the
16446 compiler will generate an error message of the form:
16449 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
16453 You will need to manually remove the wrong @code{Eliminate} pragmas from
16454 the @file{gnat.adc} file. It is advised that you recompile your program
16455 from scratch after that because you need a consistent @file{gnat.adc} file
16456 during the entire compilation.
16458 @node Making Your Executables Smaller
16459 @section Making Your Executables Smaller
16462 In order to get a smaller executable for your program you now have to
16463 recompile the program completely with the new @file{gnat.adc} file
16464 created by @code{gnatelim} in your current directory:
16467 $ gnatmake ^-f Main_Prog^/FORCE_COMPILE MAIN_PROG^
16471 (you will need @code{^-f^/FORCE_COMPILE^} option for gnatmake to
16472 recompile everything
16473 with the set of pragmas @code{Eliminate} you have obtained with
16476 Be aware that the set of @code{Eliminate} pragmas is specific to each
16477 program. It is not recommended to merge sets of @code{Eliminate}
16478 pragmas created for different programs in one @file{gnat.adc} file.
16480 @node Summary of the gnatelim Usage Cycle
16481 @section Summary of the gnatelim Usage Cycle
16484 Here is a quick summary of the steps to be taken in order to reduce
16485 the size of your executables with @code{gnatelim}. You may use
16486 other GNAT options to control the optimization level,
16487 to produce the debugging information, to set search path, etc.
16491 Produce a bind file and a set of tree files
16494 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
16495 $ gnatbind main_prog
16497 $ GNAT MAKE /FORCE_COMPILE /NO_LINK /NOLOAD /TREE_OUTPUT MAIN_PROG
16500 $ gnatmake -f -c -gnatc -gnatt Main_Prog
16505 Generate a list of @code{Eliminate} pragmas
16508 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
16511 $ gnatelim Main_Prog >[>] gnat.adc
16516 Recompile the application
16519 $ gnatmake ^-f Main_Prog^/FORCE_COMPILE MAIN_PROG^
16524 @node Other Utility Programs
16525 @chapter Other Utility Programs
16528 This chapter discusses some other utility programs available in the Ada
16532 * Using Other Utility Programs with GNAT::
16533 * The gnatpsta Utility Program::
16534 * The External Symbol Naming Scheme of GNAT::
16535 * Ada Mode for Glide::
16536 * Converting Ada Files to html with gnathtml::
16537 * Installing gnathtml::
16544 @node Using Other Utility Programs with GNAT
16545 @section Using Other Utility Programs with GNAT
16548 The object files generated by GNAT are in standard system format and in
16549 particular the debugging information uses this format. This means
16550 programs generated by GNAT can be used with existing utilities that
16551 depend on these formats.
16554 In general, any utility program that works with C will also often work with
16555 Ada programs generated by GNAT. This includes software utilities such as
16556 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
16560 @node The gnatpsta Utility Program
16561 @section The @code{gnatpsta} Utility Program
16564 Many of the definitions in package Standard are implementation-dependent.
16565 However, the source of this package does not exist as an Ada source
16566 file, so these values cannot be determined by inspecting the source.
16567 They can be determined by examining in detail the coding of
16568 @file{cstand.adb} which creates the image of Standard in the compiler,
16569 but this is awkward and requires a great deal of internal knowledge
16572 The @code{gnatpsta} utility is designed to deal with this situation.
16573 It is an Ada program that dynamically determines the
16574 values of all the relevant parameters in Standard, and prints them
16575 out in the form of an Ada source listing for Standard, displaying all
16576 the values of interest. This output is generated to
16579 To determine the value of any parameter in package Standard, simply
16580 run @code{gnatpsta} with no qualifiers or arguments, and examine
16581 the output. This is preferable to consulting documentation, because
16582 you know that the values you are getting are the actual ones provided
16583 by the executing system.
16585 @node The External Symbol Naming Scheme of GNAT
16586 @section The External Symbol Naming Scheme of GNAT
16589 In order to interpret the output from GNAT, when using tools that are
16590 originally intended for use with other languages, it is useful to
16591 understand the conventions used to generate link names from the Ada
16594 All link names are in all lowercase letters. With the exception of library
16595 procedure names, the mechanism used is simply to use the full expanded
16596 Ada name with dots replaced by double underscores. For example, suppose
16597 we have the following package spec:
16602 @b{package} QRS @b{is}
16610 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
16611 the corresponding link name is @code{qrs__mn}.
16613 Of course if a @code{pragma Export} is used this may be overridden:
16618 @b{package} Exports @b{is}
16620 @b{pragma} Export (Var1, C, External_Name => "var1_name");
16622 @b{pragma} Export (Var2, C, Link_Name => "var2_link_name");
16629 In this case, the link name for @var{Var1} is whatever link name the
16630 C compiler would assign for the C function @var{var1_name}. This typically
16631 would be either @var{var1_name} or @var{_var1_name}, depending on operating
16632 system conventions, but other possibilities exist. The link name for
16633 @var{Var2} is @var{var2_link_name}, and this is not operating system
16637 One exception occurs for library level procedures. A potential ambiguity
16638 arises between the required name @code{_main} for the C main program,
16639 and the name we would otherwise assign to an Ada library level procedure
16640 called @code{Main} (which might well not be the main program).
16642 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
16643 names. So if we have a library level procedure such as
16648 @b{procedure} Hello (S : String);
16654 the external name of this procedure will be @var{_ada_hello}.
16656 @node Ada Mode for Glide
16657 @section Ada Mode for @code{Glide}
16660 The Glide mode for programming in Ada (both, Ada83 and Ada95) helps the
16661 user in understanding existing code and facilitates writing new code. It
16662 furthermore provides some utility functions for easier integration of
16663 standard Emacs features when programming in Ada.
16665 @subsection General Features:
16669 Full Integrated Development Environment :
16673 support of 'project files' for the configuration (directories,
16674 compilation options,...)
16677 compiling and stepping through error messages.
16680 running and debugging your applications within Glide.
16684 easy to use for beginners by pull-down menus,
16687 user configurable by many user-option variables.
16690 @subsection Ada Mode Features That Help Understanding Code:
16694 functions for easy and quick stepping through Ada code,
16697 getting cross reference information for identifiers (e.g. find the
16698 defining place by a keystroke),
16701 displaying an index menu of types and subprograms and move point to
16705 automatic color highlighting of the various entities in Ada code.
16708 @subsection Glide Support for Writing Ada Code:
16712 switching between spec and body files with possible
16713 autogeneration of body files,
16716 automatic formating of subprograms parameter lists.
16719 automatic smart indentation according to Ada syntax,
16722 automatic completion of identifiers,
16725 automatic casing of identifiers, keywords, and attributes,
16728 insertion of statement templates,
16731 filling comment paragraphs like filling normal text,
16734 For more information, please refer to the online Glide documentation
16735 available in the Glide --> Help Menu.
16737 @node Converting Ada Files to html with gnathtml
16738 @section Converting Ada Files to html with @code{gnathtml}
16741 This @code{Perl} script allows Ada source files to be browsed using
16742 standard Web browsers. For installation procedure, see the section
16743 @xref{Installing gnathtml}.
16745 Ada reserved keywords are highlighted in a bold font and Ada comments in
16746 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
16747 switch to suppress the generation of cross-referencing information, user
16748 defined variables and types will appear in a different color; you will
16749 be able to click on any identifier and go to its declaration.
16751 The command line is as follow:
16753 $ perl gnathtml.pl [switches] ada-files
16756 You can pass it as many Ada files as you want. @code{gnathtml} will generate
16757 an html file for every ada file, and a global file called @file{index.htm}.
16758 This file is an index of every identifier defined in the files.
16760 The available switches are the following ones :
16764 @cindex @code{-83} (@code{gnathtml})
16765 Only the subset on the Ada 83 keywords will be highlighted, not the full
16766 Ada 95 keywords set.
16768 @item -cc @var{color}
16769 This option allows you to change the color used for comments. The default
16770 value is green. The color argument can be any name accepted by html.
16773 @cindex @code{-d} (@code{gnathtml})
16774 If the ada files depend on some other files (using for instance the
16775 @code{with} command, the latter will also be converted to html.
16776 Only the files in the user project will be converted to html, not the files
16777 in the run-time library itself.
16780 This command is the same as -d above, but @code{gnathtml} will also look
16781 for files in the run-time library, and generate html files for them.
16784 @cindex @code{-f} (@code{gnathtml})
16785 By default, gnathtml will generate html links only for global entities
16786 ('with'ed units, global variables and types,...). If you specify the
16787 @code{-f} on the command line, then links will be generated for local
16790 @item -l @var{number}
16791 @cindex @code{-l} (@code{gnathtml})
16792 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
16793 will number the html files every @var{number} line.
16796 @cindex @code{-I} (@code{gnathtml})
16797 Specify a directory to search for library files (@file{.ali} files) and
16798 source files. You can provide several -I switches on the command line,
16799 and the directories will be parsed in the order of the command line.
16802 @cindex @code{-o} (@code{gnathtml})
16803 Specify the output directory for html files. By default, gnathtml will
16804 saved the generated html files in a subdirectory named @file{html/}.
16806 @item -p @var{file}
16807 @cindex @code{-p} (@code{gnathtml})
16808 If you are using Emacs and the most recent Emacs Ada mode, which provides
16809 a full Integrated Development Environment for compiling, checking,
16810 running and debugging applications, you may be using @file{.adp} files
16811 to give the directories where Emacs can find sources and object files.
16813 Using this switch, you can tell gnathtml to use these files. This allows
16814 you to get an html version of your application, even if it is spread
16815 over multiple directories.
16817 @item -sc @var{color}
16818 @cindex @code{-sc} (@code{gnathtml})
16819 This option allows you to change the color used for symbol definitions.
16820 The default value is red. The color argument can be any name accepted by html.
16822 @item -t @var{file}
16823 @cindex @code{-t} (@code{gnathtml})
16824 This switch provides the name of a file. This file contains a list of
16825 file names to be converted, and the effect is exactly as though they had
16826 appeared explicitly on the command line. This
16827 is the recommended way to work around the command line length limit on some
16832 @node Installing gnathtml
16833 @section Installing @code{gnathtml}
16836 @code{Perl} needs to be installed on your machine to run this script.
16837 @code{Perl} is freely available for almost every architecture and
16838 Operating System via the Internet.
16840 On Unix systems, you may want to modify the first line of the script
16841 @code{gnathtml}, to explicitly tell the Operating system where Perl
16842 is. The syntax of this line is :
16844 #!full_path_name_to_perl
16848 Alternatively, you may run the script using the following command line:
16851 $ perl gnathtml.pl [switches] files
16860 The GNAT distribution provides an Ada 95 template for the Digital Language
16861 Sensitive Editor (LSE), a component of DECset. In order to
16862 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
16869 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
16870 of DECset. To use it proceed as outlined under "HELP PCA", except for running
16871 the collection phase with the /DEBUG qualifier.
16874 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
16875 $ DEFINE LIB$DEBUG PCA$COLLECTOR
16876 $ RUN/DEBUG <PROGRAM_NAME>
16881 @node Running and Debugging Ada Programs
16882 @chapter Running and Debugging Ada Programs
16886 This chapter discusses how to debug Ada programs. An incorrect Ada program
16887 may be handled in three ways by the GNAT compiler:
16891 The illegality may be a violation of the static semantics of Ada. In
16892 that case GNAT diagnoses the constructs in the program that are illegal.
16893 It is then a straightforward matter for the user to modify those parts of
16897 The illegality may be a violation of the dynamic semantics of Ada. In
16898 that case the program compiles and executes, but may generate incorrect
16899 results, or may terminate abnormally with some exception.
16902 When presented with a program that contains convoluted errors, GNAT
16903 itself may terminate abnormally without providing full diagnostics on
16904 the incorrect user program.
16908 * The GNAT Debugger GDB::
16910 * Introduction to GDB Commands::
16911 * Using Ada Expressions::
16912 * Calling User-Defined Subprograms::
16913 * Using the Next Command in a Function::
16916 * Debugging Generic Units::
16917 * GNAT Abnormal Termination or Failure to Terminate::
16918 * Naming Conventions for GNAT Source Files::
16919 * Getting Internal Debugging Information::
16920 * Stack Traceback::
16926 @node The GNAT Debugger GDB
16927 @section The GNAT Debugger GDB
16930 @code{GDB} is a general purpose, platform-independent debugger that
16931 can be used to debug mixed-language programs compiled with @code{GCC},
16932 and in particular is capable of debugging Ada programs compiled with
16933 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
16934 complex Ada data structures.
16936 The manual @cite{Debugging with GDB}
16938 , located in the GNU:[DOCS] directory,
16940 contains full details on the usage of @code{GDB}, including a section on
16941 its usage on programs. This manual should be consulted for full
16942 details. The section that follows is a brief introduction to the
16943 philosophy and use of @code{GDB}.
16945 When GNAT programs are compiled, the compiler optionally writes debugging
16946 information into the generated object file, including information on
16947 line numbers, and on declared types and variables. This information is
16948 separate from the generated code. It makes the object files considerably
16949 larger, but it does not add to the size of the actual executable that
16950 will be loaded into memory, and has no impact on run-time performance. The
16951 generation of debug information is triggered by the use of the
16952 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
16953 the compilations. It is important to emphasize that the use of these
16954 options does not change the generated code.
16956 The debugging information is written in standard system formats that
16957 are used by many tools, including debuggers and profilers. The format
16958 of the information is typically designed to describe C types and
16959 semantics, but GNAT implements a translation scheme which allows full
16960 details about Ada types and variables to be encoded into these
16961 standard C formats. Details of this encoding scheme may be found in
16962 the file exp_dbug.ads in the GNAT source distribution. However, the
16963 details of this encoding are, in general, of no interest to a user,
16964 since @code{GDB} automatically performs the necessary decoding.
16966 When a program is bound and linked, the debugging information is
16967 collected from the object files, and stored in the executable image of
16968 the program. Again, this process significantly increases the size of
16969 the generated executable file, but it does not increase the size of
16970 the executable program itself. Furthermore, if this program is run in
16971 the normal manner, it runs exactly as if the debug information were
16972 not present, and takes no more actual memory.
16974 However, if the program is run under control of @code{GDB}, the
16975 debugger is activated. The image of the program is loaded, at which
16976 point it is ready to run. If a run command is given, then the program
16977 will run exactly as it would have if @code{GDB} were not present. This
16978 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
16979 entirely non-intrusive until a breakpoint is encountered. If no
16980 breakpoint is ever hit, the program will run exactly as it would if no
16981 debugger were present. When a breakpoint is hit, @code{GDB} accesses
16982 the debugging information and can respond to user commands to inspect
16983 variables, and more generally to report on the state of execution.
16986 @section Running GDB
16990 The debugger can be launched directly and simply from @code{glide} or
16991 through its graphical interface: @code{gvd}. It can also be used
16992 directly in text mode. Here is described the basic use of @code{GDB}
16993 in text mode. All the commands described below can be used in the
16994 @code{gvd} console window eventhough there is usually other more
16995 graphical ways to achieve the same goals.
16999 The command to run de graphical interface of the debugger is
17006 The command to run @code{GDB} in text mode is
17009 $ ^gdb program^$ GDB PROGRAM^
17013 where @code{^program^PROGRAM^} is the name of the executable file. This
17014 activates the debugger and results in a prompt for debugger commands.
17015 The simplest command is simply @code{run}, which causes the program to run
17016 exactly as if the debugger were not present. The following section
17017 describes some of the additional commands that can be given to @code{GDB}.
17021 Please refer to the debugging section of the chapter specific to your
17022 cross environment at the end of this manual.
17025 @node Introduction to GDB Commands
17026 @section Introduction to GDB Commands
17029 @code{GDB} contains a large repertoire of commands. The manual
17030 @cite{Debugging with GDB}
17032 , located in the GNU:[DOCS] directory,
17034 includes extensive documentation on the use
17035 of these commands, together with examples of their use. Furthermore,
17036 the command @var{help} invoked from within @code{GDB} activates a simple help
17037 facility which summarizes the available commands and their options.
17038 In this section we summarize a few of the most commonly
17039 used commands to give an idea of what @code{GDB} is about. You should create
17040 a simple program with debugging information and experiment with the use of
17041 these @code{GDB} commands on the program as you read through the
17045 @item set args @var{arguments}
17046 The @var{arguments} list above is a list of arguments to be passed to
17047 the program on a subsequent run command, just as though the arguments
17048 had been entered on a normal invocation of the program. The @code{set args}
17049 command is not needed if the program does not require arguments.
17052 The @code{run} command causes execution of the program to start from
17053 the beginning. If the program is already running, that is to say if
17054 you are currently positioned at a breakpoint, then a prompt will ask
17055 for confirmation that you want to abandon the current execution and
17058 @item breakpoint @var{location}
17059 The breakpoint command sets a breakpoint, that is to say a point at which
17060 execution will halt and @code{GDB} will await further
17061 commands. @var{location} is
17062 either a line number within a file, given in the format @code{file:linenumber},
17063 or it is the name of a subprogram. If you request that a breakpoint be set on
17064 a subprogram that is overloaded, a prompt will ask you to specify on which of
17065 those subprograms you want to breakpoint. You can also
17066 specify that all of them should be breakpointed. If the program is run
17067 and execution encounters the breakpoint, then the program
17068 stops and @code{GDB} signals that the breakpoint was encountered by
17069 printing the line of code before which the program is halted.
17071 @item breakpoint exception @var{name}
17072 A special form of the breakpoint command which breakpoints whenever
17073 exception @var{name} is raised.
17074 If @var{name} is omitted,
17075 then a breakpoint will occur when any exception is raised.
17077 @item print @var{expression}
17078 This will print the value of the given expression. Most simple
17079 Ada expression formats are properly handled by @code{GDB}, so the expression
17080 can contain function calls, variables, operators, and attribute references.
17083 Continues execution following a breakpoint, until the next breakpoint or the
17084 termination of the program.
17087 Executes a single line after a breakpoint. If the next statement is a subprogram
17088 call, execution continues into (the first statement of) the
17092 Executes a single line. If this line is a subprogram call, executes and
17093 returns from the call.
17096 Lists a few lines around the current source location. In practice, it
17097 is usually more convenient to have a separate edit window open with the
17098 relevant source file displayed. Successive applications of this command
17099 print subsequent lines. The command can be given an argument which is a
17100 line number, in which case it displays a few lines around the specified one.
17103 Displays a backtrace of the call chain. This command is typically
17104 used after a breakpoint has occurred, to examine the sequence of calls that
17105 leads to the current breakpoint. The display includes one line for each
17106 activation record (frame) corresponding to an active subprogram.
17109 At a breakpoint, @code{GDB} can display the values of variables local
17110 to the current frame. The command @code{up} can be used to
17111 examine the contents of other active frames, by moving the focus up
17112 the stack, that is to say from callee to caller, one frame at a time.
17115 Moves the focus of @code{GDB} down from the frame currently being
17116 examined to the frame of its callee (the reverse of the previous command),
17118 @item frame @var{n}
17119 Inspect the frame with the given number. The value 0 denotes the frame
17120 of the current breakpoint, that is to say the top of the call stack.
17124 The above list is a very short introduction to the commands that
17125 @code{GDB} provides. Important additional capabilities, including conditional
17126 breakpoints, the ability to execute command sequences on a breakpoint,
17127 the ability to debug at the machine instruction level and many other
17128 features are described in detail in @cite{Debugging with GDB}.
17129 Note that most commands can be abbreviated
17130 (for example, c for continue, bt for backtrace).
17132 @node Using Ada Expressions
17133 @section Using Ada Expressions
17134 @cindex Ada expressions
17137 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
17138 extensions. The philosophy behind the design of this subset is
17142 That @code{GDB} should provide basic literals and access to operations for
17143 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
17144 leaving more sophisticated computations to subprograms written into the
17145 program (which therefore may be called from @code{GDB}).
17148 That type safety and strict adherence to Ada language restrictions
17149 are not particularly important to the @code{GDB} user.
17152 That brevity is important to the @code{GDB} user.
17155 Thus, for brevity, the debugger acts as if there were
17156 implicit @code{with} and @code{use} clauses in effect for all user-written
17157 packages, thus making it unnecessary to fully qualify most names with
17158 their packages, regardless of context. Where this causes ambiguity,
17159 @code{GDB} asks the user's intent.
17161 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
17163 @node Calling User-Defined Subprograms
17164 @section Calling User-Defined Subprograms
17167 An important capability of @code{GDB} is the ability to call user-defined
17168 subprograms while debugging. This is achieved simply by entering
17169 a subprogram call statement in the form:
17172 call subprogram-name (parameters)
17176 The keyword @code{call} can be omitted in the normal case where the
17177 @code{subprogram-name} does not coincide with any of the predefined
17178 @code{GDB} commands.
17180 The effect is to invoke the given subprogram, passing it the
17181 list of parameters that is supplied. The parameters can be expressions and
17182 can include variables from the program being debugged. The
17183 subprogram must be defined
17184 at the library level within your program, and @code{GDB} will call the
17185 subprogram within the environment of your program execution (which
17186 means that the subprogram is free to access or even modify variables
17187 within your program).
17189 The most important use of this facility is in allowing the inclusion of
17190 debugging routines that are tailored to particular data structures
17191 in your program. Such debugging routines can be written to provide a suitably
17192 high-level description of an abstract type, rather than a low-level dump
17193 of its physical layout. After all, the standard
17194 @code{GDB print} command only knows the physical layout of your
17195 types, not their abstract meaning. Debugging routines can provide information
17196 at the desired semantic level and are thus enormously useful.
17198 For example, when debugging GNAT itself, it is crucial to have access to
17199 the contents of the tree nodes used to represent the program internally.
17200 But tree nodes are represented simply by an integer value (which in turn
17201 is an index into a table of nodes).
17202 Using the @code{print} command on a tree node would simply print this integer
17203 value, which is not very useful. But the PN routine (defined in file
17204 treepr.adb in the GNAT sources) takes a tree node as input, and displays
17205 a useful high level representation of the tree node, which includes the
17206 syntactic category of the node, its position in the source, the integers
17207 that denote descendant nodes and parent node, as well as varied
17208 semantic information. To study this example in more detail, you might want to
17209 look at the body of the PN procedure in the stated file.
17211 @node Using the Next Command in a Function
17212 @section Using the Next Command in a Function
17215 When you use the @code{next} command in a function, the current source
17216 location will advance to the next statement as usual. A special case
17217 arises in the case of a @code{return} statement.
17219 Part of the code for a return statement is the "epilog" of the function.
17220 This is the code that returns to the caller. There is only one copy of
17221 this epilog code, and it is typically associated with the last return
17222 statement in the function if there is more than one return. In some
17223 implementations, this epilog is associated with the first statement
17226 The result is that if you use the @code{next} command from a return
17227 statement that is not the last return statement of the function you
17228 may see a strange apparent jump to the last return statement or to
17229 the start of the function. You should simply ignore this odd jump.
17230 The value returned is always that from the first return statement
17231 that was stepped through.
17233 @node Ada Exceptions
17234 @section Breaking on Ada Exceptions
17238 You can set breakpoints that trip when your program raises
17239 selected exceptions.
17242 @item break exception
17243 Set a breakpoint that trips whenever (any task in the) program raises
17246 @item break exception @var{name}
17247 Set a breakpoint that trips whenever (any task in the) program raises
17248 the exception @var{name}.
17250 @item break exception unhandled
17251 Set a breakpoint that trips whenever (any task in the) program raises an
17252 exception for which there is no handler.
17254 @item info exceptions
17255 @itemx info exceptions @var{regexp}
17256 The @code{info exceptions} command permits the user to examine all defined
17257 exceptions within Ada programs. With a regular expression, @var{regexp}, as
17258 argument, prints out only those exceptions whose name matches @var{regexp}.
17266 @code{GDB} allows the following task-related commands:
17270 This command shows a list of current Ada tasks, as in the following example:
17277 ID TID P-ID Thread Pri State Name
17278 1 8088000 0 807e000 15 Child Activation Wait main_task
17279 2 80a4000 1 80ae000 15 Accept/Select Wait b
17280 3 809a800 1 80a4800 15 Child Activation Wait a
17281 * 4 80ae800 3 80b8000 15 Running c
17285 In this listing, the asterisk before the first task indicates it to be the
17286 currently running task. The first column lists the task ID that is used
17287 to refer to tasks in the following commands.
17289 @item break @var{linespec} task @var{taskid}
17290 @itemx break @var{linespec} task @var{taskid} if @dots{}
17291 @cindex Breakpoints and tasks
17292 These commands are like the @code{break @dots{} thread @dots{}}.
17293 @var{linespec} specifies source lines.
17295 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
17296 to specify that you only want @code{GDB} to stop the program when a
17297 particular Ada task reaches this breakpoint. @var{taskid} is one of the
17298 numeric task identifiers assigned by @code{GDB}, shown in the first
17299 column of the @samp{info tasks} display.
17301 If you do not specify @samp{task @var{taskid}} when you set a
17302 breakpoint, the breakpoint applies to @emph{all} tasks of your
17305 You can use the @code{task} qualifier on conditional breakpoints as
17306 well; in this case, place @samp{task @var{taskid}} before the
17307 breakpoint condition (before the @code{if}).
17309 @item task @var{taskno}
17310 @cindex Task switching
17312 This command allows to switch to the task referred by @var{taskno}. In
17313 particular, This allows to browse the backtrace of the specified
17314 task. It is advised to switch back to the original task before
17315 continuing execution otherwise the scheduling of the program may be
17320 For more detailed information on the tasking support, see @cite{Debugging with GDB}.
17322 @node Debugging Generic Units
17323 @section Debugging Generic Units
17324 @cindex Debugging Generic Units
17328 GNAT always uses code expansion for generic instantiation. This means that
17329 each time an instantiation occurs, a complete copy of the original code is
17330 made, with appropriate substitutions of formals by actuals.
17332 It is not possible to refer to the original generic entities in
17333 @code{GDB}, but it is always possible to debug a particular instance of
17334 a generic, by using the appropriate expanded names. For example, if we have
17339 @b{procedure} g @b{is}
17341 @b{generic package} k @b{is}
17342 @b{procedure} kp (v1 : @b{in out} integer);
17345 @b{package body} k @b{is}
17346 @b{procedure} kp (v1 : @b{in out} integer) @b{is}
17352 @b{package} k1 @b{is new} k;
17353 @b{package} k2 @b{is new} k;
17355 var : integer := 1;
17368 Then to break on a call to procedure kp in the k2 instance, simply
17372 (gdb) break g.k2.kp
17376 When the breakpoint occurs, you can step through the code of the
17377 instance in the normal manner and examine the values of local variables, as for
17380 @node GNAT Abnormal Termination or Failure to Terminate
17381 @section GNAT Abnormal Termination or Failure to Terminate
17382 @cindex GNAT Abnormal Termination or Failure to Terminate
17385 When presented with programs that contain serious errors in syntax
17387 GNAT may on rare occasions experience problems in operation, such
17389 segmentation fault or illegal memory access, raising an internal
17390 exception, terminating abnormally, or failing to terminate at all.
17391 In such cases, you can activate
17392 various features of GNAT that can help you pinpoint the construct in your
17393 program that is the likely source of the problem.
17395 The following strategies are presented in increasing order of
17396 difficulty, corresponding to your experience in using GNAT and your
17397 familiarity with compiler internals.
17401 Run @code{gcc} with the @option{-gnatf}. This first
17402 switch causes all errors on a given line to be reported. In its absence,
17403 only the first error on a line is displayed.
17405 The @option{-gnatdO} switch causes errors to be displayed as soon as they
17406 are encountered, rather than after compilation is terminated. If GNAT
17407 terminates prematurely or goes into an infinite loop, the last error
17408 message displayed may help to pinpoint the culprit.
17411 Run @code{gcc} with the @code{^-v (verbose)^/VERBOSE^} switch. In this mode,
17412 @code{gcc} produces ongoing information about the progress of the
17413 compilation and provides the name of each procedure as code is
17414 generated. This switch allows you to find which Ada procedure was being
17415 compiled when it encountered a code generation problem.
17418 @cindex @option{-gnatdc} switch
17419 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
17420 switch that does for the front-end what @code{^-v^VERBOSE^} does for the back end.
17421 The system prints the name of each unit, either a compilation unit or
17422 nested unit, as it is being analyzed.
17424 Finally, you can start
17425 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
17426 front-end of GNAT, and can be run independently (normally it is just
17427 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
17428 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
17429 @code{where} command is the first line of attack; the variable
17430 @code{lineno} (seen by @code{print lineno}), used by the second phase of
17431 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
17432 which the execution stopped, and @code{input_file name} indicates the name of
17436 @node Naming Conventions for GNAT Source Files
17437 @section Naming Conventions for GNAT Source Files
17440 In order to examine the workings of the GNAT system, the following
17441 brief description of its organization may be helpful:
17445 Files with prefix @file{^sc^SC^} contain the lexical scanner.
17448 All files prefixed with @file{^par^PAR^} are components of the parser. The
17449 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
17450 parsing of select statements can be found in @file{par-ch9.adb}.
17453 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
17454 numbers correspond to chapters of the Ada standard. For example, all
17455 issues involving context clauses can be found in @file{sem_ch10.adb}. In
17456 addition, some features of the language require sufficient special processing
17457 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
17458 dynamic dispatching, etc.
17461 All files prefixed with @file{^exp^EXP^} perform normalization and
17462 expansion of the intermediate representation (abstract syntax tree, or AST).
17463 these files use the same numbering scheme as the parser and semantics files.
17464 For example, the construction of record initialization procedures is done in
17465 @file{exp_ch3.adb}.
17468 The files prefixed with @file{^bind^BIND^} implement the binder, which
17469 verifies the consistency of the compilation, determines an order of
17470 elaboration, and generates the bind file.
17473 The files @file{atree.ads} and @file{atree.adb} detail the low-level
17474 data structures used by the front-end.
17477 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
17478 the abstract syntax tree as produced by the parser.
17481 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
17482 all entities, computed during semantic analysis.
17485 Library management issues are dealt with in files with prefix
17491 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
17492 defined in Annex A.
17497 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
17498 defined in Annex B.
17502 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
17503 both language-defined children and GNAT run-time routines.
17507 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
17508 general-purpose packages, fully documented in their specifications. All
17509 the other @file{.c} files are modifications of common @code{gcc} files.
17512 @node Getting Internal Debugging Information
17513 @section Getting Internal Debugging Information
17516 Most compilers have internal debugging switches and modes. GNAT
17517 does also, except GNAT internal debugging switches and modes are not
17518 secret. A summary and full description of all the compiler and binder
17519 debug flags are in the file @file{debug.adb}. You must obtain the
17520 sources of the compiler to see the full detailed effects of these flags.
17522 The switches that print the source of the program (reconstructed from
17523 the internal tree) are of general interest for user programs, as are the
17525 the full internal tree, and the entity table (the symbol table
17526 information). The reconstructed source provides a readable version of the
17527 program after the front-end has completed analysis and expansion, and is useful
17528 when studying the performance of specific constructs. For example, constraint
17529 checks are indicated, complex aggregates are replaced with loops and
17530 assignments, and tasking primitives are replaced with run-time calls.
17532 @node Stack Traceback
17533 @section Stack Traceback
17535 @cindex stack traceback
17536 @cindex stack unwinding
17539 Traceback is a mechanism to display the sequence of subprogram calls that
17540 leads to a specified execution point in a program. Often (but not always)
17541 the execution point is an instruction at which an exception has been raised.
17542 This mechanism is also known as @i{stack unwinding} because it obtains
17543 its information by scanning the run-time stack and recovering the activation
17544 records of all active subprograms. Stack unwinding is one of the most
17545 important tools for program debugging.
17548 The first entry stored in traceback corresponds to the deepest calling level,
17549 that is to say the subprogram currently executing the instruction
17550 from which we want to obtain the traceback.
17553 Note that there is no runtime performance penalty when stack traceback
17554 is enabled and no exception are raised during program execution.
17557 * Non-Symbolic Traceback::
17558 * Symbolic Traceback::
17561 @node Non-Symbolic Traceback
17562 @subsection Non-Symbolic Traceback
17563 @cindex traceback, non-symbolic
17566 Note: this feature is not supported on all platforms. See
17567 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
17571 * Tracebacks From an Unhandled Exception::
17572 * Tracebacks From Exception Occurrences (non-symbolic)::
17573 * Tracebacks From Anywhere in a Program (non-symbolic)::
17576 @node Tracebacks From an Unhandled Exception
17577 @subsubsection Tracebacks From an Unhandled Exception
17580 A runtime non-symbolic traceback is a list of addresses of call instructions.
17581 To enable this feature you must use the @code{-E}
17582 @code{gnatbind}'s option. With this option a stack traceback is stored as part
17583 of exception information. It is possible to retrieve this information using the
17584 standard @code{Ada.Exception.Exception_Information} routine.
17587 Let's have a look at a simple example:
17596 raise Constraint_Error;
17612 $ gnatmake stb -bargs -E
17615 Execution terminated by unhandled exception
17616 Exception name: CONSTRAINT_ERROR
17618 Call stack traceback locations:
17619 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
17623 As we see the traceback lists a sequence of addresses for the unhandled
17624 exception @code{CONSTAINT_ERROR} raised in procedure P1. It is easy to
17625 guess that this exception come from procedure P1. To translate these
17626 addresses into the source lines where the calls appear, the
17627 @code{addr2line} tool, described below, is invaluable. The use of this tool
17628 requires the program to be compiled with debug information.
17631 $ gnatmake -g stb -bargs -E
17634 Execution terminated by unhandled exception
17635 Exception name: CONSTRAINT_ERROR
17637 Call stack traceback locations:
17638 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
17640 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
17641 0x4011f1 0x77e892a4
17643 00401373 at d:/stb/stb.adb:5
17644 0040138B at d:/stb/stb.adb:10
17645 0040139C at d:/stb/stb.adb:14
17646 00401335 at d:/stb/b~stb.adb:104
17647 004011C4 at /build/.../crt1.c:200
17648 004011F1 at /build/.../crt1.c:222
17649 77E892A4 in ?? at ??:0
17653 @code{addr2line} has a number of other useful options:
17657 to get the function name corresponding to any location
17659 @item --demangle=gnat
17660 to use the @b{gnat} decoding mode for the function names. Note that
17661 for binutils version 2.9.x the option is simply @code{--demangle}.
17665 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
17666 0x40139c 0x401335 0x4011c4 0x4011f1
17668 00401373 in stb.p1 at d:/stb/stb.adb:5
17669 0040138B in stb.p2 at d:/stb/stb.adb:10
17670 0040139C in stb at d:/stb/stb.adb:14
17671 00401335 in main at d:/stb/b~stb.adb:104
17672 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
17673 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
17677 From this traceback we can see that the exception was raised in
17678 @file{stb.adb} at line 5, which was reached from a procedure call in
17679 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
17680 which contains the call to the main program.
17681 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
17682 and the output will vary from platform to platform.
17685 It is also possible to use @code{GDB} with these traceback addresses to debug
17686 the program. For example, we can break at a given code location, as reported
17687 in the stack traceback:
17693 Furthermore, this feature is not implemented inside Windows DLL. Only
17694 the non-symbolic traceback is reported in this case.
17697 (gdb) break *0x401373
17698 Breakpoint 1 at 0x401373: file stb.adb, line 5.
17702 It is important to note that the stack traceback addresses
17703 do not change when debug information is included. This is particularly useful
17704 because it makes it possible to release software without debug information (to
17705 minimize object size), get a field report that includes a stack traceback
17706 whenever an internal bug occurs, and then be able to retrieve the sequence
17707 of calls with the same program compiled with debug information.
17709 @node Tracebacks From Exception Occurrences (non-symbolic)
17710 @subsubsection Tracebacks From Exception Occurrences
17713 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
17714 The stack traceback is attached to the exception information string, and can
17715 be retrieved in an exception handler within the Ada program, by means of the
17716 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
17722 with Ada.Exceptions;
17727 use Ada.Exceptions;
17735 Text_IO.Put_Line (Exception_Information (E));
17751 This program will output:
17756 Exception name: CONSTRAINT_ERROR
17757 Message: stb.adb:12
17758 Call stack traceback locations:
17759 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
17762 @node Tracebacks From Anywhere in a Program (non-symbolic)
17763 @subsubsection Tracebacks From Anywhere in a Program
17766 It is also possible to retrieve a stack traceback from anywhere in a
17767 program. For this you need to
17768 use the @code{GNAT.Traceback} API. This package includes a procedure called
17769 @code{Call_Chain} that computes a complete stack traceback, as well as useful
17770 display procedures described below. It is not necessary to use the
17771 @code{-E gnatbind} option in this case, because the stack traceback mechanism
17772 is invoked explicitly.
17775 In the following example we compute a traceback at a specific location in
17776 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
17777 convert addresses to strings:
17783 with GNAT.Traceback;
17784 with GNAT.Debug_Utilities;
17790 use GNAT.Traceback;
17793 TB : Tracebacks_Array (1 .. 10);
17794 -- We are asking for a maximum of 10 stack frames.
17796 -- Len will receive the actual number of stack frames returned.
17798 Call_Chain (TB, Len);
17800 Text_IO.Put ("In STB.P1 : ");
17802 for K in 1 .. Len loop
17803 Text_IO.Put (Debug_Utilities.Image (TB (K)));
17826 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
17827 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
17830 @node Symbolic Traceback
17831 @subsection Symbolic Traceback
17832 @cindex traceback, symbolic
17835 A symbolic traceback is a stack traceback in which procedure names are
17836 associated with each code location.
17839 Note that this feature is not supported on all platforms. See
17840 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
17841 list of currently supported platforms.
17844 Note that the symbolic traceback requires that the program be compiled
17845 with debug information. If it is not compiled with debug information
17846 only the non-symbolic information will be valid.
17849 * Tracebacks From Exception Occurrences (symbolic)::
17850 * Tracebacks From Anywhere in a Program (symbolic)::
17853 @node Tracebacks From Exception Occurrences (symbolic)
17854 @subsubsection Tracebacks From Exception Occurrences
17860 with GNAT.Traceback.Symbolic;
17866 raise Constraint_Error;
17883 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
17890 $ gnatmake -g stb -bargs -E -largs -lgnat -laddr2line -lintl
17893 0040149F in stb.p1 at stb.adb:8
17894 004014B7 in stb.p2 at stb.adb:13
17895 004014CF in stb.p3 at stb.adb:18
17896 004015DD in ada.stb at stb.adb:22
17897 00401461 in main at b~stb.adb:168
17898 004011C4 in __mingw_CRTStartup at crt1.c:200
17899 004011F1 in mainCRTStartup at crt1.c:222
17900 77E892A4 in ?? at ??:0
17904 The exact sequence of linker options may vary from platform to platform.
17905 The above @code{-largs} section is for Windows platforms. By contrast,
17906 under Unix there is no need for the @code{-largs} section.
17907 Differences across platforms are due to details of linker implementation.
17909 @node Tracebacks From Anywhere in a Program (symbolic)
17910 @subsubsection Tracebacks From Anywhere in a Program
17913 It is possible to get a symbolic stack traceback
17914 from anywhere in a program, just as for non-symbolic tracebacks.
17915 The first step is to obtain a non-symbolic
17916 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
17917 information. Here is an example:
17923 with GNAT.Traceback;
17924 with GNAT.Traceback.Symbolic;
17929 use GNAT.Traceback;
17930 use GNAT.Traceback.Symbolic;
17933 TB : Tracebacks_Array (1 .. 10);
17934 -- We are asking for a maximum of 10 stack frames.
17936 -- Len will receive the actual number of stack frames returned.
17938 Call_Chain (TB, Len);
17939 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
17955 @node Compatibility with DEC Ada
17956 @chapter Compatibility with DEC Ada
17957 @cindex Compatibility
17960 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
17961 OpenVMS Alpha. GNAT achieves a high level of compatibility
17962 with DEC Ada, and it should generally be straightforward to port code
17963 from the DEC Ada environment to GNAT. However, there are a few language
17964 and implementation differences of which the user must be aware. These
17965 differences are discussed in this section. In
17966 addition, the operating environment and command structure for the
17967 compiler are different, and these differences are also discussed.
17969 Note that this discussion addresses specifically the implementation
17970 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
17971 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems, GNAT
17972 always follows the Alpha implementation.
17975 * Ada 95 Compatibility::
17976 * Differences in the Definition of Package System::
17977 * Language-Related Features::
17978 * The Package STANDARD::
17979 * The Package SYSTEM::
17980 * Tasking and Task-Related Features::
17981 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
17982 * Pragmas and Pragma-Related Features::
17983 * Library of Predefined Units::
17985 * Main Program Definition::
17986 * Implementation-Defined Attributes::
17987 * Compiler and Run-Time Interfacing::
17988 * Program Compilation and Library Management::
17990 * Implementation Limits::
17994 @node Ada 95 Compatibility
17995 @section Ada 95 Compatibility
17998 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
17999 compiler. Ada 95 is almost completely upwards compatible
18000 with Ada 83, and therefore Ada 83 programs will compile
18001 and run under GNAT with
18002 no changes or only minor changes. The Ada 95 Reference
18003 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
18006 GNAT provides the switch /83 on the GNAT COMPILE command,
18007 as well as the pragma ADA_83, to force the compiler to
18008 operate in Ada 83 mode. This mode does not guarantee complete
18009 conformance to Ada 83, but in practice is sufficient to
18010 eliminate most sources of incompatibilities.
18011 In particular, it eliminates the recognition of the
18012 additional Ada 95 keywords, so that their use as identifiers
18013 in Ada83 program is legal, and handles the cases of packages
18014 with optional bodies, and generics that instantiate unconstrained
18015 types without the use of @code{(<>)}.
18017 @node Differences in the Definition of Package System
18018 @section Differences in the Definition of Package System
18021 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
18022 implementation-dependent declarations to package System. In normal mode,
18023 GNAT does not take advantage of this permission, and the version of System
18024 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
18026 However, DEC Ada adds an extensive set of declarations to package System,
18027 as fully documented in the DEC Ada manuals. To minimize changes required
18028 for programs that make use of these extensions, GNAT provides the pragma
18029 Extend_System for extending the definition of package System. By using:
18034 @b{pragma} Extend_System (Aux_DEC);
18040 The set of definitions in System is extended to include those in package
18041 @code{System.Aux_DEC}.
18042 These definitions are incorporated directly into package
18043 System, as though they had been declared there in the first place. For a
18044 list of the declarations added, see the specification of this package,
18045 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
18046 The pragma Extend_System is a configuration pragma, which means that
18047 it can be placed in the file @file{gnat.adc}, so that it will automatically
18048 apply to all subsequent compilations. See the section on Configuration
18049 Pragmas for further details.
18051 An alternative approach that avoids the use of the non-standard
18052 Extend_System pragma is to add a context clause to the unit that
18053 references these facilities:
18058 @b{with} System.Aux_DEC;
18059 @b{use} System.Aux_DEC;
18065 The effect is not quite semantically identical to incorporating the declarations
18066 directly into package @code{System},
18067 but most programs will not notice a difference
18068 unless they use prefix notation (e.g. @code{System.Integer_8})
18070 entities directly in package @code{System}.
18071 For units containing such references,
18072 the prefixes must either be removed, or the pragma @code{Extend_System}
18075 @node Language-Related Features
18076 @section Language-Related Features
18079 The following sections highlight differences in types,
18080 representations of types, operations, alignment, and
18084 * Integer Types and Representations::
18085 * Floating-Point Types and Representations::
18086 * Pragmas Float_Representation and Long_Float::
18087 * Fixed-Point Types and Representations::
18088 * Record and Array Component Alignment::
18089 * Address Clauses::
18090 * Other Representation Clauses::
18093 @node Integer Types and Representations
18094 @subsection Integer Types and Representations
18097 The set of predefined integer types is identical in DEC Ada and GNAT.
18098 Furthermore the representation of these integer types is also identical,
18099 including the capability of size clauses forcing biased representation.
18102 DEC Ada for OpenVMS Alpha systems has defined the
18103 following additional integer types in package System:
18124 When using GNAT, the first four of these types may be obtained from the
18125 standard Ada 95 package @code{Interfaces}.
18126 Alternatively, by use of the pragma
18127 @code{Extend_System}, identical
18128 declarations can be referenced directly in package @code{System}.
18129 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
18131 @node Floating-Point Types and Representations
18132 @subsection Floating-Point Types and Representations
18133 @cindex Floating-Point types
18136 The set of predefined floating-point types is identical in DEC Ada and GNAT.
18137 Furthermore the representation of these floating-point
18138 types is also identical. One important difference is that the default
18139 representation for DEC Ada is VAX_Float, but the default representation
18142 Specific types may be declared to be VAX_Float or IEEE, using the pragma
18143 @code{Float_Representation} as described in the DEC Ada documentation.
18144 For example, the declarations:
18149 @b{type} F_Float @b{is digits} 6;
18150 @b{pragma} Float_Representation (VAX_Float, F_Float);
18156 declare a type F_Float that will be represented in VAX_Float format.
18157 This set of declarations actually appears in System.Aux_DEC, which provides
18158 the full set of additional floating-point declarations provided in
18159 the DEC Ada version of package
18160 System. This and similar declarations may be accessed in a user program by using
18161 pragma @code{Extend_System}. The use of this
18162 pragma, and the related pragma @code{Long_Float} is described in further
18163 detail in the following section.
18165 @node Pragmas Float_Representation and Long_Float
18166 @subsection Pragmas Float_Representation and Long_Float
18169 DEC Ada provides the pragma @code{Float_Representation}, which
18170 acts as a program library switch to allow control over
18171 the internal representation chosen for the predefined
18172 floating-point types declared in the package @code{Standard}.
18173 The format of this pragma is as follows:
18178 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
18184 This pragma controls the representation of floating-point
18189 @code{VAX_Float} specifies that floating-point
18190 types are represented by default with the VAX hardware types
18191 F-floating, D-floating, G-floating. Note that the H-floating
18192 type is available only on DIGITAL Vax systems, and is not available
18193 in either DEC Ada or GNAT for Alpha systems.
18196 @code{IEEE_Float} specifies that floating-point
18197 types are represented by default with the IEEE single and
18198 double floating-point types.
18202 GNAT provides an identical implementation of the pragma
18203 @code{Float_Representation}, except that it functions as a
18204 configuration pragma, as defined by Ada 95. Note that the
18205 notion of configuration pragma corresponds closely to the
18206 DEC Ada notion of a program library switch.
18208 When no pragma is used in GNAT, the default is IEEE_Float, which is different
18209 from DEC Ada 83, where the default is VAX_Float. In addition, the
18210 predefined libraries in GNAT are built using IEEE_Float, so it is not
18211 advisable to change the format of numbers passed to standard library
18212 routines, and if necessary explicit type conversions may be needed.
18214 The use of IEEE_Float is recommended in GNAT since it is more efficient,
18215 and (given that it conforms to an international standard) potentially more
18216 portable. The situation in which VAX_Float may be useful is in interfacing
18217 to existing code and data that expects the use of VAX_Float. There are
18218 two possibilities here. If the requirement for the use of VAX_Float is
18219 localized, then the best approach is to use the predefined VAX_Float
18220 types in package @code{System}, as extended by
18221 @code{Extend_System}. For example, use @code{System.F_Float}
18222 to specify the 32-bit @code{F-Float} format.
18224 Alternatively, if an entire program depends heavily on the use of
18225 the @code{VAX_Float} and in particular assumes that the types in
18226 package @code{Standard} are in @code{Vax_Float} format, then it
18227 may be desirable to reconfigure GNAT to assume Vax_Float by default.
18228 This is done by using the GNAT LIBRARY command to rebuild the library, and
18229 then using the general form of the @code{Float_Representation}
18230 pragma to ensure that this default format is used throughout.
18231 The form of the GNAT LIBRARY command is:
18234 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
18238 where @i{file} contains the new configuration pragmas
18239 and @i{directory} is the directory to be created to contain
18243 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
18244 to allow control over the internal representation chosen
18245 for the predefined type @code{Long_Float} and for floating-point
18246 type declarations with digits specified in the range 7 .. 15.
18247 The format of this pragma is as follows:
18251 @b{pragma} Long_Float (D_FLOAT | G_FLOAT);
18255 @node Fixed-Point Types and Representations
18256 @subsection Fixed-Point Types and Representations
18259 On DEC Ada for OpenVMS Alpha systems, rounding is
18260 away from zero for both positive and negative numbers.
18261 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
18263 On GNAT for OpenVMS Alpha, the results of operations
18264 on fixed-point types are in accordance with the Ada 95
18265 rules. In particular, results of operations on decimal
18266 fixed-point types are truncated.
18268 @node Record and Array Component Alignment
18269 @subsection Record and Array Component Alignment
18272 On DEC Ada for OpenVMS Alpha, all non composite components
18273 are aligned on natural boundaries. For example, 1-byte
18274 components are aligned on byte boundaries, 2-byte
18275 components on 2-byte boundaries, 4-byte components on 4-byte
18276 byte boundaries, and so on. The OpenVMS Alpha hardware
18277 runs more efficiently with naturally aligned data.
18279 ON GNAT for OpenVMS Alpha, alignment rules are compatible
18280 with DEC Ada for OpenVMS Alpha.
18282 @node Address Clauses
18283 @subsection Address Clauses
18286 In DEC Ada and GNAT, address clauses are supported for
18287 objects and imported subprograms.
18288 The predefined type @code{System.Address} is a private type
18289 in both compilers, with the same representation (it is simply
18290 a machine pointer). Addition, subtraction, and comparison
18291 operations are available in the standard Ada 95 package
18292 @code{System.Storage_Elements}, or in package @code{System}
18293 if it is extended to include @code{System.Aux_DEC} using a
18294 pragma @code{Extend_System} as previously described.
18296 Note that code that with's both this extended package @code{System}
18297 and the package @code{System.Storage_Elements} should not @code{use}
18298 both packages, or ambiguities will result. In general it is better
18299 not to mix these two sets of facilities. The Ada 95 package was
18300 designed specifically to provide the kind of features that DEC Ada
18301 adds directly to package @code{System}.
18303 GNAT is compatible with DEC Ada in its handling of address
18304 clauses, except for some limitations in
18305 the form of address clauses for composite objects with
18306 initialization. Such address clauses are easily replaced
18307 by the use of an explicitly-defined constant as described
18308 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
18314 X, Y : Integer := Init_Func;
18315 Q : String (X .. Y) := "abc";
18317 @b{for} Q'Address @b{use} Compute_Address;
18323 will be rejected by GNAT, since the address cannot be computed at the time
18324 that Q is declared. To achieve the intended effect, write instead:
18329 X, Y : Integer := Init_Func;
18330 Q_Address : @b{constant} Address := Compute_Address;
18331 Q : String (X .. Y) := "abc";
18333 @b{for} Q'Address @b{use} Q_Address;
18339 which will be accepted by GNAT (and other Ada 95 compilers), and is also
18340 backwards compatible with Ada 83. A fuller description of the restrictions
18341 on address specifications is found in the GNAT Reference Manual.
18343 @node Other Representation Clauses
18344 @subsection Other Representation Clauses
18347 GNAT supports in a compatible manner all the representation
18348 clauses supported by DEC Ada. In addition, it
18349 supports representation clause forms that are new in Ada 95
18350 including COMPONENT_SIZE and SIZE clauses for objects.
18352 @node The Package STANDARD
18353 @section The Package STANDARD
18356 The package STANDARD, as implemented by DEC Ada, is fully
18357 described in the Reference Manual for the Ada Programming
18358 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
18359 Language Reference Manual. As implemented by GNAT, the
18360 package STANDARD is described in the Ada 95 Reference
18363 In addition, DEC Ada supports the Latin-1 character set in
18364 the type CHARACTER. GNAT supports the Latin-1 character set
18365 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
18366 the type WIDE_CHARACTER.
18368 The floating-point types supported by GNAT are those
18369 supported by DEC Ada, but defaults are different, and are controlled by
18370 pragmas. See @pxref{Floating-Point Types and Representations} for details.
18372 @node The Package SYSTEM
18373 @section The Package SYSTEM
18376 DEC Ada provides a system-specific version of the package
18377 SYSTEM for each platform on which the language ships.
18378 For the complete specification of the package SYSTEM, see
18379 Appendix F of the DEC Ada Language Reference Manual.
18381 On DEC Ada, the package SYSTEM includes the following conversion functions:
18383 @item TO_ADDRESS(INTEGER)
18385 @item TO_ADDRESS(UNSIGNED_LONGWORD)
18387 @item TO_ADDRESS(universal_integer)
18389 @item TO_INTEGER(ADDRESS)
18391 @item TO_UNSIGNED_LONGWORD(ADDRESS)
18393 @item Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
18394 functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
18398 By default, GNAT supplies a version of SYSTEM that matches
18399 the definition given in the Ada 95 Reference Manual.
18401 is a subset of the DIGITAL system definitions, which is as
18402 close as possible to the original definitions. The only difference
18403 is that the definition of SYSTEM_NAME is different:
18408 @b{type} Name @b{is} (SYSTEM_NAME_GNAT);
18409 System_Name : @b{constant} Name := SYSTEM_NAME_GNAT;
18415 Also, GNAT adds the new Ada 95 declarations for
18416 BIT_ORDER and DEFAULT_BIT_ORDER.
18418 However, the use of the following pragma causes GNAT
18419 to extend the definition of package SYSTEM so that it
18420 encompasses the full set of DIGITAL-specific extensions,
18421 including the functions listed above:
18425 @b{pragma} Extend_System (Aux_DEC);
18430 The pragma Extend_System is a configuration pragma that
18431 is most conveniently placed in the @file{gnat.adc} file. See the
18432 GNAT Reference Manual for further details.
18434 DEC Ada does not allow the recompilation of the package
18435 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
18436 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
18437 the package SYSTEM. On OpenVMS Alpha systems, the pragma
18438 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
18439 its single argument.
18441 GNAT does permit the recompilation of package SYSTEM using
18442 a special switch (-gnatg) and this switch can be used if
18443 it is necessary to change constants in SYSTEM. GNAT does
18444 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
18445 or MEMORY_SIZE by any other means.
18447 On GNAT systems, the pragma SYSTEM_NAME takes the
18448 enumeration literal SYSTEM_NAME_GNAT.
18450 The definitions provided by the use of
18453 pragma Extend_System (AUX_Dec);
18457 are virtually identical to those provided by the DEC Ada 83 package
18458 System. One important difference is that the name of the TO_ADDRESS
18459 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
18460 See the GNAT Reference manual for a discussion of why this change was
18464 The version of TO_ADDRESS taking a universal integer argument is in fact
18465 an extension to Ada 83 not strictly compatible with the reference manual.
18466 In GNAT, we are constrained to be exactly compatible with the standard,
18467 and this means we cannot provide this capability. In DEC Ada 83, the
18468 point of this definition is to deal with a call like:
18471 TO_ADDRESS (16#12777#);
18475 Normally, according to the Ada 83 standard, one would expect this to be
18476 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
18477 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
18478 definition using universal_integer takes precedence.
18480 In GNAT, since the version with universal_integer cannot be supplied, it is
18481 not possible to be 100% compatible. Since there are many programs using
18482 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
18483 to change the name of the function in the UNSIGNED_LONGWORD case, so the
18484 declarations provided in the GNAT version of AUX_Dec are:
18487 function To_Address (X : Integer) return Address;
18488 pragma Pure_Function (To_Address);
18490 function To_Address_Long (X : Unsigned_Longword) return Address;
18491 pragma Pure_Function (To_Address_Long);
18495 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
18496 change the name to TO_ADDRESS_LONG.
18498 @node Tasking and Task-Related Features
18499 @section Tasking and Task-Related Features
18502 The concepts relevant to a comparison of tasking on GNAT
18503 and on DEC Ada for OpenVMS Alpha systems are discussed in
18504 the following sections.
18506 For detailed information on concepts related to tasking in
18507 DEC Ada, see the DEC Ada Language Reference Manual and the
18508 relevant run-time reference manual.
18510 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
18511 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
18514 On OpenVMS Alpha systems, each Ada task (except a passive
18515 task) is implemented as a single stream of execution
18516 that is created and managed by the kernel. On these
18517 systems, DEC Ada tasking support is based on DECthreads,
18518 an implementation of the POSIX standard for threads.
18520 Although tasks are implemented as threads, all tasks in
18521 an Ada program are part of the same process. As a result,
18522 resources such as open files and virtual memory can be
18523 shared easily among tasks. Having all tasks in one process
18524 allows better integration with the programming environment
18525 (the shell and the debugger, for example).
18527 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
18528 code that calls DECthreads routines can be used together.
18529 The interaction between Ada tasks and DECthreads routines
18530 can have some benefits. For example when on OpenVMS Alpha,
18531 DEC Ada can call C code that is already threaded.
18532 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
18533 and Ada tasks are mapped to threads.
18536 * Assigning Task IDs::
18537 * Task IDs and Delays::
18538 * Task-Related Pragmas::
18539 * Scheduling and Task Priority::
18541 * External Interrupts::
18544 @node Assigning Task IDs
18545 @subsection Assigning Task IDs
18548 The DEC Ada Run-Time Library always assigns %TASK 1 to
18549 the environment task that executes the main program. On
18550 OpenVMS Alpha systems, %TASK 0 is often used for tasks
18551 that have been created but are not yet activated.
18553 On OpenVMS Alpha systems, task IDs are assigned at
18554 activation. On GNAT systems, task IDs are also assigned at
18555 task creation but do not have the same form or values as
18556 task ID values in DEC Ada. There is no null task, and the
18557 environment task does not have a specific task ID value.
18559 @node Task IDs and Delays
18560 @subsection Task IDs and Delays
18563 On OpenVMS Alpha systems, tasking delays are implemented
18564 using Timer System Services. The Task ID is used for the
18565 identification of the timer request (the REQIDT parameter).
18566 If Timers are used in the application take care not to use
18567 0 for the identification, because cancelling such a timer
18568 will cancel all timers and may lead to unpredictable results.
18570 @node Task-Related Pragmas
18571 @subsection Task-Related Pragmas
18574 Ada supplies the pragma TASK_STORAGE, which allows
18575 specification of the size of the guard area for a task
18576 stack. (The guard area forms an area of memory that has no
18577 read or write access and thus helps in the detection of
18578 stack overflow.) On OpenVMS Alpha systems, if the pragma
18579 TASK_STORAGE specifies a value of zero, a minimal guard
18580 area is created. In the absence of a pragma TASK_STORAGE, a default guard
18583 GNAT supplies the following task-related pragmas:
18588 This pragma appears within a task definition and
18589 applies to the task in which it appears. The argument
18590 must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
18594 GNAT implements pragma TASK_STORAGE in the same way as
18596 Both DEC Ada and GNAT supply the pragmas PASSIVE,
18597 SUPPRESS, and VOLATILE.
18599 @node Scheduling and Task Priority
18600 @subsection Scheduling and Task Priority
18603 DEC Ada implements the Ada language requirement that
18604 when two tasks are eligible for execution and they have
18605 different priorities, the lower priority task does not
18606 execute while the higher priority task is waiting. The DEC
18607 Ada Run-Time Library keeps a task running until either the
18608 task is suspended or a higher priority task becomes ready.
18610 On OpenVMS Alpha systems, the default strategy is round-
18611 robin with preemption. Tasks of equal priority take turns
18612 at the processor. A task is run for a certain period of
18613 time and then placed at the rear of the ready queue for
18614 its priority level.
18616 DEC Ada provides the implementation-defined pragma TIME_SLICE,
18617 which can be used to enable or disable round-robin
18618 scheduling of tasks with the same priority.
18619 See the relevant DEC Ada run-time reference manual for
18620 information on using the pragmas to control DEC Ada task
18623 GNAT follows the scheduling rules of Annex D (real-time
18624 Annex) of the Ada 95 Reference Manual. In general, this
18625 scheduling strategy is fully compatible with DEC Ada
18626 although it provides some additional constraints (as
18627 fully documented in Annex D).
18628 GNAT implements time slicing control in a manner compatible with
18629 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
18630 to the DEC Ada 83 pragma of the same name.
18631 Note that it is not possible to mix GNAT tasking and
18632 DEC Ada 83 tasking in the same program, since the two run times are
18635 @node The Task Stack
18636 @subsection The Task Stack
18639 In DEC Ada, a task stack is allocated each time a
18640 non passive task is activated. As soon as the task is
18641 terminated, the storage for the task stack is deallocated.
18642 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
18643 a default stack size is used. Also, regardless of the size
18644 specified, some additional space is allocated for task
18645 management purposes. On OpenVMS Alpha systems, at least
18646 one page is allocated.
18648 GNAT handles task stacks in a similar manner. According to
18649 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
18650 an alternative method for controlling the task stack size.
18651 The specification of the attribute T'STORAGE_SIZE is also
18652 supported in a manner compatible with DEC Ada.
18654 @node External Interrupts
18655 @subsection External Interrupts
18658 On DEC Ada, external interrupts can be associated with task entries.
18659 GNAT is compatible with DEC Ada in its handling of external interrupts.
18661 @node Pragmas and Pragma-Related Features
18662 @section Pragmas and Pragma-Related Features
18665 Both DEC Ada and GNAT supply all language-defined pragmas
18666 as specified by the Ada 83 standard. GNAT also supplies all
18667 language-defined pragmas specified in the Ada 95 Reference Manual.
18668 In addition, GNAT implements the implementation-defined pragmas
18674 @item COMMON_OBJECT
18676 @item COMPONENT_ALIGNMENT
18678 @item EXPORT_EXCEPTION
18680 @item EXPORT_FUNCTION
18682 @item EXPORT_OBJECT
18684 @item EXPORT_PROCEDURE
18686 @item EXPORT_VALUED_PROCEDURE
18688 @item FLOAT_REPRESENTATION
18692 @item IMPORT_EXCEPTION
18694 @item IMPORT_FUNCTION
18696 @item IMPORT_OBJECT
18698 @item IMPORT_PROCEDURE
18700 @item IMPORT_VALUED_PROCEDURE
18702 @item INLINE_GENERIC
18704 @item INTERFACE_NAME
18714 @item SHARE_GENERIC
18726 These pragmas are all fully implemented, with the exception of @code{Title},
18727 @code{Passive}, and @code{Share_Generic}, which are
18728 recognized, but which have no
18729 effect in GNAT. The effect of @code{Passive} may be obtained by the
18730 use of protected objects in Ada 95. In GNAT, all generics are inlined.
18732 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
18733 a separate subprogram specification which must appear before the
18736 GNAT also supplies a number of implementation-defined pragmas as follows:
18738 @item C_PASS_BY_COPY
18740 @item EXTEND_SYSTEM
18742 @item SOURCE_FILE_NAME
18760 @item CPP_CONSTRUCTOR
18762 @item CPP_DESTRUCTOR
18772 @item LINKER_SECTION
18774 @item MACHINE_ATTRIBUTE
18778 @item PURE_FUNCTION
18780 @item SOURCE_REFERENCE
18784 @item UNCHECKED_UNION
18786 @item UNIMPLEMENTED_UNIT
18788 @item WEAK_EXTERNAL
18792 For full details on these GNAT implementation-defined pragmas, see
18793 the GNAT Reference Manual.
18796 * Restrictions on the Pragma INLINE::
18797 * Restrictions on the Pragma INTERFACE::
18798 * Restrictions on the Pragma SYSTEM_NAME::
18801 @node Restrictions on the Pragma INLINE
18802 @subsection Restrictions on the Pragma INLINE
18805 DEC Ada applies the following restrictions to the pragma INLINE:
18807 @item Parameters cannot be a task type.
18809 @item Function results cannot be task types, unconstrained
18810 array types, or unconstrained types with discriminants.
18812 @item Bodies cannot declare the following:
18814 @item Subprogram body or stub (imported subprogram is allowed)
18818 @item Generic declarations
18820 @item Instantiations
18824 @item Access types (types derived from access types allowed)
18826 @item Array or record types
18828 @item Dependent tasks
18830 @item Direct recursive calls of subprogram or containing
18831 subprogram, directly or via a renaming
18837 In GNAT, the only restriction on pragma INLINE is that the
18838 body must occur before the call if both are in the same
18839 unit, and the size must be appropriately small. There are
18840 no other specific restrictions which cause subprograms to
18841 be incapable of being inlined.
18843 @node Restrictions on the Pragma INTERFACE
18844 @subsection Restrictions on the Pragma INTERFACE
18847 The following lists and describes the restrictions on the
18848 pragma INTERFACE on DEC Ada and GNAT:
18850 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
18851 Default is the default on OpenVMS Alpha systems.
18853 @item Parameter passing: Language specifies default
18854 mechanisms but can be overridden with an EXPORT pragma.
18857 @item Ada: Use internal Ada rules.
18859 @item Bliss, C: Parameters must be mode @code{in}; cannot be
18860 record or task type. Result cannot be a string, an
18861 array, or a record.
18863 @item Fortran: Parameters cannot be a task. Result cannot
18864 be a string, an array, or a record.
18869 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
18870 record parameters for all languages.
18872 @node Restrictions on the Pragma SYSTEM_NAME
18873 @subsection Restrictions on the Pragma SYSTEM_NAME
18876 For DEC Ada for OpenVMS Alpha, the enumeration literal
18877 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
18878 literal for the type NAME is SYSTEM_NAME_GNAT.
18880 @node Library of Predefined Units
18881 @section Library of Predefined Units
18884 A library of predefined units is provided as part of the
18885 DEC Ada and GNAT implementations. DEC Ada does not provide
18886 the package MACHINE_CODE but instead recommends importing
18889 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
18890 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
18891 version. During GNAT installation, the DEC Ada Predefined
18892 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
18893 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
18894 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
18897 The GNAT RTL is contained in
18898 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
18899 the default search path is set up to find DECLIB units in preference
18900 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
18903 However, it is possible to change the default so that the
18904 reverse is true, or even to mix them using child package
18905 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
18906 is the package name, and the Ada units are available in the
18907 standard manner defined for Ada 95, that is to say as Ada.xxx. To
18908 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
18909 appropriately. For example, to change the default to use the Ada95
18913 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
18914 GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
18915 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
18916 GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
18920 * Changes to DECLIB::
18923 @node Changes to DECLIB
18924 @subsection Changes to DECLIB
18927 The changes made to the DEC Ada predefined library for GNAT and Ada 95
18928 compatibility are minor and include the following:
18931 @item Adjusting the location of pragmas and record representation
18932 clauses to obey Ada 95 rules
18934 @item Adding the proper notation to generic formal parameters
18935 that take unconstrained types in instantiation
18937 @item Adding pragma ELABORATE_BODY to package specifications
18938 that have package bodies not otherwise allowed
18940 @item Occurrences of the identifier "PROTECTED" are renamed to "PROTECTD".
18941 Currently these are found only in the STARLET package spec.
18945 None of the above changes is visible to users.
18951 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
18954 @item Command Language Interpreter (CLI interface)
18956 @item DECtalk Run-Time Library (DTK interface)
18958 @item Librarian utility routines (LBR interface)
18960 @item General Purpose Run-Time Library (LIB interface)
18962 @item Math Run-Time Library (MTH interface)
18964 @item National Character Set Run-Time Library (NCS interface)
18966 @item Compiled Code Support Run-Time Library (OTS interface)
18968 @item Parallel Processing Run-Time Library (PPL interface)
18970 @item Screen Management Run-Time Library (SMG interface)
18972 @item Sort Run-Time Library (SOR interface)
18974 @item String Run-Time Library (STR interface)
18976 @item STARLET System Library
18979 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
18981 @item X Windows Toolkit (XT interface)
18983 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
18987 GNAT provides implementations of these DEC bindings in the DECLIB directory.
18989 The X/Motif bindings used to build DECLIB are whatever versions are in the
18990 DEC Ada ADA$PREDEFINED directory with extension .ADC. The build script will
18991 automatically add a pragma Linker_Options to packages Xm, Xt, and X_Lib
18992 causing the default X/Motif shareable image libraries to be linked in. This
18993 is done via options files named xm.opt, xt.opt, and x_lib.opt (also located
18994 in the DECLIB directory).
18996 It may be necessary to edit these options files to update or correct the
18997 library names if, for example, the newer X/Motif bindings from ADA$EXAMPLES
18998 had been (previous to installing GNAT) copied and renamed to superseded the
18999 default ADA$PREDEFINED versions.
19002 * Shared Libraries and Options Files::
19003 * Interfaces to C::
19006 @node Shared Libraries and Options Files
19007 @subsection Shared Libraries and Options Files
19010 When using the DEC Ada
19011 predefined X and Motif bindings, the linking with their shareable images is
19012 done automatically by GNAT LINK. When using other X and Motif bindings, it
19013 is necessary to add the corresponding shareable images to the command line for
19014 GNAT LINK. When linking with shared libraries, or with .OPT files, it is
19015 also necessary to add them to the command line for GNAT LINK.
19017 A shared library to be used with GNAT is built in the same way as other
19018 libraries under VMS. The VMS Link command can be used in standard fashion.
19020 @node Interfaces to C
19021 @subsection Interfaces to C
19025 provides the following Ada types and operations:
19028 @item C types package (C_TYPES)
19030 @item C strings (C_TYPES.NULL_TERMINATED)
19032 @item Other_types (SHORT_INT)
19036 Interfacing to C with GNAT, one can use the above approach
19037 described for DEC Ada or the facilities of Annex B of
19038 the Ada 95 Reference Manual (packages INTERFACES.C,
19039 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
19040 information, see the section "Interfacing to C" in the
19041 GNAT Reference Manual.
19043 The @option{-gnatF} qualifier forces default and explicit
19044 @code{External_Name} parameters in pragmas Import and Export
19045 to be uppercased for compatibility with the default behavior
19046 of DEC C. The qualifier has no effect on @code{Link_Name} parameters.
19048 @node Main Program Definition
19049 @section Main Program Definition
19052 The following section discusses differences in the
19053 definition of main programs on DEC Ada and GNAT.
19054 On DEC Ada, main programs are defined to meet the
19055 following conditions:
19057 @item Procedure with no formal parameters (returns 0 upon
19060 @item Procedure with no formal parameters (returns 42 when
19061 unhandled exceptions are raised)
19063 @item Function with no formal parameters whose returned value
19064 is of a discrete type
19066 @item Procedure with one OUT formal of a discrete type for
19067 which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
19072 When declared with the pragma EXPORT_VALUED_PROCEDURE,
19073 a main function or main procedure returns a discrete
19074 value whose size is less than 64 bits (32 on VAX systems),
19075 the value is zero- or sign-extended as appropriate.
19076 On GNAT, main programs are defined as follows:
19078 @item Must be a non-generic, parameter-less subprogram that
19079 is either a procedure or function returning an Ada
19080 STANDARD.INTEGER (the predefined type)
19082 @item Cannot be a generic subprogram or an instantiation of a
19086 @node Implementation-Defined Attributes
19087 @section Implementation-Defined Attributes
19090 GNAT provides all DEC Ada implementation-defined
19093 @node Compiler and Run-Time Interfacing
19094 @section Compiler and Run-Time Interfacing
19097 DEC Ada provides the following ways to pass options to the linker (ACS LINK):
19099 @item /WAIT and /SUBMIT qualifiers
19101 @item /COMMAND qualifier
19103 @item /[NO]MAP qualifier
19105 @item /OUTPUT=file-spec
19107 @item /[NO]DEBUG and /[NO]TRACEBACK qualifiers
19111 To pass options to the linker, GNAT provides the following
19115 @item /EXECUTABLE=exec-name
19117 @item /VERBOSE qualifier
19119 @item /[NO]DEBUG and /[NO]TRACEBACK qualifiers
19123 For more information on these switches, see the section
19124 "Switches for gnatlink" in the corresponding section of this Guide.
19125 In DEC Ada, the command-line switch /OPTIMIZE is available
19126 to control optimization. DEC Ada also supplies the
19133 @item INLINE_GENERIC
19141 In GNAT, optimization is controlled strictly by command
19142 line parameters, as described in the corresponding section of this guide.
19143 The DIGITAL pragmas for control of optimization are
19144 recognized but ignored.
19146 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
19147 the default is that optimization is turned on.
19149 @node Program Compilation and Library Management
19150 @section Program Compilation and Library Management
19153 DEC Ada and GNAT provide a comparable set of commands to
19154 build programs. DEC Ada also provides a program library,
19155 which is a concept that does not exist on GNAT. Instead,
19156 GNAT provides directories of sources that are compiled as
19159 The following table summarizes
19160 the DEC Ada commands and provides
19161 equivalent GNAT commands. In this table, some GNAT
19162 equivalents reflect the fact that GNAT does not use the
19163 concept of a program library. Instead, it uses a model
19164 in which collections of source and object files are used
19165 in a manner consistent with other languages like C and
19166 Fortran. Therefore, standard system file commands are used
19167 to manipulate these elements. Those GNAT commands are marked with
19168 an asterisk in the table that follows.
19169 Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards.
19172 @multitable @columnfractions .31 .30 .39
19174 @item @strong{DEC_Ada_Command}
19175 @tab @strong{GNAT_Equivalent}
19176 @tab @strong{Description}
19180 @tab Invokes the compiler to compile one or more Ada source files.
19184 @tab Switches control of terminal from current process running the program
19188 @tab GNAT MAKE /DEPENDENCY_LIST
19189 @tab Forms the execution closure of one
19190 or more compiled units and checks completeness and currency.
19193 @tab GNAT MAKE /ACTIONS=COMPILE
19194 @tab Forms the execution closure of one or
19195 more specified units, checks completeness and currency,
19196 identifies units that have revised source files, compiles same,
19197 and recompiles units that are or will become obsolete.
19198 Also completes incomplete generic instantiations.
19200 @item ACS COPY FOREIGN
19202 @tab Copies a foreign object file into the program library as a
19205 @item ACS COPY UNIT
19207 @tab Copies a compiled unit from one program library to another.
19209 @item ACS CREATE LIBRARY
19210 @tab Create /directory (*)
19211 @tab Creates a program library.
19213 @item ACS CREATE SUBLIBRARY
19214 @tab Create /directory (*)
19215 @tab Creates a program sublibrary.
19217 @item ACS DELETE LIBRARY
19219 @tab Deletes a program library and its contents.
19221 @item ACS DELETE SUBLIBRARY
19223 @tab Deletes a program sublibrary and its contents.
19225 @item ACS DELETE UNIT
19226 @tab Delete @i{file} (*)
19227 @tab On OpenVMS systems, deletes one or more compiled units from
19228 the current program library.
19230 @item ACS DIRECTORY
19232 @tab On OpenVMS systems, lists units contained in the current
19235 @item ACS ENTER FOREIGN
19237 @tab Allows the import of a foreign body as an Ada library
19238 specification and enters a reference to a pointer.
19240 @item ACS ENTER UNIT
19242 @tab Enters a reference (pointer) from the current program library to
19243 a unit compiled into another program library.
19247 @tab Exits from the program library manager.
19251 @tab Creates an object file that contains system-specific object code
19252 for one or more units. With GNAT, object files can simply be copied
19253 into the desired directory.
19255 @item ACS EXTRACT SOURCE
19257 @tab Allows access to the copied source file for each Ada compilation unit
19261 @tab Provides online help.
19265 @tab Links an object file containing Ada units into an executable
19270 @tab Loads (partially compiles) Ada units into the program library.
19271 Allows loading a program from a collection of files into a library
19272 without knowing the relationship among units.
19276 @tab Merges into the current program library, one or more units from
19277 another library where they were modified.
19279 @item ACS RECOMPILE
19280 @tab GNAT MAKE /ACTIONS=COMPILE
19281 @tab Recompiles from external or copied source files any obsolete
19282 unit in the closure. Also, completes any incomplete generic
19287 @tab Reenters current references to units compiled after last entered
19288 with the ACS ENTER UNIT command.
19290 @item ACS SET LIBRARY
19291 @tab Set default (*)
19292 @tab Defines a program library to be the compilation context as well
19293 as the target library for compiler output and commands in general.
19295 @item ACS SET PRAGMA
19296 @tab Edit gnat.adc (*)
19297 @tab Redefines specified values of the library characteristics
19298 LONG_ FLOAT, MEMORY_SIZE, SYSTEM_NAME, and @code{Float_Representation}.
19300 @item ACS SET SOURCE
19301 @tab define @* ADA_INCLUDE_PATH @i{path} (*)
19302 @tab Defines the source file search list for the ACS COMPILE command.
19304 @item ACS SHOW LIBRARY
19306 @tab Lists information about one or more program libraries.
19308 @item ACS SHOW PROGRAM
19310 @tab Lists information about the execution closure of one or
19311 more units in the program library.
19313 @item ACS SHOW SOURCE
19314 @tab Show logical @* ADA_INCLUDE_PATH
19315 @tab Shows the source file search used when compiling units.
19317 @item ACS SHOW VERSION
19318 @tab Compile with VERBOSE option
19319 @tab Displays the version number of the compiler and program library
19324 @tab Creates a subprocess of the current process (same as DCL SPAWN
19329 @tab Performs a series of consistency checks on a program library to
19330 determine whether the library structure and library files are in
19338 @section Input-Output
19341 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
19342 Management Services (RMS) to perform operations on
19346 DEC Ada and GNAT predefine an identical set of input-
19347 output packages. To make the use of the
19348 generic TEXT_IO operations more convenient, DEC Ada
19349 provides predefined library packages that instantiate the
19350 integer and floating-point operations for the predefined
19351 integer and floating-point types as shown in the following table.
19358 @item INTEGER_TEXT_IO
19359 INTEGER_IO(INTEGER)
19361 @item SHORT_INTEGER_TEXT_IO
19362 INTEGER_IO(SHORT_INTEGER)
19364 @item SHORT_SHORT_INTEGER_TEXT_IO
19365 INTEGER_IO(SHORT_SHORT_ INTEGER)
19367 @item FLOAT_TEXT_IO
19370 @item LONG_FLOAT_TEXT_IO
19371 FLOAT_IO(LONG_FLOAT)
19375 The DEC Ada predefined packages and their operations
19376 are implemented using OpenVMS Alpha files and input-
19377 output facilities. DEC Ada supports asynchronous input-
19378 output on OpenVMS Alpha. Familiarity with the following is
19381 @item RMS file organizations and access methods
19383 @item OpenVMS file specifications and directories
19385 @item OpenVMS File Definition Language (FDL)
19389 GNAT provides I/O facilities that are completely
19390 compatible with DEC Ada. The distribution includes the
19391 standard DEC Ada versions of all I/O packages, operating
19392 in a manner compatible with DEC Ada. In particular, the
19393 following packages are by default the DEC Ada (Ada 83)
19394 versions of these packages rather than the renamings
19395 suggested in annex J of the Ada 95 Reference Manual:
19399 @item SEQUENTIAL_IO
19405 The use of the standard Ada 95 syntax for child packages (for
19406 example, ADA.TEXT_IO) retrieves the Ada 95 versions of these
19407 packages, as defined in the Ada 95 Reference Manual.
19408 GNAT provides DIGITAL-compatible predefined instantiations
19409 of the TEXT_IO packages, and also
19410 provides the standard predefined instantiations required
19411 by the Ada 95 Reference Manual.
19413 For further information on how GNAT interfaces to the file
19414 system or how I/O is implemented in programs written in
19415 mixed languages, see the chapter "Implementation of the
19416 Standard I/O" in the GNAT Reference Manual.
19417 This chapter covers the following:
19419 @item Standard I/O packages
19425 @item SEQUENTIAL_IO
19429 @item Stream pointer positioning
19431 @item Reading and writing non-regular files
19433 @item GET_IMMEDIATE
19435 @item Treating TEXT_IO files as streams
19442 @node Implementation Limits
19443 @section Implementation Limits
19446 The following table lists implementation limits for DEC Ada and GNAT systems.
19447 @multitable @columnfractions .60 .20 .20
19448 @item Compilation Parameter
19452 @item In a subprogram or entry declaration, maximum number of
19453 formal parameters that are of an unconstrained record type
19457 @item Maximum identifier length (number of characters)
19461 @item Maximum number of characters in a source line
19465 @item Maximum collection size (number of bytes)
19469 @item Maximum number of discriminants for a record type
19473 @item Maximum number of formal parameters in an entry or
19474 subprogram declaration
19478 @item Maximum number of dimensions in an array type
19482 @item Maximum number of library units and subunits in a compilation.
19486 @item Maximum number of library units and subunits in an execution.
19490 @item Maximum number of objects declared with the pragma COMMON_OBJECT
19495 @item Maximum number of enumeration literals in an enumeration type
19500 @item Maximum number of lines in a source file
19504 @item Maximum number of bits in any object
19508 @item Maximum size of the static portion of a stack frame (approximate)
19518 @node Inline Assembler
19519 @chapter Inline Assembler
19522 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:
19525 @item No need to use non-Ada tools
19526 @item Consistent interface over different targets
19527 @item Automatic usage of the proper calling conventions
19528 @item Access to Ada constants and variables
19529 @item Definition of intrinsic routines
19530 @item Possibility of inlining a subprogram comprising assembler code
19531 @item Code optimizer can take Inline Assembler code into account
19534 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.
19537 * Basic Assembler Syntax::
19538 * A Simple Example of Inline Assembler::
19539 * Output Variables in Inline Assembler::
19540 * Input Variables in Inline Assembler::
19541 * Inlining Inline Assembler Code::
19542 * Other Asm Functionality::
19543 * A Complete Example::
19546 @c ---------------------------------------------------------------------------
19547 @node Basic Assembler Syntax
19548 @section Basic Assembler Syntax
19551 The assembler used by GNAT and gcc is based not on the Intel assembly language, but rather on a
19552 language that descends from the AT&T Unix assembler @emph{as} (and which is often
19553 referred to as ``AT&T syntax'').
19554 The following table summarizes the main features of @emph{as} syntax and points out the differences from the Intel conventions.
19555 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
19556 pre-processor) documentation for further information.
19559 @item Register names
19560 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
19562 Intel: No extra punctuation; for example @code{eax}
19564 @item Immediate operand
19565 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
19567 Intel: No extra punctuation; for example @code{4}
19570 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
19572 Intel: No extra punctuation; for example @code{loc}
19574 @item Memory contents
19575 gcc / @emph{as}: No extra punctuation; for example @code{loc}
19577 Intel: Square brackets; for example @code{[loc]}
19579 @item Register contents
19580 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
19582 Intel: Square brackets; for example @code{[eax]}
19584 @item Hexadecimal numbers
19585 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
19587 Intel: Trailing ``h''; for example @code{A0h}
19590 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move a 16-bit word
19592 Intel: Implicit, deduced by assembler; for example @code{mov}
19594 @item Instruction repetition
19595 gcc / @emph{as}: Split into two lines; for example
19601 Intel: Keep on one line; for example @code{rep stosl}
19603 @item Order of operands
19604 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
19606 Intel: Destination first; for example @code{mov eax, 4}
19609 @c ---------------------------------------------------------------------------
19610 @node A Simple Example of Inline Assembler
19611 @section A Simple Example of Inline Assembler
19614 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.
19618 with System.Machine_Code; use System.Machine_Code;
19619 procedure Nothing is
19626 @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.
19627 @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.
19629 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}.
19631 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:
19635 However, the interesting aspect of this example is not its run-time behavior but rather the
19636 generated assembly code. To see this output, invoke the compiler as follows:
19638 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
19640 where the options are:
19644 compile only (no bind or link)
19646 generate assembler listing
19647 @item -fomit-frame-pointer
19648 do not set up separate stack frames
19650 do not add runtime checks
19653 This gives a human-readable assembler version of the code. The resulting
19654 file will have the same name as the Ada source file, but with a @code{.s} extension.
19655 In our example, the file @file{nothing.s} has the following contents:
19659 .file "nothing.adb"
19661 ___gnu_compiled_ada:
19664 .globl __ada_nothing
19676 The assembly code you included is clearly indicated by
19677 the compiler, between the @code{#APP} and @code{#NO_APP}
19678 delimiters. The character before the 'APP' and 'NOAPP'
19679 can differ on different targets. For example, Linux uses '#APP' while
19680 on NT you will see '/APP'.
19682 If you make a mistake in your assembler code (such as using the
19683 wrong size modifier, or using a wrong operand for the instruction) GNAT
19684 will report this error in a temporary file, which will be deleted when
19685 the compilation is finished. Generating an assembler file will help
19686 in such cases, since you can assemble this file separately using the
19687 @emph{as} assembler that comes with gcc.
19689 Assembling the file using the command
19692 as @file{nothing.s}
19695 will give you error messages whose lines correspond to the assembler
19696 input file, so you can easily find and correct any mistakes you made.
19697 If there are no errors, @emph{as} will generate an object file @file{nothing.out}.
19699 @c ---------------------------------------------------------------------------
19700 @node Output Variables in Inline Assembler
19701 @section Output Variables in Inline Assembler
19704 The examples in this section, showing how to access the processor flags, illustrate how to specify the destination operands for assembly language statements.
19708 with Interfaces; use Interfaces;
19709 with Ada.Text_IO; use Ada.Text_IO;
19710 with System.Machine_Code; use System.Machine_Code;
19711 procedure Get_Flags is
19712 Flags : Unsigned_32;
19715 Asm ("pushfl" & LF & HT & -- push flags on stack
19716 "popl %%eax" & LF & HT & -- load eax with flags
19717 "movl %%eax, %0", -- store flags in variable
19718 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
19719 Put_Line ("Flags register:" & Flags'Img);
19724 In order to have a nicely aligned assembly listing, we have separated
19725 multiple assembler statements in the Asm template string with linefeed (ASCII.LF)
19726 and horizontal tab (ASCII.HT) characters. The resulting section of the
19727 assembly output file is:
19734 movl %eax, -40(%ebp)
19739 It would have been legal to write the Asm invocation as:
19742 Asm ("pushfl popl %%eax movl %%eax, %0")
19745 but in the generated assembler file, this would come out as:
19749 pushfl popl %eax movl %eax, -40(%ebp)
19753 which is not so convenient for the human reader.
19755 We use Ada comments
19756 at the end of each line to explain what the assembler instructions
19757 actually do. This is a useful convention.
19759 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.
19761 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}.
19762 An output variable is illustrated in
19763 the third statement in the Asm template string:
19767 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.
19769 Information about the output variable is supplied in the @code{Outputs} parameter to @code{Asm}:
19771 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
19774 The output is defined by the @code{Asm_Output} attribute of the target type; the general format is
19776 Type'Asm_Output (constraint_string, variable_name)
19779 The constraint string directs the compiler how
19780 to store/access the associated variable. In the example
19782 Unsigned_32'Asm_Output ("=m", Flags);
19784 the @code{"m"} (memory) constraint tells the compiler that the variable
19785 @code{Flags} should be stored in a memory variable, thus preventing
19786 the optimizer from keeping it in a register. In contrast,
19788 Unsigned_32'Asm_Output ("=r", Flags);
19790 uses the @code{"r"} (register) constraint, telling the compiler to
19791 store the variable in a register.
19793 If the constraint is preceded by the equal character (@strong{=}), it tells the
19794 compiler that the variable will be used to store data into it.
19796 In the @code{Get_Flags} example, we used the "g" (global) constraint, allowing the optimizer
19797 to choose whatever it deems best.
19799 There are a fairly large number of constraints, but the ones that are most useful (for the Intel x86 processor) are the following:
19805 global (i.e. can be stored anywhere)
19823 use one of eax, ebx, ecx or edx
19825 use one of eax, ebx, ecx, edx, esi or edi
19828 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.
19830 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
19833 Asm ("pushfl" & LF & HT & -- push flags on stack
19834 "popl %%eax" & LF & HT & -- load eax with flags
19835 "movl %%eax, %0", -- store flags in variable
19836 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
19840 @code{%0} will be replaced in the expanded code by the appropriate operand,
19842 the compiler decided for the @code{Flags} variable.
19844 In general, you may have any number of output variables:
19847 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
19849 Specify the @code{Outputs} parameter as a parenthesized comma-separated list of @code{Asm_Output} attributes
19855 Asm ("movl %%eax, %0" & LF & HT &
19856 "movl %%ebx, %1" & LF & HT &
19858 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
19859 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
19860 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
19864 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables in the Ada program.
19866 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:
19870 with Interfaces; use Interfaces;
19871 with Ada.Text_IO; use Ada.Text_IO;
19872 with System.Machine_Code; use System.Machine_Code;
19873 procedure Get_Flags_2 is
19874 Flags : Unsigned_32;
19877 Asm ("pushfl" & LF & HT & -- push flags on stack
19878 "popl %%eax", -- save flags in eax
19879 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
19880 Put_Line ("Flags register:" & Flags'Img);
19886 The @code{"a"} constraint tells the compiler that the @code{Flags}
19887 variable will come from the eax register. Here is the resulting code:
19895 movl %eax,-40(%ebp)
19900 The compiler generated the store of eax into Flags after
19901 expanding the assembler code.
19903 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:
19907 with Interfaces; use Interfaces;
19908 with Ada.Text_IO; use Ada.Text_IO;
19909 with System.Machine_Code; use System.Machine_Code;
19910 procedure Get_Flags_3 is
19911 Flags : Unsigned_32;
19914 Asm ("pushfl" & LF & HT & -- push flags on stack
19915 "pop %0", -- save flags in Flags
19916 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
19917 Put_Line ("Flags register:" & Flags'Img);
19922 @c ---------------------------------------------------------------------------
19923 @node Input Variables in Inline Assembler
19924 @section Input Variables in Inline Assembler
19927 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:
19931 with Interfaces; use Interfaces;
19932 with Ada.Text_IO; use Ada.Text_IO;
19933 with System.Machine_Code; use System.Machine_Code;
19934 procedure Increment is
19936 function Incr (Value : Unsigned_32) return Unsigned_32 is
19937 Result : Unsigned_32;
19940 Inputs => Unsigned_32'Asm_Input ("a", Value),
19941 Outputs => Unsigned_32'Asm_Output ("=a", Result));
19945 Value : Unsigned_32;
19949 Put_Line ("Value before is" & Value'Img);
19950 Value := Incr (Value);
19951 Put_Line ("Value after is" & Value'Img);
19956 The @code{Outputs} parameter to @code{Asm} specifies
19957 that the result will be in the eax register and that it is to be stored in the @code{Result}
19960 The @code{Inputs} parameter looks much like the @code{Outputs} parameter, but with an
19961 @code{Asm_Input} attribute. The
19962 @code{"="} constraint, indicating an output value, is not present.
19964 You can have multiple input variables, in the same way that you can have more
19965 than one output variable.
19967 The parameter count (%0, %1) etc, now starts at the first input
19968 statement, and continues with the output statements.
19969 When both parameters use the same variable, the
19970 compiler will treat them as the same %n operand, which is the case here.
19972 Just as the @code{Outputs} parameter causes the register to be stored into the
19973 target variable after execution of the assembler statements, so does the
19974 @code{Inputs} parameter cause its variable to be loaded into the register before execution
19976 assembler statements.
19978 Thus the effect of the @code{Asm} invocation is:
19980 @item load the 32-bit value of @code{Value} into eax
19981 @item execute the @code{incl %eax} instruction
19982 @item store the contents of eax into the @code{Result} variable
19985 The resulting assembler file (with @code{-O2} optimization) contains:
19988 _increment__incr.1:
20001 @c ---------------------------------------------------------------------------
20002 @node Inlining Inline Assembler Code
20003 @section Inlining Inline Assembler Code
20006 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)
20007 can be significant, compared to the amount of code in the subprogram body.
20008 A solution is to apply Ada's @code{Inline} pragma to the subprogram,
20009 which directs the compiler to expand invocations of the subprogram at the point(s)
20010 of call, instead of setting up a stack frame for out-of-line calls.
20011 Here is the resulting program:
20015 with Interfaces; use Interfaces;
20016 with Ada.Text_IO; use Ada.Text_IO;
20017 with System.Machine_Code; use System.Machine_Code;
20018 procedure Increment_2 is
20020 function Incr (Value : Unsigned_32) return Unsigned_32 is
20021 Result : Unsigned_32;
20024 Inputs => Unsigned_32'Asm_Input ("a", Value),
20025 Outputs => Unsigned_32'Asm_Output ("=a", Result));
20028 pragma Inline (Increment);
20030 Value : Unsigned_32;
20034 Put_Line ("Value before is" & Value'Img);
20035 Value := Increment (Value);
20036 Put_Line ("Value after is" & Value'Img);
20041 Compile the program with both optimization (@code{-O2}) and inlining
20042 enabled (@option{-gnatpn} instead of @option{-gnatp}).
20044 The @code{Incr} function is still compiled as usual, but at the
20045 point in @code{Increment} where our function used to be called:
20050 call _increment__incr.1
20055 the code for the function body directly appears:
20068 thus saving the overhead of stack frame setup and an out-of-line call.
20070 @c ---------------------------------------------------------------------------
20071 @node Other Asm Functionality
20072 @section Other @code{Asm} Functionality
20075 This section describes two important parameters to the @code{Asm} procedure: @code{Clobber}, which identifies register usage; and @code{Volatile}, which inhibits unwanted optimizations.
20078 * The Clobber Parameter::
20079 * The Volatile Parameter::
20082 @c ---------------------------------------------------------------------------
20083 @node The Clobber Parameter
20084 @subsection The @code{Clobber} Parameter
20087 One of the dangers of intermixing assembly language and a compiled language such as Ada is
20088 that the compiler needs to be aware of which registers are being used by the assembly code.
20089 In some cases, such as the earlier examples, the constraint string is sufficient to
20090 indicate register usage (e.g. "a" for the eax register). But more generally, the
20091 compiler needs an explicit identification of the registers that are used by the Inline
20092 Assembly statements.
20094 Using a register that the compiler doesn't know about
20095 could be a side effect of an instruction (like @code{mull}
20096 storing its result in both eax and edx).
20097 It can also arise from explicit register usage in your
20098 assembly code; for example:
20101 Asm ("movl %0, %%ebx" & LF & HT &
20103 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
20104 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
20108 where the compiler (since it does not analyze the @code{Asm} template string)
20109 does not know you are using the ebx register.
20111 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
20112 to identify the registers that will be used by your assembly code:
20116 Asm ("movl %0, %%ebx" & LF & HT &
20118 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
20119 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
20124 The Clobber parameter is a static string expression specifying the
20125 register(s) you are using. Note that register names are @emph{not} prefixed by a percent sign.
20126 Also, if more than one register is used then their names are separated by commas; e.g., @code{"eax, ebx"}
20128 The @code{Clobber} parameter has several additional uses:
20130 @item Use the "register" name @code{cc} to indicate that flags might have changed
20131 @item Use the "register" name @code{memory} if you changed a memory location
20134 @c ---------------------------------------------------------------------------
20135 @node The Volatile Parameter
20136 @subsection The @code{Volatile} Parameter
20137 @cindex Volatile parameter
20140 Compiler optimizations in the presence of Inline Assembler may sometimes have unwanted effects.
20142 an @code{Asm} invocation with an input variable is inside a loop, the compiler might move
20143 the loading of the input variable outside the loop, regarding it as a
20144 one-time initialization.
20146 If this effect is not desired, you can disable such optimizations by setting the
20147 @code{Volatile} parameter to @code{True}; for example:
20151 Asm ("movl %0, %%ebx" & LF & HT &
20153 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
20154 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
20160 By default, @code{Volatile} is set to @code{False} unless there is no @code{Outputs}
20163 Although setting @code{Volatile} to @code{True} prevents unwanted optimizations,
20164 it will also disable other optimizations that might be important for efficiency.
20165 In general, you should set @code{Volatile} to @code{True} only if the compiler's
20166 optimizations have created problems.
20168 @c ---------------------------------------------------------------------------
20169 @node A Complete Example
20170 @section A Complete Example
20173 This section contains a complete program illustrating a realistic usage of GNAT's Inline Assembler
20174 capabilities. It comprises a main procedure @code{Check_CPU} and a package @code{Intel_CPU}.
20175 The package declares a collection of functions that detect the properties of the 32-bit
20176 x86 processor that is running the program. The main procedure invokes these functions
20177 and displays the information.
20179 The Intel_CPU package could be enhanced by adding functions to
20180 detect the type of x386 co-processor, the processor caching options and
20181 special operations such as the SIMD extensions.
20183 Although the Intel_CPU package has been written for 32-bit Intel
20184 compatible CPUs, it is OS neutral. It has been tested on DOS,
20185 Windows/NT and Linux.
20188 * Check_CPU Procedure::
20189 * Intel_CPU Package Specification::
20190 * Intel_CPU Package Body::
20193 @c ---------------------------------------------------------------------------
20194 @node Check_CPU Procedure
20195 @subsection @code{Check_CPU} Procedure
20196 @cindex Check_CPU procedure
20199 ---------------------------------------------------------------------
20201 -- Uses the Intel_CPU package to identify the CPU the program is --
20202 -- running on, and some of the features it supports. --
20204 ---------------------------------------------------------------------
20206 with Intel_CPU; -- Intel CPU detection functions
20207 with Ada.Text_IO; -- Standard text I/O
20208 with Ada.Command_Line; -- To set the exit status
20210 procedure Check_CPU is
20212 Type_Found : Boolean := False;
20213 -- Flag to indicate that processor was identified
20215 Features : Intel_CPU.Processor_Features;
20216 -- The processor features
20218 Signature : Intel_CPU.Processor_Signature;
20219 -- The processor type signature
20223 -----------------------------------
20224 -- Display the program banner. --
20225 -----------------------------------
20227 Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
20228 ": check Intel CPU version and features, v1.0");
20229 Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
20230 Ada.Text_IO.New_Line;
20232 -----------------------------------------------------------------------
20233 -- We can safely start with the assumption that we are on at least --
20234 -- a x386 processor. If the CPUID instruction is present, then we --
20235 -- have a later processor type. --
20236 -----------------------------------------------------------------------
20238 if Intel_CPU.Has_CPUID = False then
20240 -- No CPUID instruction, so we assume this is indeed a x386
20241 -- processor. We can still check if it has a FP co-processor.
20242 if Intel_CPU.Has_FPU then
20243 Ada.Text_IO.Put_Line
20244 ("x386-type processor with a FP co-processor");
20246 Ada.Text_IO.Put_Line
20247 ("x386-type processor without a FP co-processor");
20248 end if; -- check for FPU
20251 Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
20254 end if; -- check for CPUID
20256 -----------------------------------------------------------------------
20257 -- If CPUID is supported, check if this is a true Intel processor, --
20258 -- if it is not, display a warning. --
20259 -----------------------------------------------------------------------
20261 if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
20262 Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
20263 Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
20264 end if; -- check if Intel
20266 ----------------------------------------------------------------------
20267 -- With the CPUID instruction present, we can assume at least a --
20268 -- x486 processor. If the CPUID support level is < 1 then we have --
20269 -- to leave it at that. --
20270 ----------------------------------------------------------------------
20272 if Intel_CPU.CPUID_Level < 1 then
20274 -- Ok, this is a x486 processor. we still can get the Vendor ID
20275 Ada.Text_IO.Put_Line ("x486-type processor");
20276 Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
20278 -- We can also check if there is a FPU present
20279 if Intel_CPU.Has_FPU then
20280 Ada.Text_IO.Put_Line ("Floating-Point support");
20282 Ada.Text_IO.Put_Line ("No Floating-Point support");
20283 end if; -- check for FPU
20286 Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
20289 end if; -- check CPUID level
20291 ---------------------------------------------------------------------
20292 -- With a CPUID level of 1 we can use the processor signature to --
20293 -- determine it's exact type. --
20294 ---------------------------------------------------------------------
20296 Signature := Intel_CPU.Signature;
20298 ----------------------------------------------------------------------
20299 -- Ok, now we go into a lot of messy comparisons to get the --
20300 -- processor type. For clarity, no attememt to try to optimize the --
20301 -- comparisons has been made. Note that since Intel_CPU does not --
20302 -- support getting cache info, we cannot distinguish between P5 --
20303 -- and Celeron types yet. --
20304 ----------------------------------------------------------------------
20307 if Signature.Processor_Type = 2#00# and
20308 Signature.Family = 2#0100# and
20309 Signature.Model = 2#0100# then
20310 Type_Found := True;
20311 Ada.Text_IO.Put_Line ("x486SL processor");
20314 -- x486DX2 Write-Back
20315 if Signature.Processor_Type = 2#00# and
20316 Signature.Family = 2#0100# and
20317 Signature.Model = 2#0111# then
20318 Type_Found := True;
20319 Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
20323 if Signature.Processor_Type = 2#00# and
20324 Signature.Family = 2#0100# and
20325 Signature.Model = 2#1000# then
20326 Type_Found := True;
20327 Ada.Text_IO.Put_Line ("x486DX4 processor");
20330 -- x486DX4 Overdrive
20331 if Signature.Processor_Type = 2#01# and
20332 Signature.Family = 2#0100# and
20333 Signature.Model = 2#1000# then
20334 Type_Found := True;
20335 Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
20338 -- Pentium (60, 66)
20339 if Signature.Processor_Type = 2#00# and
20340 Signature.Family = 2#0101# and
20341 Signature.Model = 2#0001# then
20342 Type_Found := True;
20343 Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
20346 -- Pentium (75, 90, 100, 120, 133, 150, 166, 200)
20347 if Signature.Processor_Type = 2#00# and
20348 Signature.Family = 2#0101# and
20349 Signature.Model = 2#0010# then
20350 Type_Found := True;
20351 Ada.Text_IO.Put_Line
20352 ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
20355 -- Pentium OverDrive (60, 66)
20356 if Signature.Processor_Type = 2#01# and
20357 Signature.Family = 2#0101# and
20358 Signature.Model = 2#0001# then
20359 Type_Found := True;
20360 Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
20363 -- Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
20364 if Signature.Processor_Type = 2#01# and
20365 Signature.Family = 2#0101# and
20366 Signature.Model = 2#0010# then
20367 Type_Found := True;
20368 Ada.Text_IO.Put_Line
20369 ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
20372 -- Pentium OverDrive processor for x486 processor-based systems
20373 if Signature.Processor_Type = 2#01# and
20374 Signature.Family = 2#0101# and
20375 Signature.Model = 2#0011# then
20376 Type_Found := True;
20377 Ada.Text_IO.Put_Line
20378 ("Pentium OverDrive processor for x486 processor-based systems");
20381 -- Pentium processor with MMX technology (166, 200)
20382 if Signature.Processor_Type = 2#00# and
20383 Signature.Family = 2#0101# and
20384 Signature.Model = 2#0100# then
20385 Type_Found := True;
20386 Ada.Text_IO.Put_Line
20387 ("Pentium processor with MMX technology (166, 200)");
20390 -- Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
20391 if Signature.Processor_Type = 2#01# and
20392 Signature.Family = 2#0101# and
20393 Signature.Model = 2#0100# then
20394 Type_Found := True;
20395 Ada.Text_IO.Put_Line
20396 ("Pentium OverDrive processor with MMX " &
20397 "technology for Pentium processor (75, 90, 100, 120, 133)");
20400 -- Pentium Pro processor
20401 if Signature.Processor_Type = 2#00# and
20402 Signature.Family = 2#0110# and
20403 Signature.Model = 2#0001# then
20404 Type_Found := True;
20405 Ada.Text_IO.Put_Line ("Pentium Pro processor");
20408 -- Pentium II processor, model 3
20409 if Signature.Processor_Type = 2#00# and
20410 Signature.Family = 2#0110# and
20411 Signature.Model = 2#0011# then
20412 Type_Found := True;
20413 Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
20416 -- Pentium II processor, model 5 or Celeron processor
20417 if Signature.Processor_Type = 2#00# and
20418 Signature.Family = 2#0110# and
20419 Signature.Model = 2#0101# then
20420 Type_Found := True;
20421 Ada.Text_IO.Put_Line
20422 ("Pentium II processor, model 5 or Celeron processor");
20425 -- Pentium Pro OverDrive processor
20426 if Signature.Processor_Type = 2#01# and
20427 Signature.Family = 2#0110# and
20428 Signature.Model = 2#0011# then
20429 Type_Found := True;
20430 Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
20433 -- If no type recognized, we have an unknown. Display what
20435 if Type_Found = False then
20436 Ada.Text_IO.Put_Line ("Unknown processor");
20439 -----------------------------------------
20440 -- Display processor stepping level. --
20441 -----------------------------------------
20443 Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
20445 ---------------------------------
20446 -- Display vendor ID string. --
20447 ---------------------------------
20449 Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
20451 ------------------------------------
20452 -- Get the processors features. --
20453 ------------------------------------
20455 Features := Intel_CPU.Features;
20457 -----------------------------
20458 -- Check for a FPU unit. --
20459 -----------------------------
20461 if Features.FPU = True then
20462 Ada.Text_IO.Put_Line ("Floating-Point unit available");
20464 Ada.Text_IO.Put_Line ("no Floating-Point unit");
20465 end if; -- check for FPU
20467 --------------------------------
20468 -- List processor features. --
20469 --------------------------------
20471 Ada.Text_IO.Put_Line ("Supported features: ");
20473 -- Virtual Mode Extension
20474 if Features.VME = True then
20475 Ada.Text_IO.Put_Line (" VME - Virtual Mode Extension");
20478 -- Debugging Extension
20479 if Features.DE = True then
20480 Ada.Text_IO.Put_Line (" DE - Debugging Extension");
20483 -- Page Size Extension
20484 if Features.PSE = True then
20485 Ada.Text_IO.Put_Line (" PSE - Page Size Extension");
20488 -- Time Stamp Counter
20489 if Features.TSC = True then
20490 Ada.Text_IO.Put_Line (" TSC - Time Stamp Counter");
20493 -- Model Specific Registers
20494 if Features.MSR = True then
20495 Ada.Text_IO.Put_Line (" MSR - Model Specific Registers");
20498 -- Physical Address Extension
20499 if Features.PAE = True then
20500 Ada.Text_IO.Put_Line (" PAE - Physical Address Extension");
20503 -- Machine Check Extension
20504 if Features.MCE = True then
20505 Ada.Text_IO.Put_Line (" MCE - Machine Check Extension");
20508 -- CMPXCHG8 instruction supported
20509 if Features.CX8 = True then
20510 Ada.Text_IO.Put_Line (" CX8 - CMPXCHG8 instruction");
20513 -- on-chip APIC hardware support
20514 if Features.APIC = True then
20515 Ada.Text_IO.Put_Line (" APIC - on-chip APIC hardware support");
20518 -- Fast System Call
20519 if Features.SEP = True then
20520 Ada.Text_IO.Put_Line (" SEP - Fast System Call");
20523 -- Memory Type Range Registers
20524 if Features.MTRR = True then
20525 Ada.Text_IO.Put_Line (" MTTR - Memory Type Range Registers");
20528 -- Page Global Enable
20529 if Features.PGE = True then
20530 Ada.Text_IO.Put_Line (" PGE - Page Global Enable");
20533 -- Machine Check Architecture
20534 if Features.MCA = True then
20535 Ada.Text_IO.Put_Line (" MCA - Machine Check Architecture");
20538 -- Conditional Move Instruction Supported
20539 if Features.CMOV = True then
20540 Ada.Text_IO.Put_Line
20541 (" CMOV - Conditional Move Instruction Supported");
20544 -- Page Attribute Table
20545 if Features.PAT = True then
20546 Ada.Text_IO.Put_Line (" PAT - Page Attribute Table");
20549 -- 36-bit Page Size Extension
20550 if Features.PSE_36 = True then
20551 Ada.Text_IO.Put_Line (" PSE_36 - 36-bit Page Size Extension");
20554 -- MMX technology supported
20555 if Features.MMX = True then
20556 Ada.Text_IO.Put_Line (" MMX - MMX technology supported");
20559 -- Fast FP Save and Restore
20560 if Features.FXSR = True then
20561 Ada.Text_IO.Put_Line (" FXSR - Fast FP Save and Restore");
20564 ---------------------
20565 -- Program done. --
20566 ---------------------
20568 Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
20573 Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
20579 @c ---------------------------------------------------------------------------
20580 @node Intel_CPU Package Specification
20581 @subsection @code{Intel_CPU} Package Specification
20582 @cindex Intel_CPU package specification
20585 -------------------------------------------------------------------------
20587 -- file: intel_cpu.ads --
20589 -- ********************************************* --
20590 -- * WARNING: for 32-bit Intel processors only * --
20591 -- ********************************************* --
20593 -- This package contains a number of subprograms that are useful in --
20594 -- determining the Intel x86 CPU (and the features it supports) on --
20595 -- which the program is running. --
20597 -- The package is based upon the information given in the Intel --
20598 -- Application Note AP-485: "Intel Processor Identification and the --
20599 -- CPUID Instruction" as of April 1998. This application note can be --
20600 -- found on www.intel.com. --
20602 -- It currently deals with 32-bit processors only, will not detect --
20603 -- features added after april 1998, and does not guarantee proper --
20604 -- results on Intel-compatible processors. --
20606 -- Cache info and x386 fpu type detection are not supported. --
20608 -- This package does not use any privileged instructions, so should --
20609 -- work on any OS running on a 32-bit Intel processor. --
20611 -------------------------------------------------------------------------
20613 with Interfaces; use Interfaces;
20614 -- for using unsigned types
20616 with System.Machine_Code; use System.Machine_Code;
20617 -- for using inline assembler code
20619 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
20620 -- for inserting control characters
20622 package Intel_CPU is
20624 ----------------------
20625 -- Processor bits --
20626 ----------------------
20628 subtype Num_Bits is Natural range 0 .. 31;
20629 -- the number of processor bits (32)
20631 --------------------------
20632 -- Processor register --
20633 --------------------------
20635 -- define a processor register type for easy access to
20636 -- the individual bits
20638 type Processor_Register is array (Num_Bits) of Boolean;
20639 pragma Pack (Processor_Register);
20640 for Processor_Register'Size use 32;
20642 -------------------------
20643 -- Unsigned register --
20644 -------------------------
20646 -- define a processor register type for easy access to
20647 -- the individual bytes
20649 type Unsigned_Register is
20657 for Unsigned_Register use
20659 L1 at 0 range 0 .. 7;
20660 H1 at 0 range 8 .. 15;
20661 L2 at 0 range 16 .. 23;
20662 H2 at 0 range 24 .. 31;
20665 for Unsigned_Register'Size use 32;
20667 ---------------------------------
20668 -- Intel processor vendor ID --
20669 ---------------------------------
20671 Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
20672 -- indicates an Intel manufactured processor
20674 ------------------------------------
20675 -- Processor signature register --
20676 ------------------------------------
20678 -- a register type to hold the processor signature
20680 type Processor_Signature is
20682 Stepping : Natural range 0 .. 15;
20683 Model : Natural range 0 .. 15;
20684 Family : Natural range 0 .. 15;
20685 Processor_Type : Natural range 0 .. 3;
20686 Reserved : Natural range 0 .. 262143;
20689 for Processor_Signature use
20691 Stepping at 0 range 0 .. 3;
20692 Model at 0 range 4 .. 7;
20693 Family at 0 range 8 .. 11;
20694 Processor_Type at 0 range 12 .. 13;
20695 Reserved at 0 range 14 .. 31;
20698 for Processor_Signature'Size use 32;
20700 -----------------------------------
20701 -- Processor features register --
20702 -----------------------------------
20704 -- a processor register to hold the processor feature flags
20706 type Processor_Features is
20708 FPU : Boolean; -- floating point unit on chip
20709 VME : Boolean; -- virtual mode extension
20710 DE : Boolean; -- debugging extension
20711 PSE : Boolean; -- page size extension
20712 TSC : Boolean; -- time stamp counter
20713 MSR : Boolean; -- model specific registers
20714 PAE : Boolean; -- physical address extension
20715 MCE : Boolean; -- machine check extension
20716 CX8 : Boolean; -- cmpxchg8 instruction
20717 APIC : Boolean; -- on-chip apic hardware
20718 Res_1 : Boolean; -- reserved for extensions
20719 SEP : Boolean; -- fast system call
20720 MTRR : Boolean; -- memory type range registers
20721 PGE : Boolean; -- page global enable
20722 MCA : Boolean; -- machine check architecture
20723 CMOV : Boolean; -- conditional move supported
20724 PAT : Boolean; -- page attribute table
20725 PSE_36 : Boolean; -- 36-bit page size extension
20726 Res_2 : Natural range 0 .. 31; -- reserved for extensions
20727 MMX : Boolean; -- MMX technology supported
20728 FXSR : Boolean; -- fast FP save and restore
20729 Res_3 : Natural range 0 .. 127; -- reserved for extensions
20732 for Processor_Features use
20734 FPU at 0 range 0 .. 0;
20735 VME at 0 range 1 .. 1;
20736 DE at 0 range 2 .. 2;
20737 PSE at 0 range 3 .. 3;
20738 TSC at 0 range 4 .. 4;
20739 MSR at 0 range 5 .. 5;
20740 PAE at 0 range 6 .. 6;
20741 MCE at 0 range 7 .. 7;
20742 CX8 at 0 range 8 .. 8;
20743 APIC at 0 range 9 .. 9;
20744 Res_1 at 0 range 10 .. 10;
20745 SEP at 0 range 11 .. 11;
20746 MTRR at 0 range 12 .. 12;
20747 PGE at 0 range 13 .. 13;
20748 MCA at 0 range 14 .. 14;
20749 CMOV at 0 range 15 .. 15;
20750 PAT at 0 range 16 .. 16;
20751 PSE_36 at 0 range 17 .. 17;
20752 Res_2 at 0 range 18 .. 22;
20753 MMX at 0 range 23 .. 23;
20754 FXSR at 0 range 24 .. 24;
20755 Res_3 at 0 range 25 .. 31;
20758 for Processor_Features'Size use 32;
20760 -------------------
20762 -------------------
20764 function Has_FPU return Boolean;
20765 -- return True if a FPU is found
20766 -- use only if CPUID is not supported
20768 function Has_CPUID return Boolean;
20769 -- return True if the processor supports the CPUID instruction
20771 function CPUID_Level return Natural;
20772 -- return the CPUID support level (0, 1 or 2)
20773 -- can only be called if the CPUID instruction is supported
20775 function Vendor_ID return String;
20776 -- return the processor vendor identification string
20777 -- can only be called if the CPUID instruction is supported
20779 function Signature return Processor_Signature;
20780 -- return the processor signature
20781 -- can only be called if the CPUID instruction is supported
20783 function Features return Processor_Features;
20784 -- return the processors features
20785 -- can only be called if the CPUID instruction is supported
20789 ------------------------
20790 -- EFLAGS bit names --
20791 ------------------------
20793 ID_Flag : constant Num_Bits := 21;
20799 @c ---------------------------------------------------------------------------
20800 @node Intel_CPU Package Body
20801 @subsection @code{Intel_CPU} Package Body
20802 @cindex Intel_CPU package body
20805 package body Intel_CPU is
20807 ---------------------------
20808 -- Detect FPU presence --
20809 ---------------------------
20811 -- There is a FPU present if we can set values to the FPU Status
20812 -- and Control Words.
20814 function Has_FPU return Boolean is
20816 Register : Unsigned_16;
20817 -- processor register to store a word
20821 -- check if we can change the status word
20824 -- the assembler code
20825 "finit" & LF & HT & -- reset status word
20826 "movw $0x5A5A, %%ax" & LF & HT & -- set value status word
20827 "fnstsw %0" & LF & HT & -- save status word
20828 "movw %%ax, %0", -- store status word
20830 -- output stored in Register
20831 -- register must be a memory location
20832 Outputs => Unsigned_16'Asm_output ("=m", Register),
20834 -- tell compiler that we used eax
20837 -- if the status word is zero, there is no FPU
20838 if Register = 0 then
20839 return False; -- no status word
20840 end if; -- check status word value
20842 -- check if we can get the control word
20845 -- the assembler code
20846 "fnstcw %0", -- save the control word
20848 -- output into Register
20849 -- register must be a memory location
20850 Outputs => Unsigned_16'Asm_output ("=m", Register));
20852 -- check the relevant bits
20853 if (Register and 16#103F#) /= 16#003F# then
20854 return False; -- no control word
20855 end if; -- check control word value
20862 --------------------------------
20863 -- Detect CPUID instruction --
20864 --------------------------------
20866 -- The processor supports the CPUID instruction if it is possible
20867 -- to change the value of ID flag bit in the EFLAGS register.
20869 function Has_CPUID return Boolean is
20871 Original_Flags, Modified_Flags : Processor_Register;
20872 -- EFLAG contents before and after changing the ID flag
20876 -- try flipping the ID flag in the EFLAGS register
20879 -- the assembler code
20880 "pushfl" & LF & HT & -- push EFLAGS on stack
20881 "pop %%eax" & LF & HT & -- pop EFLAGS into eax
20882 "movl %%eax, %0" & LF & HT & -- save EFLAGS content
20883 "xor $0x200000, %%eax" & LF & HT & -- flip ID flag
20884 "push %%eax" & LF & HT & -- push EFLAGS on stack
20885 "popfl" & LF & HT & -- load EFLAGS register
20886 "pushfl" & LF & HT & -- push EFLAGS on stack
20887 "pop %1", -- save EFLAGS content
20889 -- output values, may be anything
20890 -- Original_Flags is %0
20891 -- Modified_Flags is %1
20893 (Processor_Register'Asm_output ("=g", Original_Flags),
20894 Processor_Register'Asm_output ("=g", Modified_Flags)),
20896 -- tell compiler eax is destroyed
20899 -- check if CPUID is supported
20900 if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
20901 return True; -- ID flag was modified
20903 return False; -- ID flag unchanged
20904 end if; -- check for CPUID
20908 -------------------------------
20909 -- Get CPUID support level --
20910 -------------------------------
20912 function CPUID_Level return Natural is
20914 Level : Unsigned_32;
20915 -- returned support level
20919 -- execute CPUID, storing the results in the Level register
20922 -- the assembler code
20923 "cpuid", -- execute CPUID
20925 -- zero is stored in eax
20926 -- returning the support level in eax
20927 Inputs => Unsigned_32'Asm_input ("a", 0),
20929 -- eax is stored in Level
20930 Outputs => Unsigned_32'Asm_output ("=a", Level),
20932 -- tell compiler ebx, ecx and edx registers are destroyed
20933 Clobber => "ebx, ecx, edx");
20935 -- return the support level
20936 return Natural (Level);
20940 --------------------------------
20941 -- Get CPU Vendor ID String --
20942 --------------------------------
20944 -- The vendor ID string is returned in the ebx, ecx and edx register
20945 -- after executing the CPUID instruction with eax set to zero.
20946 -- In case of a true Intel processor the string returned is
20949 function Vendor_ID return String is
20951 Ebx, Ecx, Edx : Unsigned_Register;
20952 -- registers containing the vendor ID string
20954 Vendor_ID : String (1 .. 12);
20955 -- the vendor ID string
20959 -- execute CPUID, storing the results in the processor registers
20962 -- the assembler code
20963 "cpuid", -- execute CPUID
20965 -- zero stored in eax
20966 -- vendor ID string returned in ebx, ecx and edx
20967 Inputs => Unsigned_32'Asm_input ("a", 0),
20969 -- ebx is stored in Ebx
20970 -- ecx is stored in Ecx
20971 -- edx is stored in Edx
20972 Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
20973 Unsigned_Register'Asm_output ("=c", Ecx),
20974 Unsigned_Register'Asm_output ("=d", Edx)));
20976 -- now build the vendor ID string
20977 Vendor_ID( 1) := Character'Val (Ebx.L1);
20978 Vendor_ID( 2) := Character'Val (Ebx.H1);
20979 Vendor_ID( 3) := Character'Val (Ebx.L2);
20980 Vendor_ID( 4) := Character'Val (Ebx.H2);
20981 Vendor_ID( 5) := Character'Val (Edx.L1);
20982 Vendor_ID( 6) := Character'Val (Edx.H1);
20983 Vendor_ID( 7) := Character'Val (Edx.L2);
20984 Vendor_ID( 8) := Character'Val (Edx.H2);
20985 Vendor_ID( 9) := Character'Val (Ecx.L1);
20986 Vendor_ID(10) := Character'Val (Ecx.H1);
20987 Vendor_ID(11) := Character'Val (Ecx.L2);
20988 Vendor_ID(12) := Character'Val (Ecx.H2);
20995 -------------------------------
20996 -- Get processor signature --
20997 -------------------------------
20999 function Signature return Processor_Signature is
21001 Result : Processor_Signature;
21002 -- processor signature returned
21006 -- execute CPUID, storing the results in the Result variable
21009 -- the assembler code
21010 "cpuid", -- execute CPUID
21012 -- one is stored in eax
21013 -- processor signature returned in eax
21014 Inputs => Unsigned_32'Asm_input ("a", 1),
21016 -- eax is stored in Result
21017 Outputs => Processor_Signature'Asm_output ("=a", Result),
21019 -- tell compiler that ebx, ecx and edx are also destroyed
21020 Clobber => "ebx, ecx, edx");
21022 -- return processor signature
21027 ------------------------------
21028 -- Get processor features --
21029 ------------------------------
21031 function Features return Processor_Features is
21033 Result : Processor_Features;
21034 -- processor features returned
21038 -- execute CPUID, storing the results in the Result variable
21041 -- the assembler code
21042 "cpuid", -- execute CPUID
21044 -- one stored in eax
21045 -- processor features returned in edx
21046 Inputs => Unsigned_32'Asm_input ("a", 1),
21048 -- edx is stored in Result
21049 Outputs => Processor_Features'Asm_output ("=d", Result),
21051 -- tell compiler that ebx and ecx are also destroyed
21052 Clobber => "ebx, ecx");
21054 -- return processor signature
21061 @c END OF INLINE ASSEMBLER CHAPTER
21062 @c ===============================
21065 @node Microsoft Windows Topics
21066 @chapter Microsoft Windows Topics
21072 This chapter describes topics that are specific to the Microsoft Windows
21073 platforms (NT, 95 and 98).
21076 * Using GNAT on Windows::
21077 * GNAT Setup Tool::
21078 * CONSOLE and WINDOWS subsystems::
21079 * Temporary Files::
21080 * Mixed-Language Programming on Windows::
21081 * Windows Calling Conventions::
21082 * Introduction to Dynamic Link Libraries (DLLs)::
21083 * Using DLLs with GNAT::
21084 * Building DLLs with GNAT::
21085 * GNAT and Windows Resources::
21086 * Debugging a DLL::
21087 * GNAT and COM/DCOM Objects::
21090 @node Using GNAT on Windows
21091 @section Using GNAT on Windows
21094 One of the strengths of the GNAT technology is that its tool set
21095 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
21096 @code{gdb} debugger, etc.) is used in the same way regardless of the
21099 On Windows this tool set is complemented by a number of Microsoft-specific
21100 tools that have been provided to facilitate interoperability with Windows
21101 when this is required. With these tools:
21106 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
21110 You can use any Dynamically Linked Library (DLL) in your Ada code (both
21111 relocatable and non-relocatable DLLs are supported).
21114 You can build Ada DLLs for use in other applications. These applications
21115 can be written in a language other than Ada (e.g., C, C++, etc). Again both
21116 relocatable and non-relocatable Ada DLLs are supported.
21119 You can include Windows resources in your Ada application.
21122 You can use or create COM/DCOM objects.
21126 Immediately below are listed all known general GNAT-for-Windows restrictions.
21127 Other restrictions about specific features like Windows Resources and DLLs
21128 are listed in separate sections below.
21133 It is not possible to use @code{GetLastError} and @code{SetLastError}
21134 when tasking, protected records, or exceptions are used. In these
21135 cases, in order to implement Ada semantics, the GNAT run-time system
21136 calls certain Win32 routines that set the last error variable to 0 upon
21137 success. It should be possible to use @code{GetLastError} and
21138 @code{SetLastError} when tasking, protected record, and exception
21139 features are not used, but it is not guaranteed to work.
21142 @node GNAT Setup Tool
21143 @section GNAT Setup Tool
21144 @cindex GNAT Setup Tool
21149 * Command-line arguments::
21150 * Creating a network installation of GNAT::
21151 * Registering and unregistering additional libraries::
21155 GNAT installation on Windows is using the Windows registry in order to
21156 locate proper executables and standard libraries. GNAT setup tool, called
21157 @code{gnatreg.exe}, is provided in order to display and modify GNAT-specific
21158 registry entries, allowing to create network GNAT installations, modify the
21159 locations of GNAT components, as well as register and unregister additional
21160 libraries for use with GNAT.
21162 @node Command-line arguments
21163 @subsection Command-line arguments
21166 @code{gnatreg [switches] [parameter]}
21169 Specifying no arguments causes gnatreg to display current configuration.
21172 The switches understood by gnatreg are:
21175 print the help message
21177 add a standard library
21179 remove a standard library
21181 force creation of keys if they don't exist
21186 @node Creating a network installation of GNAT
21187 @subsection Creating a network installation of GNAT
21190 Make sure the system on which GNAT is installed is accessible from the
21195 @code{@ @ @ gnatreg -f \\server\sharename\path}
21197 in order to setup the registry entries on a current machine.
21199 For example, if GNAT is installed in @file{\GNAT} directory of a share location
21200 called @file{c-drive} on a machine @file{LOKI}, the command that can be used on
21201 other machines to allow the remote use of GNAT is,
21203 @code{@ @ @ gnatreg -f \\loki\c-drive\gnat}
21205 Remember to also add @file{\\loki\c-drive\gnat\bin} in front of your PATH variable.
21207 Be aware that every compilation using the network installation results in the
21208 transfer of large amounts of data across the network and may cause serious
21209 performance penalty.
21211 @node Registering and unregistering additional libraries
21212 @subsection Registering and unregistering additional libraries
21215 To register a standard library use a command:
21217 @code{@ @ @ gnatreg -a <library_name>=<path>}
21221 @code{@ @ @ gnatreg -a WIN32ADA=c:\Win32Ada}
21223 The libraries registered in this manner will be treated like standard libraries
21224 by the compiler (i.e. they don't have to be specified in -I and -l switches to
21225 various GNAT tools).
21227 To unregister a library, enter
21228 @code{ gnatreg -r <library_name>}
21231 @code{ gnatreg -r WIN32ADA}
21233 @node CONSOLE and WINDOWS subsystems
21234 @section CONSOLE and WINDOWS subsystems
21235 @cindex CONSOLE Subsystem
21236 @cindex WINDOWS Subsystem
21240 Under Windows there is two main subsystems. The @code{CONSOLE} subsystem
21241 (which is the default subsystem) will always create a console when
21242 launching the application. This is not something desirable when the
21243 application has a Windows GUI. To get rid of this console the
21244 application must be using the @code{WINDOWS} subsystem. To do so
21245 the @code{-mwindows} linker option must be specified.
21248 $ gnatmake winprog -largs -mwindows
21251 @node Temporary Files
21252 @section Temporary Files
21253 @cindex Temporary files
21256 It is possible to control where temporary files gets created by setting
21257 the TMP environment variable. The file will be created:
21260 @item Under the directory pointed to by the TMP environment variable if
21261 this directory exists.
21263 @item Under c:\temp, if the TMP environment variable is not set (or not
21264 pointing to a directory) and if this directory exists.
21266 @item Under the current working directory otherwise.
21270 This allows you to determine exactly where the temporary
21271 file will be created. This is particularly useful in networked
21272 environments where you may not have write access to some
21275 @node Mixed-Language Programming on Windows
21276 @section Mixed-Language Programming on Windows
21279 Developing pure Ada applications on Windows is no different than on
21280 other GNAT-supported platforms. However, when developing or porting an
21281 application that contains a mix of Ada and C/C++, the choice of your
21282 Windows C/C++ development environment conditions your overall
21283 interoperability strategy.
21285 If you use @code{gcc} to compile the non-Ada part of your application,
21286 there are no Windows-specific restrictions that affect the overall
21287 interoperability with your Ada code. If you plan to use
21288 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
21289 the following limitations:
21293 You cannot link your Ada code with an object or library generated with
21294 Microsoft tools if these use the @code{.tls} section (Thread Local
21295 Storage section) since the GNAT linker does not yet support this section.
21298 You cannot link your Ada code with an object or library generated with
21299 Microsoft tools if these use I/O routines other than those provided in
21300 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
21301 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
21302 libraries can cause a conflict with @code{msvcrt.dll} services. For
21303 instance Visual C++ I/O stream routines conflict with those in
21308 If you do want to use the Microsoft tools for your non-Ada code and hit one
21309 of the above limitations, you have two choices:
21313 Encapsulate your non Ada code in a DLL to be linked with your Ada
21314 application. In this case, use the Microsoft or whatever environment to
21315 build the DLL and use GNAT to build your executable
21316 (@pxref{Using DLLs with GNAT}).
21319 Or you can encapsulate your Ada code in a DLL to be linked with the
21320 other part of your application. In this case, use GNAT to build the DLL
21321 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
21322 environment to build your executable.
21325 @node Windows Calling Conventions
21326 @section Windows Calling Conventions
21331 * C Calling Convention::
21332 * Stdcall Calling Convention::
21333 * DLL Calling Convention::
21337 When a subprogram @code{F} (caller) calls a subprogram @code{G}
21338 (callee), there are several ways to push @code{G}'s parameters on the
21339 stack and there are several possible scenarios to clean up the stack
21340 upon @code{G}'s return. A calling convention is an agreed upon software
21341 protocol whereby the responsibilities between the caller (@code{F}) and
21342 the callee (@code{G}) are clearly defined. Several calling conventions
21343 are available for Windows:
21347 @code{C} (Microsoft defined)
21350 @code{Stdcall} (Microsoft defined)
21353 @code{DLL} (GNAT specific)
21356 @node C Calling Convention
21357 @subsection @code{C} Calling Convention
21360 This is the default calling convention used when interfacing to C/C++
21361 routines compiled with either @code{gcc} or Microsoft Visual C++.
21363 In the @code{C} calling convention subprogram parameters are pushed on the
21364 stack by the caller from right to left. The caller itself is in charge of
21365 cleaning up the stack after the call. In addition, the name of a routine
21366 with @code{C} calling convention is mangled by adding a leading underscore.
21368 The name to use on the Ada side when importing (or exporting) a routine
21369 with @code{C} calling convention is the name of the routine. For
21370 instance the C function:
21373 int get_val (long);
21377 should be imported from Ada as follows:
21381 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
21382 @b{pragma} Import (C, Get_Val, External_Name => "get_val");
21387 Note that in this particular case the @code{External_Name} parameter could
21388 have been omitted since, when missing, this parameter is taken to be the
21389 name of the Ada entity in lower case. When the @code{Link_Name} parameter
21390 is missing, as in the above example, this parameter is set to be the
21391 @code{External_Name} with a leading underscore.
21393 When importing a variable defined in C, you should always use the @code{C}
21394 calling convention unless the object containing the variable is part of a
21395 DLL (in which case you should use the @code{DLL} calling convention,
21396 @pxref{DLL Calling Convention}).
21398 @node Stdcall Calling Convention
21399 @subsection @code{Stdcall} Calling Convention
21402 This convention, which was the calling convention used for Pascal
21403 programs, is used by Microsoft for all the routines in the Win32 API for
21404 efficiency reasons. It must be used to import any routine for which this
21405 convention was specified.
21407 In the @code{Stdcall} calling convention subprogram parameters are pushed
21408 on the stack by the caller from right to left. The callee (and not the
21409 caller) is in charge of cleaning the stack on routine exit. In addition,
21410 the name of a routine with @code{Stdcall} calling convention is mangled by
21411 adding a leading underscore (as for the @code{C} calling convention) and a
21412 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
21413 bytes) of the parameters passed to the routine.
21415 The name to use on the Ada side when importing a C routine with a
21416 @code{Stdcall} calling convention is the name of the C routine. The leading
21417 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
21418 the compiler. For instance the Win32 function:
21421 @b{APIENTRY} int get_val (long);
21425 should be imported from Ada as follows:
21429 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
21430 @b{pragma} Import (Stdcall, Get_Val);
21431 -- @i{On the x86 a long is 4 bytes, so the Link_Name is }"_get_val@@4"
21436 As for the @code{C} calling convention, when the @code{External_Name}
21437 parameter is missing, it is taken to be the name of the Ada entity in lower
21438 case. If instead of writing the above import pragma you write:
21442 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
21443 @b{pragma} Import (Stdcall, Get_Val, External_Name => "retrieve_val");
21448 then the imported routine is @code{_retrieve_val@@4}. However, if instead
21449 of specifying the @code{External_Name} parameter you specify the
21450 @code{Link_Name} as in the following example:
21454 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
21455 @b{pragma} Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
21460 then the imported routine is @code{retrieve_val@@4}, that is, there is no
21461 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
21462 added at the end of the @code{Link_Name} by the compiler.
21465 Note, that in some special cases a DLL's entry point name lacks a trailing
21466 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
21467 The @code{gnatdll} tool, which creates the import library for the DLL, is able
21468 to handle those cases (see the description of the switches in
21469 @pxref{Using gnatdll} section).
21471 @node DLL Calling Convention
21472 @subsection @code{DLL} Calling Convention
21475 This convention, which is GNAT-specific, must be used when you want to
21476 import in Ada a variables defined in a DLL. For functions and procedures
21477 this convention is equivalent to the @code{Stdcall} convention. As an
21478 example, if a DLL contains a variable defined as:
21485 then, to access this variable from Ada you should write:
21489 My_Var : Interfaces.C.int;
21490 @b{pragma} Import (DLL, My_Var);
21494 The remarks concerning the @code{External_Name} and @code{Link_Name}
21495 parameters given in the previous sections equally apply to the @code{DLL}
21496 calling convention.
21498 @node Introduction to Dynamic Link Libraries (DLLs)
21499 @section Introduction to Dynamic Link Libraries (DLLs)
21503 A Dynamically Linked Library (DLL) is a library that can be shared by
21504 several applications running under Windows. A DLL can contain any number of
21505 routines and variables.
21507 One advantage of DLLs is that you can change and enhance them without
21508 forcing all the applications that depend on them to be relinked or
21509 recompiled. However, you should be aware than all calls to DLL routines are
21510 slower since, as you will understand below, such calls are indirect.
21512 To illustrate the remainder of this section, suppose that an application
21513 wants to use the services of a DLL @file{API.dll}. To use the services
21514 provided by @file{API.dll} you must statically link against an import
21515 library which contains a jump table with an entry for each routine and
21516 variable exported by the DLL. In the Microsoft world this import library is
21517 called @file{API.lib}. When using GNAT this import library is called either
21518 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
21520 After you have statically linked your application with the import library
21521 and you run your application, here is what happens:
21525 Your application is loaded into memory.
21528 The DLL @file{API.dll} is mapped into the address space of your
21529 application. This means that:
21533 The DLL will use the stack of the calling thread.
21536 The DLL will use the virtual address space of the calling process.
21539 The DLL will allocate memory from the virtual address space of the calling
21543 Handles (pointers) can be safely exchanged between routines in the DLL
21544 routines and routines in the application using the DLL.
21548 The entries in the @file{libAPI.a} or @file{API.lib} jump table which is
21549 part of your application are initialized with the addresses of the routines
21550 and variables in @file{API.dll}.
21553 If present in @file{API.dll}, routines @code{DllMain} or
21554 @code{DllMainCRTStartup} are invoked. These routines typically contain
21555 the initialization code needed for the well-being of the routines and
21556 variables exported by the DLL.
21560 There is an additional point which is worth mentioning. In the Windows
21561 world there are two kind of DLLs: relocatable and non-relocatable
21562 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
21563 in the target application address space. If the addresses of two
21564 non-relocatable DLLs overlap and these happen to be used by the same
21565 application, a conflict will occur and the application will run
21566 incorrectly. Hence, when possible, it is always preferable to use and
21567 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
21570 As a side note, an interesting difference between Microsoft DLLs and
21571 Unix shared libraries, is the fact that on most Unix systems all public
21572 routines are exported by default in a Unix shared library, while under
21573 Windows the exported routines must be listed explicitly in a definition
21574 file (@pxref{The Definition File}).
21576 @node Using DLLs with GNAT
21577 @section Using DLLs with GNAT
21580 * Creating an Ada Spec for the DLL Services::
21581 * Creating an Import Library::
21585 To use the services of a DLL, say @file{API.dll}, in your Ada application
21590 The Ada spec for the routines and/or variables you want to access in
21591 @file{API.dll}. If not available this Ada spec must be built from the C/C++
21592 header files provided with the DLL.
21595 The import library (@file{libAPI.a} or @file{API.lib}). As previously
21596 mentioned an import library is a statically linked library containing the
21597 import table which will be filled at load time to point to the actual
21598 @file{API.dll} routines. Sometimes you don't have an import library for the
21599 DLL you want to use. The following sections will explain how to build one.
21602 The actual DLL, @file{API.dll}.
21606 Once you have all the above, to compile an Ada application that uses the
21607 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
21608 you simply issue the command
21611 $ gnatmake my_ada_app -largs -lAPI
21615 The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
21616 tells the GNAT linker to look first for a library named @file{API.lib}
21617 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
21618 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
21619 contains the following pragma
21622 @b{pragma} Linker_Options ("-lAPI");
21626 you do not have to add @code{-largs -lAPI} at the end of the @code{gnatmake}
21629 If any one of the items above is missing you will have to create it
21630 yourself. The following sections explain how to do so using as an
21631 example a fictitious DLL called @file{API.dll}.
21633 @node Creating an Ada Spec for the DLL Services
21634 @subsection Creating an Ada Spec for the DLL Services
21637 A DLL typically comes with a C/C++ header file which provides the
21638 definitions of the routines and variables exported by the DLL. The Ada
21639 equivalent of this header file is a package spec that contains definitions
21640 for the imported entities. If the DLL you intend to use does not come with
21641 an Ada spec you have to generate one such spec yourself. For example if
21642 the header file of @file{API.dll} is a file @file{api.h} containing the
21643 following two definitions:
21655 then the equivalent Ada spec could be:
21660 @b{with} Interfaces.C.Strings;
21661 @b{package} API @b{is}
21662 @b{use} Interfaces;
21665 @b{function} Get (Str : C.Strings.Chars_Ptr) @b{return} C.int;
21668 @b{pragma} Import (C, Get);
21669 @b{pragma} Import (DLL, Some_Var);
21676 Note that a variable is @strong{always imported with a DLL convention}. A
21677 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
21678 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
21679 (@pxref{Windows Calling Conventions}).
21681 @node Creating an Import Library
21682 @subsection Creating an Import Library
21683 @cindex Import library
21686 * The Definition File::
21687 * GNAT-Style Import Library::
21688 * Microsoft-Style Import Library::
21692 If a Microsoft-style import library @file{API.lib} or a GNAT-style
21693 import library @file{libAPI.a} is available with @file{API.dll} you
21694 can skip this section. Otherwise read on.
21696 @node The Definition File
21697 @subsubsection The Definition File
21698 @cindex Definition file
21702 As previously mentioned, and unlike Unix systems, the list of symbols
21703 that are exported from a DLL must be provided explicitly in Windows.
21704 The main goal of a definition file is precisely that: list the symbols
21705 exported by a DLL. A definition file (usually a file with a @code{.def}
21706 suffix) has the following structure:
21712 [DESCRIPTION @i{string}]
21722 @item LIBRARY @i{name}
21723 This section, which is optional, gives the name of the DLL.
21725 @item DESCRIPTION @i{string}
21726 This section, which is optional, gives a description string that will be
21727 embedded in the import library.
21730 This section gives the list of exported symbols (procedures, functions or
21731 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
21732 section of @file{API.def} looks like:
21746 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
21747 (@pxref{Windows Calling Conventions}) for a Stdcall
21748 calling convention function in the exported symbols list.
21751 There can actually be other sections in a definition file, but these
21752 sections are not relevant to the discussion at hand.
21754 @node GNAT-Style Import Library
21755 @subsubsection GNAT-Style Import Library
21758 To create a static import library from @file{API.dll} with the GNAT tools
21759 you should proceed as follows:
21763 Create the definition file @file{API.def} (@pxref{The Definition File}).
21764 For that use the @code{dll2def} tool as follows:
21767 $ dll2def API.dll > API.def
21771 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
21772 to standard output the list of entry points in the DLL. Note that if
21773 some routines in the DLL have the @code{Stdcall} convention
21774 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
21775 suffix then you'll have to edit @file{api.def} to add it.
21778 Here are some hints to find the right @code{@@}@i{nn} suffix.
21782 If you have the Microsoft import library (.lib), it is possible to get
21783 the right symbols by using Microsoft @code{dumpbin} tool (see the
21784 corresponding Microsoft documentation for further details).
21787 $ dumpbin /exports api.lib
21791 If you have a message about a missing symbol at link time the compiler
21792 tells you what symbol is expected. You just have to go back to the
21793 definition file and add the right suffix.
21797 Build the import library @code{libAPI.a}, using @code{gnatdll}
21798 (@pxref{Using gnatdll}) as follows:
21801 $ gnatdll -e API.def -d API.dll
21805 @code{gnatdll} takes as input a definition file @file{API.def} and the
21806 name of the DLL containing the services listed in the definition file
21807 @file{API.dll}. The name of the static import library generated is
21808 computed from the name of the definition file as follows: if the
21809 definition file name is @i{xyz}@code{.def}, the import library name will
21810 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
21811 @code{-e} could have been removed because the name of the definition
21812 file (before the "@code{.def}" suffix) is the same as the name of the
21813 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
21816 @node Microsoft-Style Import Library
21817 @subsubsection Microsoft-Style Import Library
21820 With GNAT you can either use a GNAT-style or Microsoft-style import
21821 library. A Microsoft import library is needed only if you plan to make an
21822 Ada DLL available to applications developed with Microsoft
21823 tools (@pxref{Mixed-Language Programming on Windows}).
21825 To create a Microsoft-style import library for @file{API.dll} you
21826 should proceed as follows:
21830 Create the definition file @file{API.def} from the DLL. For this use either
21831 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
21832 tool (see the corresponding Microsoft documentation for further details).
21835 Build the actual import library using Microsoft's @code{lib} utility:
21838 $ lib -machine:IX86 -def:API.def -out:API.lib
21842 If you use the above command the definition file @file{API.def} must
21843 contain a line giving the name of the DLL:
21850 See the Microsoft documentation for further details about the usage of
21854 @node Building DLLs with GNAT
21855 @section Building DLLs with GNAT
21856 @cindex DLLs, building
21859 * Limitations When Using Ada DLLs from Ada::
21860 * Exporting Ada Entities::
21861 * Ada DLLs and Elaboration::
21862 * Ada DLLs and Finalization::
21863 * Creating a Spec for Ada DLLs::
21864 * Creating the Definition File::
21869 This section explains how to build DLLs containing Ada code. These DLLs
21870 will be referred to as Ada DLLs in the remainder of this section.
21872 The steps required to build an Ada DLL that is to be used by Ada as well as
21873 non-Ada applications are as follows:
21877 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
21878 @code{Stdcall} calling convention to avoid any Ada name mangling for the
21879 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
21880 skip this step if you plan to use the Ada DLL only from Ada applications.
21883 Your Ada code must export an initialization routine which calls the routine
21884 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
21885 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
21886 routine exported by the Ada DLL must be invoked by the clients of the DLL
21887 to initialize the DLL.
21890 When useful, the DLL should also export a finalization routine which calls
21891 routine @code{adafinal} generated by @code{gnatbind} to perform the
21892 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
21893 The finalization routine exported by the Ada DLL must be invoked by the
21894 clients of the DLL when the DLL services are no further needed.
21897 You must provide a spec for the services exported by the Ada DLL in each
21898 of the programming languages to which you plan to make the DLL available.
21901 You must provide a definition file listing the exported entities
21902 (@pxref{The Definition File}).
21905 Finally you must use @code{gnatdll} to produce the DLL and the import
21906 library (@pxref{Using gnatdll}).
21909 @node Limitations When Using Ada DLLs from Ada
21910 @subsection Limitations When Using Ada DLLs from Ada
21913 When using Ada DLLs from Ada applications there is a limitation users
21914 should be aware of. Because on Windows the GNAT run time is not in a DLL of
21915 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
21916 each Ada DLL includes the services of the GNAT run time that are necessary
21917 to the Ada code inside the DLL. As a result, when an Ada program uses an
21918 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
21919 one in the main program.
21921 It is therefore not possible to exchange GNAT run-time objects between the
21922 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
21923 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
21926 It is completely safe to exchange plain elementary, array or record types,
21927 Windows object handles, etc.
21929 @node Exporting Ada Entities
21930 @subsection Exporting Ada Entities
21931 @cindex Export table
21934 Building a DLL is a way to encapsulate a set of services usable from any
21935 application. As a result, the Ada entities exported by a DLL should be
21936 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
21937 any Ada name mangling. Please note that the @code{Stdcall} convention
21938 should only be used for subprograms, not for variables. As an example here
21939 is an Ada package @code{API}, spec and body, exporting two procedures, a
21940 function, and a variable:
21945 @b{with} Interfaces.C; @b{use} Interfaces;
21946 @b{package} API @b{is}
21947 Count : C.int := 0;
21948 @b{function} Factorial (Val : C.int) @b{return} C.int;
21950 @b{procedure} Initialize_API;
21951 @b{procedure} Finalize_API;
21952 -- @i{Initialization & Finalization routines. More in the next section.}
21954 @b{pragma} Export (C, Initialize_API);
21955 @b{pragma} Export (C, Finalize_API);
21956 @b{pragma} Export (C, Count);
21957 @b{pragma} Export (C, Factorial);
21966 @b{package body} API @b{is}
21967 @b{function} Factorial (Val : C.int) @b{return} C.int @b{is}
21970 Count := Count + 1;
21971 @b{for} K @b{in} 1 .. Val @b{loop}
21977 @b{procedure} Initialize_API @b{is}
21978 @b{procedure} Adainit;
21979 @b{pragma} Import (C, Adainit);
21982 @b{end} Initialize_API;
21984 @b{procedure} Finalize_API @b{is}
21985 @b{procedure} Adafinal;
21986 @b{pragma} Import (C, Adafinal);
21989 @b{end} Finalize_API;
21996 If the Ada DLL you are building will only be used by Ada applications
21997 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
21998 convention. As an example, the previous package could be written as
22004 @b{package} API @b{is}
22005 Count : Integer := 0;
22006 @b{function} Factorial (Val : Integer) @b{return} Integer;
22008 @b{procedure} Initialize_API;
22009 @b{procedure} Finalize_API;
22010 -- @i{Initialization and Finalization routines.}
22019 @b{package body} API @b{is}
22020 @b{function} Factorial (Val : Integer) @b{return} Integer @b{is}
22021 Fact : Integer := 1;
22023 Count := Count + 1;
22024 @b{for} K @b{in} 1 .. Val @b{loop}
22031 -- @i{The remainder of this package body is unchanged.}
22038 Note that if you do not export the Ada entities with a @code{C} or
22039 @code{Stdcall} convention you will have to provide the mangled Ada names
22040 in the definition file of the Ada DLL
22041 (@pxref{Creating the Definition File}).
22043 @node Ada DLLs and Elaboration
22044 @subsection Ada DLLs and Elaboration
22045 @cindex DLLs and elaboration
22048 The DLL that you are building contains your Ada code as well as all the
22049 routines in the Ada library that are needed by it. The first thing a
22050 user of your DLL must do is elaborate the Ada code
22051 (@pxref{Elaboration Order Handling in GNAT}).
22053 To achieve this you must export an initialization routine
22054 (@code{Initialize_API} in the previous example), which must be invoked
22055 before using any of the DLL services. This elaboration routine must call
22056 the Ada elaboration routine @code{adainit} generated by the GNAT binder
22057 (@pxref{Binding with Non-Ada Main Programs}). See the body of
22058 @code{Initialize_Api} for an example. Note that the GNAT binder is
22059 automatically invoked during the DLL build process by the @code{gnatdll}
22060 tool (@pxref{Using gnatdll}).
22062 When a DLL is loaded, Windows systematically invokes a routine called
22063 @code{DllMain}. It would therefore be possible to call @code{adainit}
22064 directly from @code{DllMain} without having to provide an explicit
22065 initialization routine. Unfortunately, it is not possible to call
22066 @code{adainit} from the @code{DllMain} if your program has library level
22067 tasks because access to the @code{DllMain} entry point is serialized by
22068 the system (that is, only a single thread can execute "through" it at a
22069 time), which means that the GNAT run time will deadlock waiting for the
22070 newly created task to complete its initialization.
22072 @node Ada DLLs and Finalization
22073 @subsection Ada DLLs and Finalization
22074 @cindex DLLs and finalization
22077 When the services of an Ada DLL are no longer needed, the client code should
22078 invoke the DLL finalization routine, if available. The DLL finalization
22079 routine is in charge of releasing all resources acquired by the DLL. In the
22080 case of the Ada code contained in the DLL, this is achieved by calling
22081 routine @code{adafinal} generated by the GNAT binder
22082 (@pxref{Binding with Non-Ada Main Programs}).
22083 See the body of @code{Finalize_Api} for an
22084 example. As already pointed out the GNAT binder is automatically invoked
22085 during the DLL build process by the @code{gnatdll} tool
22086 (@pxref{Using gnatdll}).
22089 @cindex @code{-g} (@code{gnatdll})
22091 Generate debugging information. This information is stored in the object
22092 file and copied from there to the final DLL file by the linker,
22093 where it can be read by the debugger. You must use the
22094 @code{-g} switch if you plan on using the debugger or the symbolic
22097 @node Creating a Spec for Ada DLLs
22098 @subsection Creating a Spec for Ada DLLs
22101 To use the services exported by the Ada DLL from another programming
22102 language (e.g. C), you have to translate the specs of the exported Ada
22103 entities in that language. For instance in the case of @code{API.dll},
22104 the corresponding C header file could look like:
22109 extern int *__imp__count;
22110 #define count (*__imp__count)
22111 int factorial (int);
22117 It is important to understand that when building an Ada DLL to be used by
22118 other Ada applications, you need two different specs for the packages
22119 contained in the DLL: one for building the DLL and the other for using
22120 the DLL. This is because the @code{DLL} calling convention is needed to
22121 use a variable defined in a DLL, but when building the DLL, the variable
22122 must have either the @code{Ada} or @code{C} calling convention. As an
22123 example consider a DLL comprising the following package @code{API}:
22128 @b{package} API @b{is}
22129 Count : Integer := 0;
22131 -- @i{Remainder of the package omitted.}
22138 After producing a DLL containing package @code{API}, the spec that
22139 must be used to import @code{API.Count} from Ada code outside of the
22145 @b{package} API @b{is}
22147 @b{pragma} Import (DLL, Count);
22153 @node Creating the Definition File
22154 @subsection Creating the Definition File
22157 The definition file is the last file needed to build the DLL. It lists
22158 the exported symbols. As an example, the definition file for a DLL
22159 containing only package @code{API} (where all the entities are exported
22160 with a @code{C} calling convention) is:
22175 If the @code{C} calling convention is missing from package @code{API},
22176 then the definition file contains the mangled Ada names of the above
22177 entities, which in this case are:
22186 api__initialize_api
22191 @node Using gnatdll
22192 @subsection Using @code{gnatdll}
22196 * gnatdll Example::
22197 * gnatdll behind the Scenes::
22202 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
22203 and non-Ada sources that make up your DLL have been compiled.
22204 @code{gnatdll} is actually in charge of two distinct tasks: build the
22205 static import library for the DLL and the actual DLL. The form of the
22206 @code{gnatdll} command is
22210 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
22215 where @i{list-of-files} is a list of ALI and object files. The object
22216 file list must be the exact list of objects corresponding to the non-Ada
22217 sources whose services are to be included in the DLL. The ALI file list
22218 must be the exact list of ALI files for the corresponding Ada sources
22219 whose services are to be included in the DLL. If @i{list-of-files} is
22220 missing, only the static import library is generated.
22223 You may specify any of the following switches to @code{gnatdll}:
22226 @item -a[@var{address}]
22227 @cindex @code{-a} (@code{gnatdll})
22228 Build a non-relocatable DLL at @var{address}. If @var{address} is not
22229 specified the default address @var{0x11000000} will be used. By default,
22230 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
22231 advise the reader to build relocatable DLL.
22233 @item -b @var{address}
22234 @cindex @code{-b} (@code{gnatdll})
22235 Set the relocatable DLL base address. By default the address is
22238 @item -d @var{dllfile}
22239 @cindex @code{-d} (@code{gnatdll})
22240 @var{dllfile} is the name of the DLL. This switch must be present for
22241 @code{gnatdll} to do anything. The name of the generated import library is
22242 obtained algorithmically from @var{dllfile} as shown in the following
22243 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
22244 @code{libxyz.a}. The name of the definition file to use (if not specified
22245 by option @code{-e}) is obtained algorithmically from @var{dllfile} as shown in
22246 the following example: if @var{dllfile} is @code{xyz.dll}, the definition
22247 file used is @code{xyz.def}.
22249 @item -e @var{deffile}
22250 @cindex @code{-e} (@code{gnatdll})
22251 @var{deffile} is the name of the definition file.
22254 @cindex @code{-h} (@code{gnatdll})
22255 Help mode. Displays @code{gnatdll} switch usage information.
22258 Direct @code{gnatdll} to search the @var{dir} directory for source and
22259 object files needed to build the DLL.
22260 (@pxref{Search Paths and the Run-Time Library (RTL)}).
22263 Removes the @code{@@}@i{nn} suffix from the import library's exported
22264 names. You must specified this option if you want to use a
22265 @code{Stdcall} function in a DLL for which the @code{@@}@i{nn} suffix
22266 has been removed. This is the case for most of the Windows NT DLL for
22267 example. This option has no effect when @code{-n} option is specified.
22269 @item -l @var{file}
22270 @cindex @code{-l} (@code{gnatdll})
22271 The list of ALI and object files used to build the DLL are listed in
22272 @var{file}, instead of being given in the command line. Each line in
22273 @var{file} contains the name of an ALI or object file.
22276 @cindex @code{-n} (@code{gnatdll})
22277 No Import. Do not create the import library.
22280 @cindex @code{-q} (@code{gnatdll})
22281 Quiet mode. Do not display unnecessary messages.
22284 @cindex @code{-v} (@code{gnatdll})
22285 Verbose mode. Display extra information.
22287 @item -largs @var{opts}
22288 @cindex @code{-largs} (@code{gnatdll})
22289 Linker options. Pass @var{opts} to the linker.
22292 @node gnatdll Example
22293 @subsubsection @code{gnatdll} Example
22296 As an example the command to build a relocatable DLL from @file{api.adb}
22297 once @file{api.adb} has been compiled and @file{api.def} created is
22300 $ gnatdll -d api.dll api.ali
22304 The above command creates two files: @file{libapi.a} (the import
22305 library) and @file{api.dll} (the actual DLL). If you want to create
22306 only the DLL, just type:
22309 $ gnatdll -d api.dll -n api.ali
22313 Alternatively if you want to create just the import library, type:
22316 $ gnatdll -d api.dll
22319 @node gnatdll behind the Scenes
22320 @subsubsection @code{gnatdll} behind the Scenes
22323 This section details the steps involved in creating a DLL. @code{gnatdll}
22324 does these steps for you. Unless you are interested in understanding what
22325 goes on behind the scenes, you should skip this section.
22327 We use the previous example of a DLL containing the Ada package @code{API},
22328 to illustrate the steps necessary to build a DLL. The starting point is a
22329 set of objects that will make up the DLL and the corresponding ALI
22330 files. In the case of this example this means that @file{api.o} and
22331 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
22336 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
22337 the information necessary to generate relocation information for the
22343 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
22348 In addition to the base file, the @code{gnatlink} command generates an
22349 output file @file{api.jnk} which can be discarded. The @code{-mdll} switch
22350 asks @code{gnatlink} to generate the routines @code{DllMain} and
22351 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
22352 is loaded into memory.
22355 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
22356 export table (@file{api.exp}). The export table contains the relocation
22357 information in a form which can be used during the final link to ensure
22358 that the Windows loader is able to place the DLL anywhere in memory.
22362 $ dlltool --dllname api.dll --def api.def --base-file api.base \
22363 --output-exp api.exp
22368 @code{gnatdll} builds the base file using the new export table. Note that
22369 @code{gnatbind} must be called once again since the binder generated file
22370 has been deleted during the previous call to @code{gnatlink}.
22375 $ gnatlink api -o api.jnk api.exp -mdll
22376 -Wl,--base-file,api.base
22381 @code{gnatdll} builds the new export table using the new base file and
22382 generates the DLL import library @file{libAPI.a}.
22386 $ dlltool --dllname api.dll --def api.def --base-file api.base \
22387 --output-exp api.exp --output-lib libAPI.a
22392 Finally @code{gnatdll} builds the relocatable DLL using the final export
22398 $ gnatlink api api.exp -o api.dll -mdll
22403 @node Using dlltool
22404 @subsubsection Using @code{dlltool}
22407 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
22408 DLLs and static import libraries. This section summarizes the most
22409 common @code{dlltool} switches. The form of the @code{dlltool} command
22413 $ dlltool [@var{switches}]
22417 @code{dlltool} switches include:
22420 @item --base-file @var{basefile}
22421 Read the base file @var{basefile} generated by the linker. This switch
22422 is used to create a relocatable DLL.
22424 @item --def @var{deffile}
22425 Read the definition file.
22427 @item --dllname @var{name}
22428 Gives the name of the DLL. This switch is used to embed the name of the
22429 DLL in the static import library generated by @code{dlltool} with switch
22430 @code{--output-lib}.
22433 Kill @code{@@}@i{nn} from exported names
22434 (@pxref{Windows Calling Conventions}
22435 for a discussion about @code{Stdcall}-style symbols.
22438 Prints the @code{dlltool} switches with a concise description.
22440 @item --output-exp @var{exportfile}
22441 Generate an export file @var{exportfile}. The export file contains the
22442 export table (list of symbols in the DLL) and is used to create the DLL.
22444 @item --output-lib @i{libfile}
22445 Generate a static import library @var{libfile}.
22450 @item --as @i{assembler-name}
22451 Use @i{assembler-name} as the assembler. The default is @code{as}.
22454 @node GNAT and Windows Resources
22455 @section GNAT and Windows Resources
22456 @cindex Resources, windows
22459 * Building Resources::
22460 * Compiling Resources::
22461 * Using Resources::
22466 Resources are an easy way to add Windows specific objects to your
22467 application. The objects that can be added as resources include:
22496 This section explains how to build, compile and use resources.
22498 @node Building Resources
22499 @subsection Building Resources
22500 @cindex Resources, building
22503 A resource file is an ASCII file. By convention resource files have an
22504 @file{.rc} extension.
22505 The easiest way to build a resource file is to use Microsoft tools
22506 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
22507 @code{dlgedit.exe} to build dialogs.
22508 It is always possible to build an @file{.rc} file yourself by writing a
22511 It is not our objective to explain how to write a resource file. A
22512 complete description of the resource script language can be found in the
22513 Microsoft documentation.
22515 @node Compiling Resources
22516 @subsection Compiling Resources
22520 @cindex Resources, compiling
22523 This section describes how to build a GNAT-compatible (COFF) object file
22524 containing the resources. This is done using the Resource Compiler
22525 @code{rcl} as follows:
22528 $ rcl -i myres.rc -o myres.o
22532 By default @code{rcl} will run @code{gcc} to preprocess the @file{.rc}
22533 file. You can specify an alternate preprocessor (usually named
22534 @file{cpp.exe}) using the @code{rcl} @code{-cpp} parameter. A list of
22535 all possible options may be obtained by entering the command @code{rcl}
22536 with no parameters.
22538 It is also possible to use the Microsoft resource compiler @code{rc.exe}
22539 to produce a @file{.res} file (binary resource file). See the
22540 corresponding Microsoft documentation for further details. In this case
22541 you need to use @code{res2coff} to translate the @file{.res} file to a
22542 GNAT-compatible object file as follows:
22545 $ res2coff -i myres.res -o myres.o
22548 @node Using Resources
22549 @subsection Using Resources
22550 @cindex Resources, using
22553 To include the resource file in your program just add the
22554 GNAT-compatible object file for the resource(s) to the linker
22555 arguments. With @code{gnatmake} this is done by using the @code{-largs}
22559 $ gnatmake myprog -largs myres.o
22563 @subsection Limitations
22564 @cindex Resources, limitations
22567 In this section we describe the current limitations together with
22568 suggestions for workarounds.
22572 @code{rcl} does not handle the @code{RCINCLUDE} directive.
22574 Workaround: replace @code{RCINCLUDE} by an @code{#include} directive.
22577 @code{rcl} does not handle the brackets as block delimiters.
22579 Workaround: replace character '@{' by @code{BEGIN} and '@}' by
22580 @code{END}. Note that Microsoft's @code{rc} handles both forms of block
22584 @code{rcl} does not handle @code{TypeLib} resources. This type of
22585 resource is used to build COM, DCOM or ActiveX objects.
22587 Workaround: use @code{rc}, the Microsoft resource compiler.
22590 It is not possible to use @code{strip} to remove the debugging symbols
22591 from a program with resources.
22593 Workaround: use linker option @code{-s} to strip debugging symbols from
22594 the final executable.
22597 @node Debugging a DLL
22598 @section Debugging a DLL
22599 @cindex DLL debugging
22602 * The Program and the DLL Are Built with GCC/GNAT::
22603 * The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT::
22607 Debugging a DLL is similar to debugging a standard program. But
22608 we have to deal with two different executable parts: the DLL and the
22609 program that uses it. We have the following four possibilities:
22613 The program and the DLL are built with @code{GCC/GNAT}.
22615 The program is built with foreign tools and the DLL is built with
22618 The program is built with @code{GCC/GNAT} and the DLL is built with
22624 In this section we address only cases one and two above.
22625 There is no point in trying to debug
22626 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
22627 information in it. To do so you must use a debugger compatible with the
22628 tools suite used to build the DLL.
22630 @node The Program and the DLL Are Built with GCC/GNAT
22631 @subsection The Program and the DLL Are Built with GCC/GNAT
22634 This is the simplest case. Both the DLL and the program have @code{GDB}
22635 compatible debugging information. It is then possible to break anywhere in
22636 the process. Let's suppose here that the main procedure is named
22637 @code{ada_main} and that in the DLL there is an entry point named
22641 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
22642 program must have been built with the debugging information (see GNAT -g
22643 switch). Here are the step-by-step instructions for debugging it:
22646 @item Launch @code{GDB} on the main program.
22652 @item Break on the main procedure and run the program.
22655 (gdb) break ada_main
22660 This step is required to be able to set a breakpoint inside the DLL. As long
22661 as the program is not run, the DLL is not loaded. This has the
22662 consequence that the DLL debugging information is also not loaded, so it is not
22663 possible to set a breakpoint in the DLL.
22665 @item Set a breakpoint inside the DLL
22668 (gdb) break ada_dll
22675 At this stage a breakpoint is set inside the DLL. From there on
22676 you can use the standard approach to debug the whole program
22677 (@pxref{Running and Debugging Ada Programs}).
22679 @node The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT
22680 @subsection The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT
22683 * Debugging the DLL Directly::
22684 * Attaching to a Running Process::
22688 In this case things are slightly more complex because it is not possible to
22689 start the main program and then break at the beginning to load the DLL and the
22690 associated DLL debugging information. It is not possible to break at the
22691 beginning of the program because there is no @code{GDB} debugging information,
22692 and therefore there is no direct way of getting initial control. This
22693 section addresses this issue by describing some methods that can be used
22694 to break somewhere in the DLL to debug it.
22697 First suppose that the main procedure is named @code{main} (this is for
22698 example some C code built with Microsoft Visual C) and that there is a
22699 DLL named @code{test.dll} containing an Ada entry point named
22703 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
22704 been built with debugging information (see GNAT -g option).
22706 @node Debugging the DLL Directly
22707 @subsubsection Debugging the DLL Directly
22711 Launch the debugger on the DLL.
22717 @item Set a breakpoint on a DLL subroutine.
22720 (gdb) break ada_dll
22724 Specify the executable file to @code{GDB}.
22727 (gdb) exec-file main.exe
22738 This will run the program until it reaches the breakpoint that has been
22739 set. From that point you can use the standard way to debug a program
22740 as described in (@pxref{Running and Debugging Ada Programs}).
22745 It is also possible to debug the DLL by attaching to a running process.
22747 @node Attaching to a Running Process
22748 @subsubsection Attaching to a Running Process
22749 @cindex DLL debugging, attach to process
22752 With @code{GDB} it is always possible to debug a running process by
22753 attaching to it. It is possible to debug a DLL this way. The limitation
22754 of this approach is that the DLL must run long enough to perform the
22755 attach operation. It may be useful for instance to insert a time wasting
22756 loop in the code of the DLL to meet this criterion.
22760 @item Launch the main program @file{main.exe}.
22766 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
22767 that the process PID for @file{main.exe} is 208.
22775 @item Attach to the running process to be debugged.
22781 @item Load the process debugging information.
22784 (gdb) symbol-file main.exe
22787 @item Break somewhere in the DLL.
22790 (gdb) break ada_dll
22793 @item Continue process execution.
22802 This last step will resume the process execution, and stop at
22803 the breakpoint we have set. From there you can use the standard
22804 approach to debug a program as described in
22805 (@pxref{Running and Debugging Ada Programs}).
22807 @node GNAT and COM/DCOM Objects
22808 @section GNAT and COM/DCOM Objects
22813 This section is temporarily left blank.
22817 ???????????? WE NEED TO DECIDE WHETHER TO DISTRIBUTE IT ??????????????????????
22819 @node gnatreg : Registry Tool for NT
22820 @section @code{gnatreg} : Registry Tool for NT
22825 * Changing the GNAT compiler to Use::
22826 * Adding/Changing a Library Path::
22827 * Removing a Library Path::
22828 * List Current Configuration::
22832 This tool can be used to switch from one compiler to another and to manage
22833 the list of directories where GNAT must look to find packages. It is
22834 also a convenient way to do network installation of GNAT.
22836 The form of the @code{gnatreg} command is
22839 $ gnatreg [@var{-hqcarf}] parameter
22843 Commons options are
22848 print a usage message.
22851 quiet/terse - display nothing, just do the job.
22854 force mode - create the registry keys if they do not
22855 exist. @code{gnatreg} will exit with an error if this option is omitted
22856 and some registry keys are not setup correctly.
22860 @subsection Changing the GNAT compiler to use
22863 $ gnatreg c:\gnatpro
22867 This will setup the registry to use the GNAT compiler that has been
22868 installed under c:\gnatpro. @code{gnatreg} check that this directory contain
22869 effectively a GNAT compiler. If you want to setup a network installation
22870 and if GNAT has never been installed on this computer you'll have to use
22873 @subsection Adding/Changing a library path
22876 $ gnatreg -a COMPNT=c:\ada\components
22880 Add the directory c:\ada\components to the list of standards libraries. When
22881 running gnatmake the option -Ic:\ada\components is added automatically to the
22884 The directory c:\ada\components is associated with the name COMPNT. This
22885 name will be used to remove the library path.
22887 @subsection Removing a library path
22890 $ gnatreg -r COMPNT
22894 Remove the library path named COMPNT.
22896 @subsection List current configuration
22903 @code{gnatreg} will display the GNAT and AdaGIDE path used and
22904 all the standards libraries and their associated names that have been set.
22910 @node VxWorks Topics
22911 @chapter VxWorks Topics
22914 This chapter describes topics that are specific to the GNAT for VxWorks
22918 * Kernel Configuration for VxWorks::
22919 * Kernel Compilation Issues for VxWorks::
22920 * Handling Relocation Issues for PowerPc Targets::
22921 * Support for Software Floating Point on PowerPC Processors::
22922 * Interrupt Handling for VxWorks::
22923 * Simulating Command Line Arguments for VxWorks::
22924 * Debugging Issues for VxWorks::
22925 * Using GNAT from the Tornado 2 Project Facility::
22926 * Frequently Asked Questions for VxWorks::
22929 @node Kernel Configuration for VxWorks
22930 @section Kernel Configuration for VxWorks
22933 When configuring your VxWorks kernel we recommend including the target
22934 shell. If you omit it from the configuration, you may get undefined
22935 symbols at load time, e.g.
22945 Generally, such undefined symbols are harmless since these are used by
22946 optional parts of the GNAT run time. However if running your application
22947 generates a VxWorks exception or illegal instruction, you should reconfigure
22948 your kernel to resolve these symbols.
22950 @node Kernel Compilation Issues for VxWorks
22951 @section Kernel Compilation Issues for VxWorks
22954 If you plan to link an Ada module with a Tornado 2 Kernel, follow these steps.
22955 (Note that these recommendations apply to @file{cygnus-2.7.2-960126},
22956 shipped with Tornado 2 as the C compiler toolchain.)
22960 Compile your Ada module without linking it with the VxWorks Library:
22962 gnatmake foo.adb -largs -nostdlib
22966 Edit your makefile and add on the @code{LIBS} line the exact path and name
22967 of the GCC library file provided with GNAT.
22969 LIBS = $(WIND_BASE)/target/lib/libPPC604gnuvx.a \
22970 /opt/gnu/gnat/lib/gcc-lib/powerpc-wrs-vxworks/2.8.1/libgcc.a
22974 To know the exact name and location of this file, type
22975 @code{<arch>-gcc -print-libgcc-file-name} in a console. Note that this version of GCC is the
22976 one provided with GNAT.
22978 ~ >powerpc-wrs-vxworks-gcc -print-libgcc-file-name
22979 /opt/gnu/gnat/lib/gcc-lib/powerpc-wrs-vxworks/2.8.1/libgcc.a
22984 @node Handling Relocation Issues for PowerPc Targets
22985 @section Handling Relocation Issues for PowerPc Targets
22986 @cindex Relocation issues for PowerPc VxWorks targets
22987 @cindex PowerPc VxWorks, relocation issues
22988 @cindex VxWorks PowerPc, relocation issues
22991 Under certain circumstances, loading a program onto a PowerPC
22992 board will fail with the message
22993 @emph{Relocation value does not fit in 24 bits}.
22995 For some background on this issue, please refer to WRS' SPRs
22996 6040, 20257, and 22767.
22998 VxWorks on the PowerPC follows the variation of the SVR4 ABI known
22999 as the Embedded ABI (@emph{EABI}).
23000 @cindex Embedded ABI (for VxWorks on PowerPc)
23001 @cindex EABI (for VxWorks on PowerPc)
23002 In order to save space and time in
23003 embedded applications, the EABI specifies that the default for
23004 subprogram calls should be the branch instruction with relative
23005 addressing using an immediate operand. The immediate operand
23006 to this instruction (relative address) is 24 bits wide. It
23007 is sign extended and 2#00# is appended for the last 2 bits (all
23008 instructions must be on a 4 byte boundary).
23010 26 bit offset means that the target of the branch must be within
23011 +/- 32 Mbytes of the relative branch instruction. When VxWorks
23012 is loading a program it completes the linking phase by
23013 resolving all of the unresolved references in the object being
23014 loaded. When one of those references is a relative address in
23015 a branch instruction, and the linker determines that the target
23016 is more than 32 Mbytes away from the branch, the error occurs.
23018 This only happens when the BSP is configured to use
23019 more than 32 MBytes of memory. The VxWorks kernel is loaded into
23020 low memory addresses, and the error usually occurs when the target
23021 loader is used (because it loads objects into high memory, and thus
23022 calls from the program to the VxWorks kernel can be too far).
23023 @cindex VxWorks kernel (relocation issues on PowerPc)
23025 One way to solve this problem is to use the Tornado
23026 host loader; this will place programs in low memory, close to the kernel.
23028 Another approach is to make use of the @code{-mlongcall} option to the
23030 @cindex @code{-mlongcall} (gcc)
23031 GNAT has incorporated WRS'
23032 gcc modification that implements this option.
23033 If a subprogram call is
23034 compiled with the @code{-mlongcall} option, then the generated code
23035 constructs an absolute address in a register and uses a branch
23036 instruction with absolute addressing mode.
23038 Starting with release 3.15, the GNAT runtime libraries that are
23039 distributed are compiled with the @code{-mlongcall} option. In many
23040 cases the use of these libraries is sufficient to avoid the
23041 relocation problem, since it is the runtime library that contains
23042 calls to the VxWorks kernel that need to span the address space gap.
23043 If you are using an earlier GNAT release or a manually-built runtime,
23044 you should recompile the GNAT runtime library with @code{-mlongcall};
23046 @file{Makefile.adalib} file from the @file{adalib} directory.
23048 Application code may need to be compiled with @code{-mlongcall} if there
23049 are calls directly to the kernel, the application is very large,
23050 or in some specialized linking/loading scenarios.
23052 You can compile individual files with @code{-mlongcall} by placing this
23053 option on the @code{gcc} command line (for brevity we are omitting the
23054 @code{powerpc-wrs-vxworks-} prefix on the commands shown in this
23056 If you provide @code{-mlongcall} as an option for @code{gnatmake}, it will be
23057 passed to all invocations of @code{gcc} that @code{gnatmake} directly performs.
23058 Note that one other compilation is made by @code{gnatlink}, on the file created
23059 by @code{gnatbind} for the elaboration package body
23060 (see @ref{Binding Using gnatbind}).
23061 Passing @code{-mlongcall} to @code{gnatlink}, either directly
23062 on the @code{gnatlink} command line or by including @code{-mlongcall} in the
23063 @code{-largs} list of @code{gnatmake}, will direct @code{gnatlink} to compile the
23064 binder file with the @code{-mlongcall} option.
23066 To see the effect of @code{-mlongcall}, consider the following small example:
23070 procedure Imported_Proc;
23071 pragma Import (Ada, Imported_Proc);
23078 If you compile @code{Proc} with the default options (no @code{-mlongcall}), the following code is generated:
23088 In contrast, here is the result with the @code{-mlongcall} option:
23093 addis 9,0,imported_proc@@ha
23094 addi 0,9,imported_proc@@l
23101 @node Support for Software Floating Point on PowerPC Processors
23102 @section Support for Software Floating Point on PowerPC Processors
23105 The PowerPC 860 processor does not have hardware floating-point support.
23106 In order to build and run GNAT modules properly, you need to install and
23107 invoke software-emulated floating-point support as follows:
23111 At installation time:
23114 Create a file @file{ada_object_path} under the directory
23115 @file{BASE\lib\gcc-lib\powerpc-wrs-vxworks\2.8.1}
23116 (by default @file{BASE}=@file{c:\gnatpro})
23117 containing the following line:
23119 rts-soft-float\adalib
23123 Create a file @file{ada_source_path} under the directory
23124 @file{BASE\lib\gcc-lib\powerpc-wrs-vxworks\2.8.1}
23125 (by default @file{BASE}=@file{c:\gnatpro})
23126 containing the following line:
23128 rts-soft-float\adainclude
23133 When using the compiler, specify @option{-msoft-float}
23134 as a compiler and a linker option, e.g.:
23136 $powerpc-wrs-vxworks-gnatmake -msoft-float module -largs -msoft-float
23141 @node Interrupt Handling for VxWorks
23142 @section Interrupt Handling for VxWorks
23145 GNAT offers a range of options for hardware interrupt handling. In rough
23146 order of latency and lack of restrictions:
23149 @item Directly vectored interrupt procedure handlers
23150 @item Directly vectored interrupt procedures that signal a task using
23151 a suspension object
23152 @item Ada 95 protected procedure handlers for interrupts
23153 @item Ada 83 style interrupt entry handlers for interrupts
23157 In general, the range of possible solutions trades off latency versus
23158 restrictions in the handler code. Restrictions in direct vectored
23159 interrupt handlers are documented in the @cite{VxWorks Programmer's Guide}.
23160 Protected procedure handlers have only the
23161 restriction that no potentially blocking operations are performed within
23162 the handler. Interrupt entries have no restrictions. We recommend the
23163 use of the protected procedure mechanism as providing the best balance
23164 of these considerations for most applications.
23166 All handler types must explicitly perform any required hardware cleanups,
23167 such as issuing an end-of-interrupt if necessary.
23169 For VxWorks/AE, applications that handle interrupts must be loaded into
23170 the kernel protection domain.
23173 @item Direct Vectored Interrupt Routines
23176 This approach provides the lowest interrupt latency, but has the most
23177 restrictions on what VxWorks and Ada runtime calls can be made, as well
23178 as on what Ada entities are accessible to the handler code. Such handlers
23179 are most useful when there are stringent latency requirements, and very
23180 little processing is to be performed in the handler. Access to the
23181 necessary VxWorks routines for setting up such handlers is provided in
23182 the package @code{Interfaces.VxWorks}.
23184 VxWorks restrictions are described in the @cite{VxWorks Programmer's Manual}.
23185 Note in particular that floating point context is not automatically saved and
23186 restored when interrupts are vectored to the handler. If the handler is
23187 to execute floating point instructions, the statements involved must be
23188 bracketed by a pair of calls to @code{fppSave} and @code{fppRestore} defined
23189 in @code{Interfaces.VxWorks}.
23191 In general, it is a good idea to save and restore the handler that was
23192 installed prior to application startup. The routines @code{intVecGet}
23193 and @code{intVecSet} are used for this purpose. The Ada handler code
23194 is installed into the vector table using routine @code{intConnect},
23195 which generates wrapper code to save and restore registers.
23200 with Interfaces.VxWorks; use Interfaces.VxWorks;
23205 Count : Natural := 0;
23206 pragma Atomic (Count);
23208 -- Interrupt level used by this example
23209 Level : constant := 1;
23211 -- Be sure to use a reasonable interrupt number for the target
23212 -- board! Refer to the BSP for details.
23213 Interrupt : constant := 16#14#;
23215 procedure Handler (Parameter : System.Address);
23221 procedure Handler (parameter : System.Address) is
23224 Count := Count + 1;
23225 -- Acknowledge interrupt. Not necessary for all interrupts.
23226 S := sysBusIntAck (intLevel => Level);
23230 with Interfaces.VxWorks; use Interfaces.VxWorks;
23231 with Ada.Text_IO; use Ada.Text_IO;
23234 procedure Useint is
23241 for I in 1 .. 10 loop
23242 Put_Line ("Generating an interrupt...");
23245 -- Generate interrupt, using interrupt number
23246 S := sysBusIntGen (Level, Interrupt);
23250 -- Save old handler
23251 Old_Handler : VOIDFUNCPTR := intVecGet (INUM_TO_IVEC (Interrupt));
23253 S := intConnect (INUM_TO_IVEC (Interrupt), Handler'Access);
23254 S := sysIntEnable (intLevel => Level);
23256 for I in 1 .. 10 loop
23258 Put_Line ("value of count:" & P.Count'Img);
23261 -- Restore previous handler
23262 S := sysIntDisable (intLevel => Level);
23263 intVecSet (INUM_TO_IVEC (Interrupt), Old_Handler);
23267 @item Direct Vectored Interrupt Routines
23270 A variation on the direct vectored routine that allows for less restrictive
23271 handler code is to separate the interrupt processing into two levels.
23273 The first level is the same as in the previous section. Here we perform
23274 simple hardware actions and signal a task pending on a Suspension_Object
23275 (defined in @code{Ada.Synchronous_Task_Control}) to perform the more complex
23276 and time-consuming operations. The routine @code{Set_True} signals a task
23277 whose body loops and pends on the suspension object using @code{Suspend_Until_True}.
23278 The suspension object is declared in a scope global to both the handler and
23279 the task. This approach can be thought of as a slightly higher-level
23280 application of the @code{C} example using a binary semaphore given in the
23281 VxWorks Programmer's Manual. In fact, the implementation of
23282 @code{Ada.Synchronous_Task_Control} is a very thin wrapper around a VxWorks
23285 This approach has a latency between the direct vectored approach and the
23286 protected procedure approach. There are no restrictions in the Ada task
23287 code, while the handler code has the same restrictions as any other
23288 direct interrupt handler.
23294 package Sem_Handler is
23296 Count : Natural := 0;
23297 pragma Atomic (Count);
23299 -- Interrupt level used by this example
23300 Level : constant := 1;
23301 Interrupt : constant := 16#14#;
23303 -- Interrupt handler providing "immediate" handling
23304 procedure Handler (Param : System.Address);
23306 -- Task whose body provides "deferred" handling
23308 pragma Interrupt_Priority
23309 (System.Interrupt_Priority'First + Level + 1);
23314 with Ada.Synchronous_Task_Control; use Ada.Synchronous_Task_Control;
23315 with Interfaces.VxWorks; use Interfaces.VxWorks;
23316 package body Sema_Handler is
23318 SO : Suspension_Object;
23320 task body Receiver is
23323 -- Wait for notification from immediate handler
23324 Suspend_Until_True (SO);
23326 -- Interrupt processing
23327 Count := Count + 1;
23331 procedure Handler (Param : System.Address) is
23334 -- Hardware cleanup, if necessary
23335 S := sysBusIntAck (Level);
23343 with Interfaces.VxWorks; use Interfaces.VxWorks;
23344 with Ada.Text_IO; use Ada.Text_IO;
23345 with Sem_Handler; use Sem_Handler;
23346 procedure Useint is
23354 for I in 1 .. 10 loop
23355 Put_Line ("Generating an interrupt...");
23358 -- Generate interrupt, using interrupt number
23359 S := sysBusIntGen (Level, Interrupt);
23363 -- Save old handler
23364 Old_Handler : VOIDFUNCPTR := intVecGet (INUM_TO_IVEC (Interrupt));
23366 S := intConnect (INUM_TO_IVEC (Interrupt), Handler'Access);
23367 S := sysIntEnable (intLevel => Level);
23369 for I in 1 .. 10 loop
23371 Put_Line ("value of Count:" & Sem_Handler.Count'Img);
23375 S := sysIntDisable (intLevel => Level);
23376 intVecSet (INUM_TO_IVEC (Interrupt), Old_Handler);
23381 @item Protected Procedure Handlers for Interrupts
23384 This is the recommended default mechanism for interrupt handling.
23385 It essentially wraps the hybrid handler / task mechanism in a higher-level
23386 abstraction, and provides a good balance between latency and capability.
23388 Vectored interrupts are designated by their interrupt number, starting from
23389 0 and ranging to the number of entries in the interrupt vector table - 1.
23391 In the GNAT VxWorks implementation, the following priority mappings are used:
23393 @item Normal task priorities are in the range 0 .. 245.
23394 @item Interrupt priority 246 is used by the GNAT @code{Interrupt_Manager}
23396 @item Interrupt priority 247 is used for vectored interrupts
23397 that do not correspond to those generated via an interrupt controller.
23398 @item Interrupt priorities 248 .. 255 correspond to PIC interrupt levels
23400 @item Priority 256 is reserved to the VxWorks kernel.
23403 Except for reserved priorities, the above are recommendations for setting the
23404 ceiling priority of a protected object that handles interrupts, or the
23405 priority of a task with interrupt entries. It's a very good idea to follow
23406 these recommendations for vectored interrupts that come in through the PIC
23407 as it will determine the priority of execution of the code in the protected
23408 procedure or interrupt entry.
23410 No vectored interrupt numbers are reserved in this implementation, because
23411 dedicated interrupts are determined by the board support package. Obviously,
23412 careful consideration of the hardware is necessary when handling interrupts.
23413 The VxWorks BSP for the board is the definitive reference for interrupt
23419 package PO_Handler is
23421 -- Interrupt level used by this example
23422 Level : constant := 1;
23424 Interrupt : constant := 16#14#;
23426 protected Protected_Handler is
23428 pragma Attach_Handler (Handler, Interrupt);
23430 function Count return Natural;
23432 pragma Interrupt_Priority (248);
23434 The_Count : Natural := 0;
23435 end Protected_Handler;
23439 with Interfaces.VxWorks; use Interfaces.VxWorks;
23440 package body PO_Handler is
23442 protected body Protected_Handler is
23444 procedure Handler is
23447 -- Hardware cleanup if necessary
23448 S := sysBusIntAck (Level);
23450 -- Interrupt processing
23451 The_Count := The_Count + 1;
23454 function Count return Natural is
23458 end Protected_Handler;
23462 with Interfaces.VxWorks; use Interfaces.VxWorks;
23463 with Ada.Text_IO; use Ada.Text_IO;
23465 with PO_Handler; use PO_Handler;
23466 procedure Useint is
23474 for I in 1 .. 10 loop
23475 Put_Line ("Generating an interrupt...");
23478 -- Generate interrupt, using interrupt number
23479 S := sysBusIntGen (Level, Interrupt);
23484 S := sysIntEnable (intLevel => Level);
23486 for I in 1 .. 10 loop
23488 Put_Line ("value of count:" & Protected_Handler.Count'Img);
23491 S := sysIntDisable (intLevel => Level);
23496 This is obviously significantly higher-level and easier to write than the
23499 @item Ada 83 Style Interrupt Entries
23501 GNAT provides a full implementation of the Ada 83 interrupt entry mechanism
23502 for vectored interrupts. However, due to latency issues,
23503 we only recommend using these for backward compatibility. The comments in
23504 the previous section regarding interrupt priorities and reserved interrupts
23507 In order to associate an interrupt with an entry, GNAT provides the
23508 standard Ada convenience routine @code{Ada.Interrupts.Reference}. It is used
23512 Interrupt_Address : constant System.Address :=
23513 Ada.Interrupts.Reference (Int_Num);
23515 task Handler_Task is
23516 pragma Interrupt_Priority (248); -- For instance
23518 for Handler'Address use Interrupt_Address;
23523 Since there is no restriction within an interrupt entry on blocking operations,
23524 be sure to perform any hardware interrupt controller related operations before
23525 executing a call that could block within the entry's accept statements. It
23526 is assumed that interrupt entries are always open alternatives when they
23527 appear within a selective wait statement. The presence of a guard gives
23528 undefined behavior.
23533 with Ada.Interrupts;
23535 package Task_Handler is
23537 -- Interrupt level used by this example
23538 Level : constant := 1;
23540 Interrupt : constant := 16#14#;
23542 Interrupt_Address : constant System.Address :=
23543 Ada.Interrupts.Reference (Int_Num);
23545 task Handler_Task is
23546 pragma Interrupt_Priority (248); -- For instance
23548 for Handler'Address use Interrupt_Address;
23550 entry Count (Value : out Natural);
23554 with Interfaces.VxWorks; use Interfaces.VxWorks;
23555 package body Task_Handler is
23557 task body Handler_Task is
23558 The_Count : Natural := 0;
23564 -- Hardware cleanup if necessary
23565 S := sysBusIntAck (Level);
23567 -- Interrupt processing
23568 The_Count := The_Count + 1;
23571 accept Count (Value : out Natural) do
23572 Value := The_Count;
23580 with Interfaces.VxWorks; use Interfaces.VxWorks;
23581 with Ada.Text_IO; use Ada.Text_IO;
23583 with Handler_Task; use Handler_Task;
23584 procedure Useint is
23589 Current_Count : Natural := 0;
23593 for I in 1 .. 10 loop
23594 Put_Line ("Generating an interrupt...");
23597 -- Generate interrupt, using interrupt number
23598 S := sysBusIntGen (Level, Interrupt);
23603 S := sysIntEnable (intLevel => Level);
23605 for I in 1 .. 10 loop
23607 Handler_Task.Count (Current_Count);
23608 Put_Line ("value of count:" & Current_Count'Img);
23611 S := sysIntDisable (intLevel => Level);
23612 abort Handler_Task;
23618 @node Simulating Command Line Arguments for VxWorks
23619 @section Simulating Command Line Arguments for VxWorks
23622 The GNAT implementation of @code{Ada.Command_Line} relies on the standard C
23623 symbols @code{argv} and @code{argc}. The model for invoking "programs" under
23624 VxWorks does not provide these symbols. The typical method for invoking a
23625 program under VxWorks is to call the @code{sp} function in order to spawn a
23626 thread in which to execute a designated function (in GNAT, this is the implicit
23627 main generated by gnatbind. @code{sp} provides the capability to push a variable
23628 number of arguments onto the stack when the function is invoked. But this does
23629 not work for the implicit Ada main, because it has no way of knowing how many
23630 arguments might be required. This eliminates the possibility to use
23631 @code{Ada.Command_Line}.
23633 One way to solve this problem is to define symbols in the VxWorks environment,
23634 then import them into the Ada application. For example, we could define the
23635 following package that imports two symbols, one an int and the other a string:
23638 with Interfaces.C.Strings;
23639 use Interfaces.C.Strings;
23641 -- Define and import a variable for each argument
23642 Int_Arg : Interfaces.C.Int;
23643 String_Arg : Chars_Ptr;
23645 pragma Import (C, Int_Arg, "intarg");
23646 pragma Import (C, String_Arg, "stringarg");
23651 An Ada unit could then use the two imported variables @code{Int_Arg} and
23652 @code{String_Arg} as follows:
23655 with Args; use Args;
23656 with Interfaces.C.Strings;
23657 use Interfaces.C, Interfaces.C.Strings;
23658 with Ada.Text_IO; use Ada.Text_IO;
23659 procedure Argtest is
23661 Put_Line (Int'Image (Int_Arg));
23662 Put_Line (Value (String_Arg));
23667 When invoking the application from the shell, one will then set the values
23668 to be imported, and spawn the application, as follows:
23672 -> stringarg="Hello"
23677 @node Debugging Issues for VxWorks
23678 @section Debugging Issues for VxWorks
23681 The debugger can be launched directly from the Tornado environment or from @code{glide}
23682 through its graphical interface: @code{gvd}. It can also be used
23683 directly in text mode as shown below:
23685 The command to run @code{GDB} in text mode is
23692 where @i{target} is the name of target of the cross GNAT
23693 compiler. In contrast with native @code{gdb}, it is not useful to give the name of
23694 the program to debug on the command line. Before starting a debugging
23695 session, one needs to connect to the VxWorks-configured board and load
23696 the relocatable object produced by @code{gnatlink}. This can be achieved
23697 by the following commands:
23700 (vxgdb) target wtx myboard
23701 (vxgdb) load program
23705 where @code{myboard} is the host name or IP number of the target board, and
23706 @code{wtx} is the name of debugging protocol used to communicate
23707 with the VxWorks board. Early versions of VxWorks, up tp 5.2, only
23708 support the @code{<vxworks>} protocol whereas starting with VxWorks 5.3
23709 and Tornado, another protocol called @code{<wtx>} was made available. The
23710 choice of the protocol can be made when configuring the VxWorks
23711 kernel itself. When available, the @code{<wtx>} is greatly preferable
23712 and actually the only supported protocol with GNAT. When the debugger
23713 is launched directly from Tornado, the proper @code{target} command
23714 is automatically generated by the environment.
23716 The GNAT debugger can be used for debugging multitasking programs in two
23717 different modes and some minimal understanding of these modes is
23718 necessary in order to use the debugger effectively. The two modes are:
23721 @item Monotask mode: attach to, and debug, a single task.
23722 This mode is equivalent to the capabilities offered by CrossWind. The
23723 debugger interacts with a single task, while not affecting other tasks
23724 (insofar as possible). This is the DEFAULT mode.
23726 @item Multitask mode:
23727 The debugger has control over all Ada tasks in an application. It is
23728 possible to gather information about all application tasks, and to
23729 switch from one to another within a single debugging session.
23733 It is not advised to switch between the two modes within a debugging
23734 session. A third mode called System mode is also available and can be
23735 used in place of the Multitask mode. Consult the Tornado documentation
23738 Among the criteria for selecting the appropriate mode is the effect of
23739 task synchronization on the application's behavior. Debugging a
23740 tasking application affects the timing of the application; minimizing
23741 such effects may be critical in certain situations. The two modes have
23742 different effects: monotask mode only affects the attached task:
23743 others will run normally (if possible). Multitask mode stops all tasks
23744 at each breakpoint and restarts them on single-step, next, finish or
23745 continue; this may help avoid deadlocks in the presence of task
23746 synchronization despite the inherent latency of stopping and
23747 restarting the tasks.
23749 @subsection Using the debugger in monotask mode
23752 There are two ways to begin your debugging session:
23755 @item The program is already running on the board.
23758 The sequence of commands to use this mode is:
23760 @item Launch GVD (possibly from the Tornado menu)
23763 Verify that the debugger has access to the debug information of both
23764 your program and the kernel. The Console window should have a message
23765 "Looking for all loaded modules:" followed by the names of the modules
23766 on the board and "ok". If you have some error messages here instead of
23767 "ok", the debugging session may not work as expected.
23769 @item Attach to the desired task using
23774 This task is stopped by the debugger. Other tasks continue to operate
23775 normally (unless they are blocked by synchronization with the stopped
23776 task). The source window should display the code on which the task has
23777 been stopped, and if the stack display is enabled, it should reflect
23778 the stack of the task.
23781 @item The program hasn't been loaded yet on the board
23783 @item Launch GVD (possibly from the Tornado menu)
23784 @item Load your program to the board:
23786 File --> Open Program...
23790 GVD should display:
23792 Downloading your_program ...done.
23793 Reading symbols from your_program...expanding to full symbols...done.
23796 @item Set breakpoints in your program.
23799 WARNING: they must be set in the main task (if your program runs
23802 @item Run your program using one of the three methods below:
23805 Click on button <run> or <start>
23809 Program --> Run/Start
23813 Type in GVD's Console window
23815 (gdb) run your_program
23820 @item Whichever method you chose to start your debugging session,
23821 you can use the following commands at this point:
23823 @item Browse sources and set breakpoints
23824 @item Examine the call stack (Data --> call stack)
23825 @item Go "up" and "down" in the call stack ("up" & "down" buttons)
23827 (Data --> Display local variables, or any of the other methods for viewing data in GVD)
23828 @item Continue/finish
23831 Next/step/finish will only work if the top frame in the call stack has
23832 debug information. This is almost never the case when first attaching
23833 to the task since the task is usually stopped by the attach operation
23834 in the GNAT runtime. You can verify which frames of the call stack
23835 have debug information by:
23837 Data --> call stack
23838 <right Button> (contextual menu inside the call stack window)
23839 add "file location"
23843 If the current frame does not have a "file location", then there is no
23844 debug information for the frame. We strongly recommended that you set
23845 breakpoints in the source where debug information can be found and
23846 "continue" until a breakpoint is reached before using
23847 "next/step". Another convenient possibility is to use the "continue
23848 until" capability available from the contextual menu of the Source
23851 You can also examine the state of other tasks using
23857 but you can't "switch" to another task by clicking on the
23858 elements of the task list. If you try to, you will get an error
23859 message in GVD's console:
23861 "Task switching is not allowed when multi-tasks mode is not active"
23865 Once you have completed your debugging session on the attached
23866 task, you can detach from the task:
23872 The task resumes normal execution at this stage. WARNING: when you
23873 detach from a task, be sure that you are in a frame where there is
23874 debug information. Otherwise, the task won't resume properly. You can
23875 then start another attach/detach cycle if you wish.
23877 Note that it is possible to launch several GVD sessions and
23878 simultaneously attach each to a distinct task in monotask mode:
23880 File --> New Debugger... (uncheck the box: Replace Current Debugger)
23881 File --> Attach... (in the new window)
23887 @subsection Using the debugger in Multitask mode
23890 The steps are as follows
23894 Launch GVD (possibly from the Tornado menu)
23897 There are two possibilities:
23900 If the program is already loaded on the target board, you need only verify
23901 that debug information has been found by the debugger as described
23905 Otherwise, load the program on the board using
23907 File --> Open program
23911 @item Set breakpoints in the desired parts of the program
23913 @item Start the program
23916 The simplest way to start the debugger in multitask mode is to use the
23919 Program --> Run/Start
23923 and check the box "enable vxWorks multi-tasks mode".
23924 You can also use the following gdb commands in the console window
23926 (gdb) set multi-tasks-mode on
23927 (gdb) run your_program
23930 @item Debug the stopped program
23933 Once stopped at a breakpoint
23934 (or if you pressed the "stop" button), you can use all the standard
23935 commands listed for monotask mode + task switching (using Data -->
23936 tasks). Using next/step under this mode is possible with the same
23937 restrictions as for monotask mode, but is not recommended because all
23938 tasks are restarted, leading to the possibility that a different task
23939 hits a breakpoint before the stepping operation has completed. Such
23940 an occurrence can result in a confusing state for both the user and
23941 the debugger. So we strongly suggest the use of only breakpoints and
23942 "continue" in this mode.
23945 A final reminder: whatever the mode, whether you are debugging or not,
23946 the program has to be reloaded before each new execution, so that data
23947 initialized by the loader is set correctly. For instance, if you wish
23948 to restart the same execution of the same program, you can use the
23949 following sequence of gdb commands in the console window:
23952 (gdb) unload your_program(.exe)
23953 (gdb) load your_program(.exe)
23954 (gdb) run your_program
23958 @node Using GNAT from the Tornado 2 Project Facility
23959 @section Using GNAT from the Tornado 2 Project Facility
23960 @cindex Tornado II Project
23963 * The GNAT Toolchain as Used from the Tornado 2 Project Facility::
23964 * Building a Simple Application::
23965 * Mixing C and Ada Code in a Tornado 2 Project::
23966 * Compilation Switches::
23967 * Autoscale and Minimal Kernel Configuration::
23968 * Adapting BSPs to GNAT::
23969 * Using GNAT Project Files in a Tornado 2 Project::
23973 This section describes how to add an Ada module in a Tornado project
23974 using the Tornado 2 Project facility described in
23975 @cite{Tornado User's Guide}, Chapter 4.
23976 All recommendations apply for both 'Downloadable Modules' and 'Kernel'
23980 @node The GNAT Toolchain as Used from the Tornado 2 Project Facility
23981 @subsection The GNAT Toolchain as Used from the Tornado 2 Project Facility
23984 Tornado 2 allows you to integrate third-party C toolchains.
23985 (@cite{Tornado 2 API Programmer's Guide}, Chapter 7).
23986 Thus the GNAT toolchain will be seen as a new C toolchain when used from
23987 the Tornado 2 Project Facility. For each processor you can compile for,
23988 you will find a <proc>gnat toolchain, e.g. PPC604gnat. These toolchains will
23989 allow you to include Ada modules into your projects, and simply build them.
23991 The name of the so-called C compiler is @emph{cc_gnat_<arch>}, the name
23992 of the 'linker' is @emph{ld_gnat_<arch>}, where <arch> is an architecture; e.g.,
23993 PPC. These scripts will call the correct executables during the compilation or
23994 link processes, thus the C compiler, the C linker, or the GNAT toolchain,
23995 depending on the context.
23998 @node Building a Simple Application
23999 @subsection Building a Simple Application
24002 First, create a new project, using one of the gnat toolchains.
24004 To add an Ada source file to the current project, just click on
24005 @code{Project -> Add/Include}, browse to the relevant file, and include it.
24006 The Ada source file included should be the Ada entry point. Only
24007 one Ada entry point is allowed in a project. Any other required Ada source
24008 files will be automatically compiled and linked by the underlying tools.
24010 You can now compile the project, @code{Build->Rebuild all}.
24011 A log of the compilation process can be found in the build directory, in
24012 @file{gnatbuild.log}. It contains all the calls executed by the scripts, and
24013 associated information.
24016 @node Mixing C and Ada Code in a Tornado 2 Project
24017 @subsection Mixing C and Ada Code in a Tornado 2 Project
24020 You can mix C and Ada code in your projects. Your source files and the build
24021 options should comply with the recommendations from the section
24022 @cite{Interfacing to C}.
24023 This means that you can have several or no C source files, and one or no Ada entry
24024 point in your Tornado 2 Project.
24027 @node Compilation Switches
24028 @subsection Compilation Switches
24030 Once you have included all your source files, you may modify some compilation
24031 and linking options.
24032 To pass specific options to the GNAT toolchain, go to the Project's build
24033 settings, on the @code{C/C++ Compiler} tab, and add your arguments in the
24036 You must comply with several rules to pass arguments to GNAT.
24037 Arguments to be passed should be
24041 @item after any arguments passed to the C toolchain.
24043 @item prefixed depending on the tool that uses them, with the following syntax
24046 @item @code{-cargs @emph{gnatmake-options}} to pass arguments to gnatmake
24047 @item @code{-bargs @emph{gnatbind-options}} to pass arguments to gnatbind
24048 @item @code{-largs @emph{gnatlink-options}} to pass arguments to gnatlink
24053 You will find more information on the compilation process of Ada source files
24054 in the section @cite{The GNAT Compilation Model}.
24055 For a list of all available switches, refer to the sections describing
24056 @code{gnatmake}, @code{gnatbind} and @code{gnatlink}.
24058 Here is an example that passes the option @code{-v} to the GNAT compiler :
24060 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
24061 -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
24066 Here is an example that passes the option @code{-v} to the GNAT compiler, binder and linker,
24067 and @code{-v} and @code{-g} to the compiler :
24069 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
24070 -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
24071 -cargs -v -g -O2 -bargs -v -largs -v
24075 In both examples, the following arguments have been automatically added by the Project
24076 Facility, and will be used by the C compiler.
24078 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
24079 -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
24083 Note: The @code{-prjtype $(PRJ_TYPE)} option present in a few input
24084 boxes is used by the GNAT toolchain. It is required for the compilation
24085 process. You should not remove it from any input box.
24088 @node Autoscale and Minimal Kernel Configuration
24089 @subsection Autoscale and Minimal Kernel Configuration
24092 The Autoscale feature, present in the Project Facility can be used on your
24093 VxWorks Kernel projects to determine the minimum set of components required
24094 for your kernel to work.
24095 (Please refer to the @cite{Tornado II User's Guide} Section 4.4 for more details.)
24096 This feature is also available for projects involving Ada code. Just click on
24097 @code{Project->Autoscale} to launch a check and determine the minimal kernel
24101 @node Adapting BSPs to GNAT
24102 @subsection Adapting BSPs to GNAT
24105 To use your Board Support Packages with the GNAT toolchain, you will have to adapt them,
24106 either manually or using the @code{adaptbsp4gnat} script.
24107 This procedure is described in the @cite{Tornado API Programmer's Guide},
24109 Here is a summary of this setup, depending on the context.
24112 @item To do the adaptation manually:
24116 @item Copy your BSP directory contents into a new directory
24118 @item Go to this directory
24120 @item Edit the file @file{Makefile},
24123 @item Set tool to gnat, @code{TOOL=gnat}
24125 @item Reverse the order of the following lines
24127 @item @code{include $(TGT_DIR)/h/make/make.$(CPU)$(TOOL)}
24128 @item @code{include $(TGT_DIR)/h/make/defs.$(WIND_HOST_TYPE)}
24135 @item To do the adaptation automatically, you may use the @code{adaptbsp4gnat}
24136 script. Its syntax is @code{adaptbsp4gnat <path_to_bsp>}.
24139 This script follows the different steps described above to perform the
24141 The name of the new bsp is given after the modification. By default, if
24142 @file{<bsp>} is the name of your BSP, @file{<bsp>-gnat}, will be the name of
24147 @node Using GNAT Project Files in a Tornado 2 Project
24148 @subsection Using GNAT Project Files in a Tornado 2 Project
24151 You can use GNAT Project files to compile your Ada files.
24152 To do so, you need to use the @option{-Pproject_file.gpr} option from @command{gnatmake}.
24153 The path to the project file can be either absolute, or relative to the build
24154 directory, i.e. where the executable will be placed (e.g. @file{~/myproject/PPC604gnat}).
24155 Your project file should set the @code{Object_Dir} variable to a specific
24160 Target := external ("TARGET_DIR");
24161 for Object_Dir use Target;
24167 @node Frequently Asked Questions for VxWorks
24168 @section Frequently Asked Questions for VxWorks
24173 When I run my program twice on the board, it does not work, why?
24176 Usually, Ada programs require elaboration and finalization, so the
24177 compiler creates a wrapper procedure whose name is the same as the Ada
24178 name of the main subprogram, which takes care of calling the elaboration
24179 and finalization routines before and after your program. But the static
24180 part of the elaboration is taken care of while loading the program
24181 itself and thus if you launch it twice this part of the elaboration will
24182 not be performed. This affects the proper elaboration of the
24183 GNAT runtime and thus it is mandatory to reload your program before
24187 Can I load a collection of subprograms rather than a standalone program?
24190 It is possible to write Ada programs with multiple entry points which
24191 can be called from the VxWorks shell; you just need to consider your
24192 main program as the VxWorks shell itself and generate an Ada subsystem
24193 callable from outside @xref{Binding with Non-Ada Main Programs}. If you
24194 use this method, you need to call @code{adainit} manually before calling
24195 any Ada entry point.
24198 When I use the @code{break exception} command, I get the message
24199 @code{"exception" is not a function}, why?
24201 You are not in the proper language mode. Issue the command:
24203 (vxgdb) set language ada
24207 When I load a large application from the VxWorks shell using the "ld"
24208 command, the load hangs and never finishes. How can I load large
24211 This is a classic VxWorks problem when using the default "rsh" communication
24212 method. Using NFS instead should work. Use the @code{nfsShowMount} command to
24213 verify that your program is in a NFS mounted directory.
24216 When I load a large application from the debugger using the wtx target
24217 connection, the load never finishes, why?
24219 Make sure that the memory cache size parameter of the target server is
24220 large enough. (@code{target -m big_enough_size}, or Memory cache size box in GUI.)
24221 See @cite{Tornado 1.01 API Programming Guide}, Section 3.6.2.
24224 When I spawn my program under the VxWorks shell, interactive input does
24227 Only programs directly launched from the shell can have interactive
24228 input. For a program spawned with the @code{sp} or @code{taskSpawn}
24229 command, you need to have file redirection for input:
24231 -> # here you can have interactive input
24233 -> # here you cannot
24236 -> taskSpawn("ess",100,0,8000000,main)
24237 -> # but you can input from a file:
24238 -> taskSpawn("Bae",100,0,8000000,main) < input_file
24243 @node LynxOS Topics
24244 @chapter LynxOS Topics
24246 This chapter describes topics that are specific to the GNAT for LynxOS
24247 cross configurations.
24250 * Getting Started with GNAT on LynxOS::
24251 * Kernel Configuration for LynxOS::
24252 * Patch Level Issues for LynxOS::
24253 * Debugging Issues for LynxOS::
24254 * An Example Debugging Session for LynxOS::
24257 @node Getting Started with GNAT on LynxOS
24258 @section Getting Started with GNAT on LynxOS
24261 This section is a starting point for using GNAT to develop and
24262 execute Ada 95 programs for LynuxWorks' LynxOS target environment from a
24263 Unix host environment.
24264 We assume that you know how to use GNAT in a native environment
24265 and how to start a telnet or other login session to connect to your LynxOS board.
24267 To compile code for a LynxOS system running on a PowerPC
24268 board, the basic compiler command is
24269 @command{powerpc-xcoff-lynxos-gcc}.
24271 With GNAT, the easiest way to build the basic @code{Hello World} program is
24272 with @code{gnatmake}. For the LynxOS PowerPC target this would look
24276 $ powerpc-xcoff-lynxos-gnatmake hello
24277 @i{powerpc-xcoff-lynxos-gcc -c hello.adb
24278 powerpc-xcoff-lynxos-gnatbind -x hello.ali
24279 powerpc-xcoff-lynxos-gnatlink hello.ali}
24283 (The first line is the command entered by the user -- the subseqent three
24284 are the programs run by @code{gnatmake}.)
24286 This creates the executable @command{hello}" which you then need to load on the
24287 board (using ftp or an NFS directory for example) to run it.
24290 @node Kernel Configuration for LynxOS
24291 @section Kernel Configuration for LynxOS
24294 The appropriate configuration for your LynxOS kernel depends
24295 on the target system and the requirements of your application. GNAT itself
24296 adds no additional demands; however in some situations it may be appropriate
24297 to increase the conservative
24298 resource assumptions made by the default configuration.
24300 Kernel parameters limiting the maximum number of file descriptors,
24301 kernel and user threads, synchronization objects, etc., may be set in the
24302 file @file{uparam.h}. You may also wish to modify the file
24303 @file{/etc/starttab}, which places limits on data, stack, and core file
24304 size. See the documentation provided by LynuxWorks for more information.
24307 @node Patch Level Issues for LynxOS
24308 @section Patch Level Issues for LynxOS
24311 The GNAT runtime requires that your system run at patch level 040 or
24312 later. Please see the file @file{PatchCompatibility.txt} from the
24313 distribution for more information.
24316 @node Debugging Issues for LynxOS
24317 @section Debugging Issues for LynxOS
24320 GNAT's debugger is based on the same GNU gdb technology as the debugger
24321 provided by LynxOS, though with a great number of extensions and
24322 enhancements to support the Ada language and GNAT. The LynxOS
24323 documentation is relevant to understanding how to get the debugger
24324 started if you run into difficulties.
24326 To demonstrate a debugging session, we will use a slightly more complex
24327 program called @file{demo1.adb}, which can be found in the @file{examples}
24328 directory of the GNAT distribution. This program is compiled with
24329 debugging information as follows:
24332 $ powerpc-xcoff-lynxos-gnatmake -g demo1
24333 powerpc-xcoff-lynxos-gcc -c -g demo1.adb
24334 powerpc-xcoff-lynxos-gcc -c -g gen_list.adb
24335 powerpc-xcoff-lynxos-gcc -c -g instr.adb
24336 powerpc-xcoff-lynxos-gnatbind -x demo1.ali
24337 powerpc-xcoff-lynxos-gnatlink -g demo1.ali
24341 Once the executable is created, copy it to your working directory on the
24342 board. In this directory, you will have to launch the gdb server and
24343 choose a free port number on your TCP/IP socket. Presuming the Internet
24344 hostname of the board is @file{myboard} and the port chosen is 2345,
24345 issue the following command:
24348 myboard> gdbserver myboard:2345 demo1
24352 Then return to your host environment.
24354 The graphical debugger interface, @command{gvd}, supports both native
24355 and cross environments at the same time. @command{gvd} can be launched from
24356 @command{Glide} (see @file{README.Glide} for more information on customizing
24357 @command{Glide} for LynxOS) or it can be launched from the command line as
24361 $ gvd --debugger powerpc-xcoff-lynxos-gdb
24365 Then to attach to the target, enter in @command{gvd}'s command line window:
24368 (gdb) target remote myboard:2345
24372 For more information see the GVD documentation.
24374 The comments below concern debugging directly from the command line but
24375 they also apply to @command{gvd}, though in most cases an equivalent
24376 graphical command is also available.
24378 To run the cross debugger from the command line without the visual
24379 interface use the command @code{powerpc-xcoff-lynxos-gdb}.
24381 You will see something like:
24384 GNU gdb 4.17.gnat.3.14a1
24385 Copyright 1998 Free Software Foundation, Inc.
24386 GDB is free software, covered by the GNU General Public License, and you are
24387 welcome to change it and/or distribute copies of it under certain conditions.
24388 Type "show copying" to see the conditions.
24389 There is absolutely no warranty for GDB. Type "show warranty" for details.
24390 This GDB was configured as "--host=sparc-sun-solaris2.5.1 --target=powerpc-xc
24396 Where @command{(gdb)} is the debugger's prompt. The first thing to do at the
24397 prompt from within @command{gdb} is to load the symbol table from the
24402 Reading symbols from demo1...done.
24407 You then have to attach to the server running on the board. Issue the command:
24410 (gdb) target remote myboard:2345
24414 After the server has been started and attached from the host, the program is
24415 running on the target but has halted execution at the very beginning.
24416 The following commands set a breakpoint and continue execution:
24419 (gdb) break demo1.adb:37
24420 Breakpoint 1 at 0x100064d0: file demo1.adb, line 37.
24424 Breakpoint 1, demo1 () at demo1.adb:37
24425 37 Set_Name (Fuel, "Fuel");
24430 Here the execution has stopped at the breakpoint set above. Now
24431 you can use the standard @code{gdb} commands to examine the stack and
24434 Note that once execution has completed, the server on the board must be
24435 restarted before a new debugging session may begin.
24437 @node An Example Debugging Session for LynxOS
24438 @section An Example Debugging Session for LynxOS
24441 Carrying on a little further with the debugging session, the following
24442 example illustrates some of the usual debugging commands for moving
24443 around and seeing where you are:
24447 38 Set_Name (Water, "Water");
24449 #0 demo1 () at demo1.adb:38
24450 #1 0x10001218 in main (argc=1, argv=2147483640, envp=2147483520) at
24452 #2 0x10017538 in runmainthread ()
24453 #3 0x10001048 in __start ()
24455 #1 0x10001218 in main (argc=1, argv=2147483640, envp=2147483520) at
24457 118 Ada_Main_Program;
24459 #0 demo1 () at demo1.adb:38
24460 38 Set_Name (Water, "Water");
24465 To examine and modify variables (of a tagged type here):
24469 $1 = (name => "Speed ", value => -286331154)
24471 type = new instr.instrument with record
24472 value: instr.speed;
24474 (gdb) speed.value := 3
24477 $3 = (name => "Speed ", value => 3)
24479 speed = (name => "Speed ", value => 3)
24480 fuel = (name => "Fuel ", value => -286331154)
24481 oil = (name => ' ' <repeats 14 times>, value => -286331154, size => 20,
24482 fill => 42 '*', empty => 46 '.')
24483 water = (name => ' ' <repeats 14 times>, value => -286331154, size => 20,
24484 fill => 42 '*', empty => 46 '.')
24485 time = (name => ' ' <repeats 14 times>, seconds => 0, minutes => 0, hours =>
24487 chrono = (name => ' ' <repeats 14 times>, seconds => 0, minutes => 0,
24489 db = (access demo1.dash_board.internal) 0x0
24494 And finally letting the program it run to completion:
24500 Program exited normally.
24506 @node Performance Considerations
24507 @chapter Performance Considerations
24508 @cindex Performance
24511 The GNAT system provides a number of options that allow a trade-off
24516 performance of the generated code
24519 speed of compilation
24522 minimization of dependences and recompilation
24525 the degree of run-time checking.
24529 The defaults (if no options are selected) aim at improving the speed
24530 of compilation and minimizing dependences, at the expense of performance
24531 of the generated code:
24538 no inlining of subprogram calls
24541 all run-time checks enabled except overflow and elaboration checks
24545 These options are suitable for most program development purposes. This
24546 chapter describes how you can modify these choices, and also provides
24547 some guidelines on debugging optimized code.
24550 * Controlling Run-Time Checks::
24551 * Optimization Levels::
24552 * Debugging Optimized Code::
24553 * Inlining of Subprograms::
24555 * Coverage Analysis::
24559 @node Controlling Run-Time Checks
24560 @section Controlling Run-Time Checks
24563 By default, GNAT generates all run-time checks, except arithmetic overflow
24564 checking for integer operations and checks for access before elaboration on
24565 subprogram calls. The latter are not required in default mode, because all
24566 necessary checking is done at compile time.
24567 @cindex @option{-gnatp} (@code{gcc})
24568 @cindex @option{-gnato} (@code{gcc})
24569 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
24570 be modified. @xref{Run-Time Checks}.
24572 Our experience is that the default is suitable for most development
24575 We treat integer overflow specially because these
24576 are quite expensive and in our experience are not as important as other
24577 run-time checks in the development process. Note that division by zero
24578 is not considered an overflow check, and divide by zero checks are
24579 generated where required by default.
24581 Elaboration checks are off by default, and also not needed by default, since
24582 GNAT uses a static elaboration analysis approach that avoids the need for
24583 run-time checking. This manual contains a full chapter discussing the issue
24584 of elaboration checks, and if the default is not satisfactory for your use,
24585 you should read this chapter.
24587 For validity checks, the minimal checks required by the Ada Reference
24588 Manual (for case statements and assignments to array elements) are on
24589 by default. These can be suppressed by use of the @option{-gnatVn} switch.
24590 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
24591 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
24592 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
24593 are also suppressed entirely if @option{-gnatp} is used.
24595 @cindex Overflow checks
24596 @cindex Checks, overflow
24599 @cindex pragma Suppress
24600 @cindex pragma Unsuppress
24601 Note that the setting of the switches controls the default setting of
24602 the checks. They may be modified using either @code{pragma Suppress} (to
24603 remove checks) or @code{pragma Unsuppress} (to add back suppressed
24604 checks) in the program source.
24606 @node Optimization Levels
24607 @section Optimization Levels
24608 @cindex @code{^-O^/OPTIMIZE^} (@code{gcc})
24611 The default is optimization off. This results in the fastest compile
24612 times, but GNAT makes absolutely no attempt to optimize, and the
24613 generated programs are considerably larger and slower than when
24614 optimization is enabled. You can use the
24616 @code{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
24621 on the @code{gcc} command line to control the optimization level:
24625 no optimization (the default)
24628 medium level optimization
24634 full optimization, and also attempt automatic inlining of small
24635 subprograms within a unit (@pxref{Inlining of Subprograms}).
24638 Higher optimization levels perform more global transformations on the
24639 program and apply more expensive analysis algorithms in order to generate
24640 faster and more compact code. The price in compilation time, and the
24641 resulting improvement in execution time,
24642 both depend on the particular application and the hardware environment.
24643 You should experiment to find the best level for your application.
24645 Note: Unlike some other compilation systems, @code{gcc} has
24646 been tested extensively at all optimization levels. There are some bugs
24647 which appear only with optimization turned on, but there have also been
24648 bugs which show up only in @emph{unoptimized} code. Selecting a lower
24649 level of optimization does not improve the reliability of the code
24650 generator, which in practice is highly reliable at all optimization
24653 Note regarding the use of @code{-O3}: The use of this optimization level
24654 is generally discouraged with GNAT, since it often results in larger
24655 executables which run more slowly. See further discussion of this point
24656 in @pxref{Inlining of Subprograms}.
24658 @node Debugging Optimized Code
24659 @section Debugging Optimized Code
24662 Since the compiler generates debugging tables for a compilation unit before
24663 it performs optimizations, the optimizing transformations may invalidate some
24664 of the debugging data. You therefore need to anticipate certain
24665 anomalous situations that may arise while debugging optimized code. This
24666 section describes the most common cases.
24670 @i{The "hopping Program Counter":} Repeated 'step' or 'next' commands show the PC
24671 bouncing back and forth in the code. This may result from any of the following
24676 @i{Common subexpression elimination:} using a single instance of code for a
24677 quantity that the source computes several times. As a result you
24678 may not be able to stop on what looks like a statement.
24681 @i{Invariant code motion:} moving an expression that does not change within a
24682 loop, to the beginning of the loop.
24685 @i{Instruction scheduling:} moving instructions so as to
24686 overlap loads and stores (typically) with other code, or in
24687 general to move computations of values closer to their uses. Often
24688 this causes you to pass an assignment statement without the assignment
24689 happening and then later bounce back to the statement when the
24690 value is actually needed. Placing a breakpoint on a line of code
24691 and then stepping over it may, therefore, not always cause all the
24692 expected side-effects.
24696 @i{The "big leap":} More commonly known as @i{cross-jumping}, in which two
24697 identical pieces of code are merged and the program counter suddenly
24698 jumps to a statement that is not supposed to be executed, simply because
24699 it (and the code following) translates to the same thing as the code
24700 that @emph{was} supposed to be executed. This effect is typically seen in
24701 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
24702 a @code{break} in a C @code{switch} statement.
24705 @i{The "roving variable":} The symptom is an unexpected value in a variable.
24706 There are various reasons for this effect:
24710 In a subprogram prologue, a parameter may not yet have been moved to its
24714 A variable may be dead, and its register re-used. This is
24715 probably the most common cause.
24718 As mentioned above, the assignment of a value to a variable may
24722 A variable may be eliminated entirely by value propagation or
24723 other means. In this case, GCC may incorrectly generate debugging
24724 information for the variable
24728 In general, when an unexpected value appears for a local variable or parameter
24729 you should first ascertain if that value was actually computed by
24730 your program, as opposed to being incorrectly reported by the debugger.
24732 array elements in an object designated by an access value
24733 are generally less of a problem, once you have ascertained that the access value
24735 Typically, this means checking variables in the preceding code and in the
24736 calling subprogram to verify that the value observed is explainable from other
24737 values (one must apply the procedure recursively to those
24738 other values); or re-running the code and stopping a little earlier
24739 (perhaps before the call) and stepping to better see how the variable obtained
24740 the value in question; or continuing to step @emph{from} the point of the
24741 strange value to see if code motion had simply moved the variable's
24745 @node Inlining of Subprograms
24746 @section Inlining of Subprograms
24749 A call to a subprogram in the current unit is inlined if all the
24750 following conditions are met:
24754 The optimization level is at least @code{-O1}.
24757 The called subprogram is suitable for inlining: It must be small enough
24758 and not contain nested subprograms or anything else that @code{gcc}
24759 cannot support in inlined subprograms.
24762 The call occurs after the definition of the body of the subprogram.
24765 @cindex pragma Inline
24767 Either @code{pragma Inline} applies to the subprogram or it is
24768 small and automatic inlining (optimization level @code{-O3}) is
24773 Calls to subprograms in @code{with}'ed units are normally not inlined.
24774 To achieve this level of inlining, the following conditions must all be
24779 The optimization level is at least @code{-O1}.
24782 The called subprogram is suitable for inlining: It must be small enough
24783 and not contain nested subprograms or anything else @code{gcc} cannot
24784 support in inlined subprograms.
24787 The call appears in a body (not in a package spec).
24790 There is a @code{pragma Inline} for the subprogram.
24793 @cindex @option{-gnatn} (@code{gcc})
24794 The @code{^-gnatn^/INLINE^} switch
24795 is used in the @code{gcc} command line
24798 Note that specifying the @option{-gnatn} switch causes additional
24799 compilation dependencies. Consider the following:
24804 @b{package} R @b{is}
24806 @b{pragma} Inline (Q);
24808 @b{package body} R @b{is}
24813 @b{procedure} Main @b{is}
24823 With the default behavior (no @option{-gnatn} switch specified), the
24824 compilation of the @code{Main} procedure depends only on its own source,
24825 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
24826 means that editing the body of @code{R} does not require recompiling
24829 On the other hand, the call @code{R.Q} is not inlined under these
24830 circumstances. If the @option{-gnatn} switch is present when @code{Main}
24831 is compiled, the call will be inlined if the body of @code{Q} is small
24832 enough, but now @code{Main} depends on the body of @code{R} in
24833 @file{r.adb} as well as on the spec. This means that if this body is edited,
24834 the main program must be recompiled. Note that this extra dependency
24835 occurs whether or not the call is in fact inlined by @code{gcc}.
24837 The use of front end inlining with @option{-gnatN} generates similar
24838 additional dependencies.
24840 @cindex @code{^-fno-inline^/INLINE=SUPPRESS^} (@code{gcc})
24841 Note: The @code{^-fno-inline^/INLINE=SUPPRESS^} switch
24842 can be used to prevent
24843 all inlining. This switch overrides all other conditions and ensures
24844 that no inlining occurs. The extra dependences resulting from
24845 @option{-gnatn} will still be active, even if
24846 this switch is used to suppress the resulting inlining actions.
24848 Note regarding the use of @code{-O3}: There is no difference in inlining
24849 behavior between @code{-O2} and @code{-O3} for subprograms with an explicit
24850 pragma @code{Inline} assuming the use of @option{-gnatn}
24851 or @option{-gnatN} (the switches that activate inlining). If you have used
24852 pragma @code{Inline} in appropriate cases, then it is usually much better
24853 to use @code{-O2} and @option{-gnatn} and avoid the use of @code{-O3} which
24854 in this case only has the effect of inlining subprograms you did not
24855 think should be inlined. We often find that the use of @code{-O3} slows
24856 down code by performing excessive inlining, leading to increased instruction
24857 cache pressure from the increased code size. So the bottom line here is
24858 that you should not automatically assume that @code{-O3} is better than
24859 @code{-O2}, and indeed you should use @code{-O3} only if tests show that
24860 it actually improves performance.
24863 @node Coverage Analysis
24864 @section Coverage Analysis
24867 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
24868 the user to determine the distribution of execution time across a program,
24869 @pxref{Profiling} for details of usage.
24873 @c GNU Free Documentation License
24875 @node Index,,GNU Free Documentation License, Top