1 \input texinfo @c -*-texinfo-*-
3 @setfilename gnat_ugn.info
4 @documentencoding UTF-8
6 @*Generated by Sphinx 1.4.6.@*
8 @settitle GNAT User's Guide for Native Platforms
13 @dircategory GNU Ada Tools
15 * gnat_ugn: (gnat_ugn.info). gnat_ugn
18 @definfoenclose strong,`,'
19 @definfoenclose emph,`,'
24 GNAT User's Guide for Native Platforms , Sep 29, 2017
28 Copyright @copyright{} 2008-2017, Free Software Foundation
34 @title GNAT User's Guide for Native Platforms
39 @c %** start of user preamble
41 @c %** end of user preamble
45 @top GNAT User's Guide for Native Platforms
50 @anchor{gnat_ugn doc}@anchor{0}
51 @emph{GNAT, The GNU Ada Development Environment}
54 @include gcc-common.texi
55 GCC version @value{version-GCC}@*
58 Permission is granted to copy, distribute and/or modify this document
59 under the terms of the GNU Free Documentation License, Version 1.3 or
60 any later version published by the Free Software Foundation; with no
61 Invariant Sections, with the Front-Cover Texts being
62 "GNAT User's Guide for Native Platforms",
63 and with no Back-Cover Texts. A copy of the license is
64 included in the section entitled @ref{1,,GNU Free Documentation License}.
68 * Getting Started with GNAT::
69 * The GNAT Compilation Model::
70 * Building Executable Programs with GNAT::
71 * GNAT Utility Programs::
72 * GNAT and Program Execution::
73 * Platform-Specific Information::
74 * Example of Binder Output File::
75 * Elaboration Order Handling in GNAT::
77 * GNU Free Documentation License::
81 --- The Detailed Node Listing ---
85 * What This Guide Contains::
86 * What You Should Know before Reading This Guide::
87 * Related Information::
88 * A Note to Readers of Previous Versions of the Manual::
91 Getting Started with GNAT
94 * Running a Simple Ada Program::
95 * Running a Program with Multiple Units::
96 * Using the gnatmake Utility::
98 The GNAT Compilation Model
100 * Source Representation::
101 * Foreign Language Representation::
102 * File Naming Topics and Utilities::
103 * Configuration Pragmas::
104 * Generating Object Files::
105 * Source Dependencies::
106 * The Ada Library Information Files::
107 * Binding an Ada Program::
108 * GNAT and Libraries::
109 * Conditional Compilation::
110 * Mixed Language Programming::
111 * GNAT and Other Compilation Models::
112 * Using GNAT Files with External Tools::
114 Foreign Language Representation
117 * Other 8-Bit Codes::
118 * Wide_Character Encodings::
119 * Wide_Wide_Character Encodings::
121 File Naming Topics and Utilities
123 * File Naming Rules::
124 * Using Other File Names::
125 * Alternative File Naming Schemes::
126 * Handling Arbitrary File Naming Conventions with gnatname::
127 * File Name Krunching with gnatkr::
128 * Renaming Files with gnatchop::
130 Handling Arbitrary File Naming Conventions with gnatname
132 * Arbitrary File Naming Conventions::
134 * Switches for gnatname::
135 * Examples of gnatname Usage::
137 File Name Krunching with gnatkr
142 * Examples of gnatkr Usage::
144 Renaming Files with gnatchop
146 * Handling Files with Multiple Units::
147 * Operating gnatchop in Compilation Mode::
148 * Command Line for gnatchop::
149 * Switches for gnatchop::
150 * Examples of gnatchop Usage::
152 Configuration Pragmas
154 * Handling of Configuration Pragmas::
155 * The Configuration Pragmas Files::
159 * Introduction to Libraries in GNAT::
160 * General Ada Libraries::
161 * Stand-alone Ada Libraries::
162 * Rebuilding the GNAT Run-Time Library::
164 General Ada Libraries
166 * Building a library::
167 * Installing a library::
170 Stand-alone Ada Libraries
172 * Introduction to Stand-alone Libraries::
173 * Building a Stand-alone Library::
174 * Creating a Stand-alone Library to be used in a non-Ada context::
175 * Restrictions in Stand-alone Libraries::
177 Conditional Compilation
179 * Modeling Conditional Compilation in Ada::
180 * Preprocessing with gnatprep::
181 * Integrated Preprocessing::
183 Modeling Conditional Compilation in Ada
185 * Use of Boolean Constants::
186 * Debugging - A Special Case::
187 * Conditionalizing Declarations::
188 * Use of Alternative Implementations::
191 Preprocessing with gnatprep
193 * Preprocessing Symbols::
195 * Switches for gnatprep::
196 * Form of Definitions File::
197 * Form of Input Text for gnatprep::
199 Mixed Language Programming
202 * Calling Conventions::
203 * Building Mixed Ada and C++ Programs::
204 * Generating Ada Bindings for C and C++ headers::
205 * Generating C Headers for Ada Specifications::
207 Building Mixed Ada and C++ Programs
209 * Interfacing to C++::
210 * Linking a Mixed C++ & Ada Program::
212 * Interfacing with C++ constructors::
213 * Interfacing with C++ at the Class Level::
215 Generating Ada Bindings for C and C++ headers
217 * Running the Binding Generator::
218 * Generating Bindings for C++ Headers::
221 Generating C Headers for Ada Specifications
223 * Running the C Header Generator::
225 GNAT and Other Compilation Models
227 * Comparison between GNAT and C/C++ Compilation Models::
228 * Comparison between GNAT and Conventional Ada Library Models::
230 Using GNAT Files with External Tools
232 * Using Other Utility Programs with GNAT::
233 * The External Symbol Naming Scheme of GNAT::
235 Building Executable Programs with GNAT
237 * Building with gnatmake::
238 * Compiling with gcc::
239 * Compiler Switches::
241 * Binding with gnatbind::
242 * Linking with gnatlink::
243 * Using the GNU make Utility::
245 Building with gnatmake
248 * Switches for gnatmake::
249 * Mode Switches for gnatmake::
250 * Notes on the Command Line::
251 * How gnatmake Works::
252 * Examples of gnatmake Usage::
256 * Compiling Programs::
257 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL.
258 * Order of Compilation Issues::
263 * Alphabetical List of All Switches::
264 * Output and Error Message Control::
265 * Warning Message Control::
266 * Debugging and Assertion Control::
267 * Validity Checking::
270 * Using gcc for Syntax Checking::
271 * Using gcc for Semantic Checking::
272 * Compiling Different Versions of Ada::
273 * Character Set Control::
274 * File Naming Control::
275 * Subprogram Inlining Control::
276 * Auxiliary Output Control::
277 * Debugging Control::
278 * Exception Handling Control::
279 * Units to Sources Mapping Files::
280 * Code Generation Control::
282 Binding with gnatbind
285 * Switches for gnatbind::
286 * Command-Line Access::
287 * Search Paths for gnatbind::
288 * Examples of gnatbind Usage::
290 Switches for gnatbind
292 * Consistency-Checking Modes::
293 * Binder Error Message Control::
294 * Elaboration Control::
296 * Dynamic Allocation Control::
297 * Binding with Non-Ada Main Programs::
298 * Binding Programs with No Main Subprogram::
300 Linking with gnatlink
303 * Switches for gnatlink::
305 Using the GNU make Utility
307 * Using gnatmake in a Makefile::
308 * Automatically Creating a List of Directories::
309 * Generating the Command Line Switches::
310 * Overcoming Command Line Length Limits::
312 GNAT Utility Programs
314 * The File Cleanup Utility gnatclean::
315 * The GNAT Library Browser gnatls::
316 * The Cross-Referencing Tools gnatxref and gnatfind::
317 * The Ada to HTML Converter gnathtml::
319 The File Cleanup Utility gnatclean
321 * Running gnatclean::
322 * Switches for gnatclean::
324 The GNAT Library Browser gnatls
327 * Switches for gnatls::
328 * Example of gnatls Usage::
330 The Cross-Referencing Tools gnatxref and gnatfind
332 * gnatxref Switches::
333 * gnatfind Switches::
334 * Configuration Files for gnatxref and gnatfind::
335 * Regular Expressions in gnatfind and gnatxref::
336 * Examples of gnatxref Usage::
337 * Examples of gnatfind Usage::
339 Examples of gnatxref Usage
342 * Using gnatxref with vi::
344 The Ada to HTML Converter gnathtml
346 * Invoking gnathtml::
347 * Installing gnathtml::
349 GNAT and Program Execution
351 * Running and Debugging Ada Programs::
352 * Code Coverage and Profiling::
353 * Improving Performance::
354 * Overflow Check Handling in GNAT::
355 * Performing Dimensionality Analysis in GNAT::
356 * Stack Related Facilities::
357 * Memory Management Issues::
359 Running and Debugging Ada Programs
361 * The GNAT Debugger GDB::
363 * Introduction to GDB Commands::
364 * Using Ada Expressions::
365 * Calling User-Defined Subprograms::
366 * Using the next Command in a Function::
367 * Stopping When Ada Exceptions Are Raised::
369 * Debugging Generic Units::
370 * Remote Debugging with gdbserver::
371 * GNAT Abnormal Termination or Failure to Terminate::
372 * Naming Conventions for GNAT Source Files::
373 * Getting Internal Debugging Information::
375 * Pretty-Printers for the GNAT runtime::
379 * Non-Symbolic Traceback::
380 * Symbolic Traceback::
382 Code Coverage and Profiling
384 * Code Coverage of Ada Programs with gcov::
385 * Profiling an Ada Program with gprof::
387 Code Coverage of Ada Programs with gcov
389 * Quick startup guide::
392 Profiling an Ada Program with gprof
394 * Compilation for profiling::
395 * Program execution::
397 * Interpretation of profiling results::
399 Improving Performance
401 * Performance Considerations::
402 * Text_IO Suggestions::
403 * Reducing Size of Executables with Unused Subprogram/Data Elimination::
405 Performance Considerations
407 * Controlling Run-Time Checks::
408 * Use of Restrictions::
409 * Optimization Levels::
410 * Debugging Optimized Code::
411 * Inlining of Subprograms::
412 * Floating_Point_Operations::
413 * Vectorization of loops::
414 * Other Optimization Switches::
415 * Optimization and Strict Aliasing::
416 * Aliased Variables and Optimization::
417 * Atomic Variables and Optimization::
418 * Passive Task Optimization::
420 Reducing Size of Executables with Unused Subprogram/Data Elimination
422 * About unused subprogram/data elimination::
423 * Compilation options::
424 * Example of unused subprogram/data elimination::
426 Overflow Check Handling in GNAT
429 * Management of Overflows in GNAT::
430 * Specifying the Desired Mode::
432 * Implementation Notes::
434 Stack Related Facilities
436 * Stack Overflow Checking::
437 * Static Stack Usage Analysis::
438 * Dynamic Stack Usage Analysis::
440 Memory Management Issues
442 * Some Useful Memory Pools::
443 * The GNAT Debug Pool Facility::
445 Platform-Specific Information
447 * Run-Time Libraries::
448 * Specifying a Run-Time Library::
449 * Microsoft Windows Topics::
454 * Summary of Run-Time Configurations::
456 Specifying a Run-Time Library
458 * Choosing the Scheduling Policy::
460 Microsoft Windows Topics
462 * Using GNAT on Windows::
463 * Using a network installation of GNAT::
464 * CONSOLE and WINDOWS subsystems::
466 * Disabling Command Line Argument Expansion::
467 * Mixed-Language Programming on Windows::
468 * Windows Specific Add-Ons::
470 Mixed-Language Programming on Windows
472 * Windows Calling Conventions::
473 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs.
474 * Using DLLs with GNAT::
475 * Building DLLs with GNAT Project files::
476 * Building DLLs with GNAT::
477 * Building DLLs with gnatdll::
478 * Ada DLLs and Finalization::
479 * Creating a Spec for Ada DLLs::
480 * GNAT and Windows Resources::
481 * Using GNAT DLLs from Microsoft Visual Studio Applications::
483 * Setting Stack Size from gnatlink::
484 * Setting Heap Size from gnatlink::
486 Windows Calling Conventions
488 * C Calling Convention::
489 * Stdcall Calling Convention::
490 * Win32 Calling Convention::
491 * DLL Calling Convention::
495 * Creating an Ada Spec for the DLL Services::
496 * Creating an Import Library::
498 Building DLLs with gnatdll
500 * Limitations When Using Ada DLLs from Ada::
501 * Exporting Ada Entities::
502 * Ada DLLs and Elaboration::
504 Creating a Spec for Ada DLLs
506 * Creating the Definition File::
509 GNAT and Windows Resources
511 * Building Resources::
512 * Compiling Resources::
517 * Program and DLL Both Built with GCC/GNAT::
518 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
520 Windows Specific Add-Ons
527 * Codesigning the Debugger::
529 Elaboration Order Handling in GNAT
532 * Checking the Elaboration Order::
533 * Controlling the Elaboration Order::
534 * Controlling Elaboration in GNAT - Internal Calls::
535 * Controlling Elaboration in GNAT - External Calls::
536 * Default Behavior in GNAT - Ensuring Safety::
537 * Treatment of Pragma Elaborate::
538 * Elaboration Issues for Library Tasks::
539 * Mixing Elaboration Models::
540 * What to Do If the Default Elaboration Behavior Fails::
541 * Elaboration for Indirect Calls::
542 * Summary of Procedures for Elaboration Control::
543 * Other Elaboration Order Considerations::
544 * Determining the Chosen Elaboration Order::
548 * Basic Assembler Syntax::
549 * A Simple Example of Inline Assembler::
550 * Output Variables in Inline Assembler::
551 * Input Variables in Inline Assembler::
552 * Inlining Inline Assembler Code::
553 * Other Asm Functionality::
555 Other Asm Functionality
557 * The Clobber Parameter::
558 * The Volatile Parameter::
563 @node About This Guide,Getting Started with GNAT,Top,Top
564 @anchor{gnat_ugn/about_this_guide about-this-guide}@anchor{2}@anchor{gnat_ugn/about_this_guide doc}@anchor{3}@anchor{gnat_ugn/about_this_guide gnat-user-s-guide-for-native-platforms}@anchor{4}@anchor{gnat_ugn/about_this_guide id1}@anchor{5}
565 @chapter About This Guide
569 This guide describes the use of GNAT,
570 a compiler and software development
571 toolset for the full Ada programming language.
572 It documents the features of the compiler and tools, and explains
573 how to use them to build Ada applications.
575 GNAT implements Ada 95, Ada 2005 and Ada 2012, and it may also be
576 invoked in Ada 83 compatibility mode.
577 By default, GNAT assumes Ada 2012, but you can override with a
578 compiler switch (@ref{6,,Compiling Different Versions of Ada})
579 to explicitly specify the language version.
580 Throughout this manual, references to 'Ada' without a year suffix
581 apply to all Ada 95/2005/2012 versions of the language.
584 * What This Guide Contains::
585 * What You Should Know before Reading This Guide::
586 * Related Information::
587 * A Note to Readers of Previous Versions of the Manual::
592 @node What This Guide Contains,What You Should Know before Reading This Guide,,About This Guide
593 @anchor{gnat_ugn/about_this_guide what-this-guide-contains}@anchor{7}
594 @section What This Guide Contains
597 This guide contains the following chapters:
603 @ref{8,,Getting Started with GNAT} describes how to get started compiling
604 and running Ada programs with the GNAT Ada programming environment.
607 @ref{9,,The GNAT Compilation Model} describes the compilation model used
611 @ref{a,,Building Executable Programs with GNAT} describes how to use the
612 main GNAT tools to build executable programs, and it also gives examples of
613 using the GNU make utility with GNAT.
616 @ref{b,,GNAT Utility Programs} explains the various utility programs that
617 are included in the GNAT environment
620 @ref{c,,GNAT and Program Execution} covers a number of topics related to
621 running, debugging, and tuning the performace of programs developed
625 Appendices cover several additional topics:
631 @ref{d,,Platform-Specific Information} describes the different run-time
632 library implementations and also presents information on how to use
633 GNAT on several specific platforms
636 @ref{e,,Example of Binder Output File} shows the source code for the binder
637 output file for a sample program.
640 @ref{f,,Elaboration Order Handling in GNAT} describes how GNAT helps
641 you deal with elaboration order issues.
644 @ref{10,,Inline Assembler} shows how to use the inline assembly facility
648 @node What You Should Know before Reading This Guide,Related Information,What This Guide Contains,About This Guide
649 @anchor{gnat_ugn/about_this_guide what-you-should-know-before-reading-this-guide}@anchor{11}
650 @section What You Should Know before Reading This Guide
653 @geindex Ada 95 Language Reference Manual
655 @geindex Ada 2005 Language Reference Manual
657 This guide assumes a basic familiarity with the Ada 95 language, as
658 described in the International Standard ANSI/ISO/IEC-8652:1995, January
660 It does not require knowledge of the features introduced by Ada 2005
662 Reference manuals for Ada 95, Ada 2005, and Ada 2012 are included in
663 the GNAT documentation package.
665 @node Related Information,A Note to Readers of Previous Versions of the Manual,What You Should Know before Reading This Guide,About This Guide
666 @anchor{gnat_ugn/about_this_guide related-information}@anchor{12}
667 @section Related Information
670 For further information about Ada and related tools, please refer to the
677 @cite{Ada 95 Reference Manual}, @cite{Ada 2005 Reference Manual}, and
678 @cite{Ada 2012 Reference Manual}, which contain reference
679 material for the several revisions of the Ada language standard.
682 @cite{GNAT Reference_Manual}, which contains all reference material for the GNAT
683 implementation of Ada.
686 @cite{Using the GNAT Programming Studio}, which describes the GPS
687 Integrated Development Environment.
690 @cite{GNAT Programming Studio Tutorial}, which introduces the
691 main GPS features through examples.
694 @cite{Debugging with GDB},
695 for all details on the use of the GNU source-level debugger.
698 @cite{GNU Emacs Manual},
699 for full information on the extensible editor and programming
703 @node A Note to Readers of Previous Versions of the Manual,Conventions,Related Information,About This Guide
704 @anchor{gnat_ugn/about_this_guide a-note-to-readers-of-previous-versions-of-the-manual}@anchor{13}
705 @section A Note to Readers of Previous Versions of the Manual
708 In early 2015 the GNAT manuals were transitioned to the
709 reStructuredText (rst) / Sphinx documentation generator technology.
710 During that process the @cite{GNAT User's Guide} was reorganized
711 so that related topics would be described together in the same chapter
712 or appendix. Here's a summary of the major changes realized in
713 the new document structure.
719 @ref{9,,The GNAT Compilation Model} has been extended so that it now covers
720 the following material:
726 The @code{gnatname}, @code{gnatkr}, and @code{gnatchop} tools
729 @ref{14,,Configuration Pragmas}
732 @ref{15,,GNAT and Libraries}
735 @ref{16,,Conditional Compilation} including @ref{17,,Preprocessing with gnatprep}
736 and @ref{18,,Integrated Preprocessing}
739 @ref{19,,Generating Ada Bindings for C and C++ headers}
742 @ref{1a,,Using GNAT Files with External Tools}
746 @ref{a,,Building Executable Programs with GNAT} is a new chapter consolidating
747 the following content:
753 @ref{1b,,Building with gnatmake}
756 @ref{1c,,Compiling with gcc}
759 @ref{1d,,Binding with gnatbind}
762 @ref{1e,,Linking with gnatlink}
765 @ref{1f,,Using the GNU make Utility}
769 @ref{b,,GNAT Utility Programs} is a new chapter consolidating the information about several
777 @ref{20,,The File Cleanup Utility gnatclean}
780 @ref{21,,The GNAT Library Browser gnatls}
783 @ref{22,,The Cross-Referencing Tools gnatxref and gnatfind}
786 @ref{23,,The Ada to HTML Converter gnathtml}
790 @ref{c,,GNAT and Program Execution} is a new chapter consolidating the following:
796 @ref{24,,Running and Debugging Ada Programs}
799 @ref{25,,Code Coverage and Profiling}
802 @ref{26,,Improving Performance}
805 @ref{27,,Overflow Check Handling in GNAT}
808 @ref{28,,Performing Dimensionality Analysis in GNAT}
811 @ref{29,,Stack Related Facilities}
814 @ref{2a,,Memory Management Issues}
818 @ref{d,,Platform-Specific Information} is a new appendix consolidating the following:
824 @ref{2b,,Run-Time Libraries}
827 @ref{2c,,Microsoft Windows Topics}
830 @ref{2d,,Mac OS Topics}
834 The @emph{Compatibility and Porting Guide} appendix has been moved to the
835 @cite{GNAT Reference Manual}. It now includes a section
836 @emph{Writing Portable Fixed-Point Declarations} which was previously
837 a separate chapter in the @cite{GNAT User's Guide}.
840 @node Conventions,,A Note to Readers of Previous Versions of the Manual,About This Guide
841 @anchor{gnat_ugn/about_this_guide conventions}@anchor{2e}
846 @geindex typographical
848 @geindex Typographical conventions
850 Following are examples of the typographical and graphic conventions used
857 @code{Functions}, @code{utility program names}, @code{standard names},
873 [optional information or parameters]
876 Examples are described by text
879 and then shown this way.
883 Commands that are entered by the user are shown as preceded by a prompt string
884 comprising the @code{$} character followed by a space.
887 Full file names are shown with the '/' character
888 as the directory separator; e.g., @code{parent-dir/subdir/myfile.adb}.
889 If you are using GNAT on a Windows platform, please note that
890 the '\' character should be used instead.
893 @node Getting Started with GNAT,The GNAT Compilation Model,About This Guide,Top
894 @anchor{gnat_ugn/getting_started_with_gnat getting-started-with-gnat}@anchor{8}@anchor{gnat_ugn/getting_started_with_gnat doc}@anchor{2f}@anchor{gnat_ugn/getting_started_with_gnat id1}@anchor{30}
895 @chapter Getting Started with GNAT
898 This chapter describes how to use GNAT's command line interface to build
899 executable Ada programs.
900 On most platforms a visually oriented Integrated Development Environment
901 is also available, the GNAT Programming Studio (GPS).
902 GPS offers a graphical "look and feel", support for development in
903 other programming languages, comprehensive browsing features, and
904 many other capabilities.
905 For information on GPS please refer to
906 @cite{Using the GNAT Programming Studio}.
910 * Running a Simple Ada Program::
911 * Running a Program with Multiple Units::
912 * Using the gnatmake Utility::
916 @node Running GNAT,Running a Simple Ada Program,,Getting Started with GNAT
917 @anchor{gnat_ugn/getting_started_with_gnat running-gnat}@anchor{31}@anchor{gnat_ugn/getting_started_with_gnat id2}@anchor{32}
918 @section Running GNAT
921 Three steps are needed to create an executable file from an Ada source
928 The source file(s) must be compiled.
931 The file(s) must be bound using the GNAT binder.
934 All appropriate object files must be linked to produce an executable.
937 All three steps are most commonly handled by using the @code{gnatmake}
938 utility program that, given the name of the main program, automatically
939 performs the necessary compilation, binding and linking steps.
941 @node Running a Simple Ada Program,Running a Program with Multiple Units,Running GNAT,Getting Started with GNAT
942 @anchor{gnat_ugn/getting_started_with_gnat running-a-simple-ada-program}@anchor{33}@anchor{gnat_ugn/getting_started_with_gnat id3}@anchor{34}
943 @section Running a Simple Ada Program
946 Any text editor may be used to prepare an Ada program.
947 (If Emacs is used, the optional Ada mode may be helpful in laying out the
949 The program text is a normal text file. We will assume in our initial
950 example that you have used your editor to prepare the following
951 standard format text file:
954 with Ada.Text_IO; use Ada.Text_IO;
957 Put_Line ("Hello WORLD!");
961 This file should be named @code{hello.adb}.
962 With the normal default file naming conventions, GNAT requires
964 contain a single compilation unit whose file name is the
966 with periods replaced by hyphens; the
967 extension is @code{ads} for a
968 spec and @code{adb} for a body.
969 You can override this default file naming convention by use of the
970 special pragma @code{Source_File_Name} (for further information please
971 see @ref{35,,Using Other File Names}).
972 Alternatively, if you want to rename your files according to this default
973 convention, which is probably more convenient if you will be using GNAT
974 for all your compilations, then the @code{gnatchop} utility
975 can be used to generate correctly-named source files
976 (see @ref{36,,Renaming Files with gnatchop}).
978 You can compile the program using the following command (@code{$} is used
979 as the command prompt in the examples in this document):
985 @code{gcc} is the command used to run the compiler. This compiler is
986 capable of compiling programs in several languages, including Ada and
987 C. It assumes that you have given it an Ada program if the file extension is
988 either @code{.ads} or @code{.adb}, and it will then call
989 the GNAT compiler to compile the specified file.
991 The @code{-c} switch is required. It tells @code{gcc} to only do a
992 compilation. (For C programs, @code{gcc} can also do linking, but this
993 capability is not used directly for Ada programs, so the @code{-c}
994 switch must always be present.)
996 This compile command generates a file
997 @code{hello.o}, which is the object
998 file corresponding to your Ada program. It also generates
999 an 'Ada Library Information' file @code{hello.ali},
1000 which contains additional information used to check
1001 that an Ada program is consistent.
1002 To build an executable file,
1003 use @code{gnatbind} to bind the program
1004 and @code{gnatlink} to link it. The
1005 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1006 @code{ALI} file, but the default extension of @code{.ali} can
1007 be omitted. This means that in the most common case, the argument
1008 is simply the name of the main program:
1015 A simpler method of carrying out these steps is to use @code{gnatmake},
1016 a master program that invokes all the required
1017 compilation, binding and linking tools in the correct order. In particular,
1018 @code{gnatmake} automatically recompiles any sources that have been
1019 modified since they were last compiled, or sources that depend
1020 on such modified sources, so that 'version skew' is avoided.
1022 @geindex Version skew (avoided by `@w{`}gnatmake`@w{`})
1025 $ gnatmake hello.adb
1028 The result is an executable program called @code{hello}, which can be
1035 assuming that the current directory is on the search path
1036 for executable programs.
1038 and, if all has gone well, you will see:
1044 appear in response to this command.
1046 @node Running a Program with Multiple Units,Using the gnatmake Utility,Running a Simple Ada Program,Getting Started with GNAT
1047 @anchor{gnat_ugn/getting_started_with_gnat id4}@anchor{37}@anchor{gnat_ugn/getting_started_with_gnat running-a-program-with-multiple-units}@anchor{38}
1048 @section Running a Program with Multiple Units
1051 Consider a slightly more complicated example that has three files: a
1052 main program, and the spec and body of a package:
1055 package Greetings is
1060 with Ada.Text_IO; use Ada.Text_IO;
1061 package body Greetings is
1064 Put_Line ("Hello WORLD!");
1067 procedure Goodbye is
1069 Put_Line ("Goodbye WORLD!");
1081 Following the one-unit-per-file rule, place this program in the
1082 following three separate files:
1087 @item @emph{greetings.ads}
1089 spec of package @code{Greetings}
1091 @item @emph{greetings.adb}
1093 body of package @code{Greetings}
1095 @item @emph{gmain.adb}
1097 body of main program
1100 To build an executable version of
1101 this program, we could use four separate steps to compile, bind, and link
1102 the program, as follows:
1106 $ gcc -c greetings.adb
1111 Note that there is no required order of compilation when using GNAT.
1112 In particular it is perfectly fine to compile the main program first.
1113 Also, it is not necessary to compile package specs in the case where
1114 there is an accompanying body; you only need to compile the body. If you want
1115 to submit these files to the compiler for semantic checking and not code
1116 generation, then use the @code{-gnatc} switch:
1119 $ gcc -c greetings.ads -gnatc
1122 Although the compilation can be done in separate steps as in the
1123 above example, in practice it is almost always more convenient
1124 to use the @code{gnatmake} tool. All you need to know in this case
1125 is the name of the main program's source file. The effect of the above four
1126 commands can be achieved with a single one:
1129 $ gnatmake gmain.adb
1132 In the next section we discuss the advantages of using @code{gnatmake} in
1135 @node Using the gnatmake Utility,,Running a Program with Multiple Units,Getting Started with GNAT
1136 @anchor{gnat_ugn/getting_started_with_gnat using-the-gnatmake-utility}@anchor{39}@anchor{gnat_ugn/getting_started_with_gnat id5}@anchor{3a}
1137 @section Using the @code{gnatmake} Utility
1140 If you work on a program by compiling single components at a time using
1141 @code{gcc}, you typically keep track of the units you modify. In order to
1142 build a consistent system, you compile not only these units, but also any
1143 units that depend on the units you have modified.
1144 For example, in the preceding case,
1145 if you edit @code{gmain.adb}, you only need to recompile that file. But if
1146 you edit @code{greetings.ads}, you must recompile both
1147 @code{greetings.adb} and @code{gmain.adb}, because both files contain
1148 units that depend on @code{greetings.ads}.
1150 @code{gnatbind} will warn you if you forget one of these compilation
1151 steps, so that it is impossible to generate an inconsistent program as a
1152 result of forgetting to do a compilation. Nevertheless it is tedious and
1153 error-prone to keep track of dependencies among units.
1154 One approach to handle the dependency-bookkeeping is to use a
1155 makefile. However, makefiles present maintenance problems of their own:
1156 if the dependencies change as you change the program, you must make
1157 sure that the makefile is kept up-to-date manually, which is also an
1158 error-prone process.
1160 The @code{gnatmake} utility takes care of these details automatically.
1161 Invoke it using either one of the following forms:
1164 $ gnatmake gmain.adb
1168 The argument is the name of the file containing the main program;
1169 you may omit the extension. @code{gnatmake}
1170 examines the environment, automatically recompiles any files that need
1171 recompiling, and binds and links the resulting set of object files,
1172 generating the executable file, @code{gmain}.
1173 In a large program, it
1174 can be extremely helpful to use @code{gnatmake}, because working out by hand
1175 what needs to be recompiled can be difficult.
1177 Note that @code{gnatmake} takes into account all the Ada rules that
1178 establish dependencies among units. These include dependencies that result
1179 from inlining subprogram bodies, and from
1180 generic instantiation. Unlike some other
1181 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1182 found by the compiler on a previous compilation, which may possibly
1183 be wrong when sources change. @code{gnatmake} determines the exact set of
1184 dependencies from scratch each time it is run.
1186 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
1188 @node The GNAT Compilation Model,Building Executable Programs with GNAT,Getting Started with GNAT,Top
1189 @anchor{gnat_ugn/the_gnat_compilation_model doc}@anchor{3b}@anchor{gnat_ugn/the_gnat_compilation_model the-gnat-compilation-model}@anchor{9}@anchor{gnat_ugn/the_gnat_compilation_model id1}@anchor{3c}
1190 @chapter The GNAT Compilation Model
1193 @geindex GNAT compilation model
1195 @geindex Compilation model
1197 This chapter describes the compilation model used by GNAT. Although
1198 similar to that used by other languages such as C and C++, this model
1199 is substantially different from the traditional Ada compilation models,
1200 which are based on a centralized program library. The chapter covers
1201 the following material:
1207 Topics related to source file makeup and naming
1213 @ref{3d,,Source Representation}
1216 @ref{3e,,Foreign Language Representation}
1219 @ref{3f,,File Naming Topics and Utilities}
1223 @ref{14,,Configuration Pragmas}
1226 @ref{40,,Generating Object Files}
1229 @ref{41,,Source Dependencies}
1232 @ref{42,,The Ada Library Information Files}
1235 @ref{43,,Binding an Ada Program}
1238 @ref{15,,GNAT and Libraries}
1241 @ref{16,,Conditional Compilation}
1244 @ref{44,,Mixed Language Programming}
1247 @ref{45,,GNAT and Other Compilation Models}
1250 @ref{1a,,Using GNAT Files with External Tools}
1254 * Source Representation::
1255 * Foreign Language Representation::
1256 * File Naming Topics and Utilities::
1257 * Configuration Pragmas::
1258 * Generating Object Files::
1259 * Source Dependencies::
1260 * The Ada Library Information Files::
1261 * Binding an Ada Program::
1262 * GNAT and Libraries::
1263 * Conditional Compilation::
1264 * Mixed Language Programming::
1265 * GNAT and Other Compilation Models::
1266 * Using GNAT Files with External Tools::
1270 @node Source Representation,Foreign Language Representation,,The GNAT Compilation Model
1271 @anchor{gnat_ugn/the_gnat_compilation_model source-representation}@anchor{3d}@anchor{gnat_ugn/the_gnat_compilation_model id2}@anchor{46}
1272 @section Source Representation
1283 Ada source programs are represented in standard text files, using
1284 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1285 7-bit ASCII set, plus additional characters used for
1286 representing foreign languages (see @ref{3e,,Foreign Language Representation}
1287 for support of non-USA character sets). The format effector characters
1288 are represented using their standard ASCII encodings, as follows:
1293 @multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxx}
1370 Source files are in standard text file format. In addition, GNAT will
1371 recognize a wide variety of stream formats, in which the end of
1372 physical lines is marked by any of the following sequences:
1373 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1374 in accommodating files that are imported from other operating systems.
1376 @geindex End of source file; Source file@comma{} end
1378 @geindex SUB (control character)
1380 The end of a source file is normally represented by the physical end of
1381 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1382 recognized as signalling the end of the source file. Again, this is
1383 provided for compatibility with other operating systems where this
1384 code is used to represent the end of file.
1386 @geindex spec (definition)
1387 @geindex compilation (definition)
1389 Each file contains a single Ada compilation unit, including any pragmas
1390 associated with the unit. For example, this means you must place a
1391 package declaration (a package @emph{spec}) and the corresponding body in
1392 separate files. An Ada @emph{compilation} (which is a sequence of
1393 compilation units) is represented using a sequence of files. Similarly,
1394 you will place each subunit or child unit in a separate file.
1396 @node Foreign Language Representation,File Naming Topics and Utilities,Source Representation,The GNAT Compilation Model
1397 @anchor{gnat_ugn/the_gnat_compilation_model foreign-language-representation}@anchor{3e}@anchor{gnat_ugn/the_gnat_compilation_model id3}@anchor{47}
1398 @section Foreign Language Representation
1401 GNAT supports the standard character sets defined in Ada as well as
1402 several other non-standard character sets for use in localized versions
1403 of the compiler (@ref{48,,Character Set Control}).
1407 * Other 8-Bit Codes::
1408 * Wide_Character Encodings::
1409 * Wide_Wide_Character Encodings::
1413 @node Latin-1,Other 8-Bit Codes,,Foreign Language Representation
1414 @anchor{gnat_ugn/the_gnat_compilation_model id4}@anchor{49}@anchor{gnat_ugn/the_gnat_compilation_model latin-1}@anchor{4a}
1420 The basic character set is Latin-1. This character set is defined by ISO
1421 standard 8859, part 1. The lower half (character codes @code{16#00#}
1422 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper
1423 half is used to represent additional characters. These include extended letters
1424 used by European languages, such as French accents, the vowels with umlauts
1425 used in German, and the extra letter A-ring used in Swedish.
1427 @geindex Ada.Characters.Latin_1
1429 For a complete list of Latin-1 codes and their encodings, see the source
1430 file of library unit @code{Ada.Characters.Latin_1} in file
1431 @code{a-chlat1.ads}.
1432 You may use any of these extended characters freely in character or
1433 string literals. In addition, the extended characters that represent
1434 letters can be used in identifiers.
1436 @node Other 8-Bit Codes,Wide_Character Encodings,Latin-1,Foreign Language Representation
1437 @anchor{gnat_ugn/the_gnat_compilation_model other-8-bit-codes}@anchor{4b}@anchor{gnat_ugn/the_gnat_compilation_model id5}@anchor{4c}
1438 @subsection Other 8-Bit Codes
1441 GNAT also supports several other 8-bit coding schemes:
1450 @item @emph{ISO 8859-2 (Latin-2)}
1452 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1463 @item @emph{ISO 8859-3 (Latin-3)}
1465 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1476 @item @emph{ISO 8859-4 (Latin-4)}
1478 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1489 @item @emph{ISO 8859-5 (Cyrillic)}
1491 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1492 lowercase equivalence.
1495 @geindex ISO 8859-15
1502 @item @emph{ISO 8859-15 (Latin-9)}
1504 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1505 lowercase equivalence
1508 @geindex code page 437 (IBM PC)
1513 @item @emph{IBM PC (code page 437)}
1515 This code page is the normal default for PCs in the U.S. It corresponds
1516 to the original IBM PC character set. This set has some, but not all, of
1517 the extended Latin-1 letters, but these letters do not have the same
1518 encoding as Latin-1. In this mode, these letters are allowed in
1519 identifiers with uppercase and lowercase equivalence.
1522 @geindex code page 850 (IBM PC)
1527 @item @emph{IBM PC (code page 850)}
1529 This code page is a modification of 437 extended to include all the
1530 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1531 mode, all these letters are allowed in identifiers with uppercase and
1532 lowercase equivalence.
1534 @item @emph{Full Upper 8-bit}
1536 Any character in the range 80-FF allowed in identifiers, and all are
1537 considered distinct. In other words, there are no uppercase and lowercase
1538 equivalences in this range. This is useful in conjunction with
1539 certain encoding schemes used for some foreign character sets (e.g.,
1540 the typical method of representing Chinese characters on the PC).
1542 @item @emph{No Upper-Half}
1544 No upper-half characters in the range 80-FF are allowed in identifiers.
1545 This gives Ada 83 compatibility for identifier names.
1548 For precise data on the encodings permitted, and the uppercase and lowercase
1549 equivalences that are recognized, see the file @code{csets.adb} in
1550 the GNAT compiler sources. You will need to obtain a full source release
1551 of GNAT to obtain this file.
1553 @node Wide_Character Encodings,Wide_Wide_Character Encodings,Other 8-Bit Codes,Foreign Language Representation
1554 @anchor{gnat_ugn/the_gnat_compilation_model id6}@anchor{4d}@anchor{gnat_ugn/the_gnat_compilation_model wide-character-encodings}@anchor{4e}
1555 @subsection Wide_Character Encodings
1558 GNAT allows wide character codes to appear in character and string
1559 literals, and also optionally in identifiers, by means of the following
1560 possible encoding schemes:
1565 @item @emph{Hex Coding}
1567 In this encoding, a wide character is represented by the following five
1574 where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1575 characters (using uppercase letters) of the wide character code. For
1576 example, ESC A345 is used to represent the wide character with code
1578 This scheme is compatible with use of the full Wide_Character set.
1580 @item @emph{Upper-Half Coding}
1582 @geindex Upper-Half Coding
1584 The wide character with encoding @code{16#abcd#} where the upper bit is on
1585 (in other words, 'a' is in the range 8-F) is represented as two bytes,
1586 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1587 character, but is not required to be in the upper half. This method can
1588 be also used for shift-JIS or EUC, where the internal coding matches the
1591 @item @emph{Shift JIS Coding}
1593 @geindex Shift JIS Coding
1595 A wide character is represented by a two-character sequence,
1597 @code{16#cd#}, with the restrictions described for upper-half encoding as
1598 described above. The internal character code is the corresponding JIS
1599 character according to the standard algorithm for Shift-JIS
1600 conversion. Only characters defined in the JIS code set table can be
1601 used with this encoding method.
1603 @item @emph{EUC Coding}
1607 A wide character is represented by a two-character sequence
1609 @code{16#cd#}, with both characters being in the upper half. The internal
1610 character code is the corresponding JIS character according to the EUC
1611 encoding algorithm. Only characters defined in the JIS code set table
1612 can be used with this encoding method.
1614 @item @emph{UTF-8 Coding}
1616 A wide character is represented using
1617 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1618 10646-1/Am.2. Depending on the character value, the representation
1619 is a one, two, or three byte sequence:
1622 16#0000#-16#007f#: 2#0xxxxxxx#
1623 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1624 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1627 where the @code{xxx} bits correspond to the left-padded bits of the
1628 16-bit character value. Note that all lower half ASCII characters
1629 are represented as ASCII bytes and all upper half characters and
1630 other wide characters are represented as sequences of upper-half
1631 (The full UTF-8 scheme allows for encoding 31-bit characters as
1632 6-byte sequences, and in the following section on wide wide
1633 characters, the use of these sequences is documented).
1635 @item @emph{Brackets Coding}
1637 In this encoding, a wide character is represented by the following eight
1644 where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1645 characters (using uppercase letters) of the wide character code. For
1646 example, ['A345'] is used to represent the wide character with code
1647 @code{16#A345#}. It is also possible (though not required) to use the
1648 Brackets coding for upper half characters. For example, the code
1649 @code{16#A3#} can be represented as @code{['A3']}.
1651 This scheme is compatible with use of the full Wide_Character set,
1652 and is also the method used for wide character encoding in some standard
1653 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1658 Some of these coding schemes do not permit the full use of the
1659 Ada character set. For example, neither Shift JIS nor EUC allow the
1660 use of the upper half of the Latin-1 set.
1664 @node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1665 @anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{4f}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{50}
1666 @subsection Wide_Wide_Character Encodings
1669 GNAT allows wide wide character codes to appear in character and string
1670 literals, and also optionally in identifiers, by means of the following
1671 possible encoding schemes:
1676 @item @emph{UTF-8 Coding}
1678 A wide character is represented using
1679 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1680 10646-1/Am.2. Depending on the character value, the representation
1681 of character codes with values greater than 16#FFFF# is a
1682 is a four, five, or six byte sequence:
1685 16#01_0000#-16#10_FFFF#: 11110xxx 10xxxxxx 10xxxxxx
1687 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1689 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1690 10xxxxxx 10xxxxxx 10xxxxxx
1693 where the @code{xxx} bits correspond to the left-padded bits of the
1694 32-bit character value.
1696 @item @emph{Brackets Coding}
1698 In this encoding, a wide wide character is represented by the following ten or
1699 twelve byte character sequence:
1703 [ " a b c d e f g h " ]
1706 where @code{a-h} are the six or eight hexadecimal
1707 characters (using uppercase letters) of the wide wide character code. For
1708 example, ["1F4567"] is used to represent the wide wide character with code
1709 @code{16#001F_4567#}.
1711 This scheme is compatible with use of the full Wide_Wide_Character set,
1712 and is also the method used for wide wide character encoding in some standard
1713 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1716 @node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1717 @anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{3f}
1718 @section File Naming Topics and Utilities
1721 GNAT has a default file naming scheme and also provides the user with
1722 a high degree of control over how the names and extensions of the
1723 source files correspond to the Ada compilation units that they contain.
1726 * File Naming Rules::
1727 * Using Other File Names::
1728 * Alternative File Naming Schemes::
1729 * Handling Arbitrary File Naming Conventions with gnatname::
1730 * File Name Krunching with gnatkr::
1731 * Renaming Files with gnatchop::
1735 @node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1736 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{52}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{53}
1737 @subsection File Naming Rules
1740 The default file name is determined by the name of the unit that the
1741 file contains. The name is formed by taking the full expanded name of
1742 the unit and replacing the separating dots with hyphens and using
1743 lowercase for all letters.
1745 An exception arises if the file name generated by the above rules starts
1746 with one of the characters
1747 @code{a}, @code{g}, @code{i}, or @code{s}, and the second character is a
1748 minus. In this case, the character tilde is used in place
1749 of the minus. The reason for this special rule is to avoid clashes with
1750 the standard names for child units of the packages System, Ada,
1751 Interfaces, and GNAT, which use the prefixes
1752 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
1755 The file extension is @code{.ads} for a spec and
1756 @code{.adb} for a body. The following table shows some
1757 examples of these rules.
1762 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
1769 Ada Compilation Unit
1789 @code{arith_functions.ads}
1793 Arith_Functions (package spec)
1797 @code{arith_functions.adb}
1801 Arith_Functions (package body)
1805 @code{func-spec.ads}
1809 Func.Spec (child package spec)
1813 @code{func-spec.adb}
1817 Func.Spec (child package body)
1825 Sub (subunit of Main)
1833 A.Bad (child package body)
1839 Following these rules can result in excessively long
1840 file names if corresponding
1841 unit names are long (for example, if child units or subunits are
1842 heavily nested). An option is available to shorten such long file names
1843 (called file name 'krunching'). This may be particularly useful when
1844 programs being developed with GNAT are to be used on operating systems
1845 with limited file name lengths. @ref{54,,Using gnatkr}.
1847 Of course, no file shortening algorithm can guarantee uniqueness over
1848 all possible unit names; if file name krunching is used, it is your
1849 responsibility to ensure no name clashes occur. Alternatively you
1850 can specify the exact file names that you want used, as described
1851 in the next section. Finally, if your Ada programs are migrating from a
1852 compiler with a different naming convention, you can use the gnatchop
1853 utility to produce source files that follow the GNAT naming conventions.
1854 (For details see @ref{36,,Renaming Files with gnatchop}.)
1856 Note: in the case of Windows or Mac OS operating systems, case is not
1857 significant. So for example on Windows if the canonical name is
1858 @code{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1859 However, case is significant for other operating systems, so for example,
1860 if you want to use other than canonically cased file names on a Unix system,
1861 you need to follow the procedures described in the next section.
1863 @node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1864 @anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{55}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{35}
1865 @subsection Using Other File Names
1870 In the previous section, we have described the default rules used by
1871 GNAT to determine the file name in which a given unit resides. It is
1872 often convenient to follow these default rules, and if you follow them,
1873 the compiler knows without being explicitly told where to find all
1876 @geindex Source_File_Name pragma
1878 However, in some cases, particularly when a program is imported from
1879 another Ada compiler environment, it may be more convenient for the
1880 programmer to specify which file names contain which units. GNAT allows
1881 arbitrary file names to be used by means of the Source_File_Name pragma.
1882 The form of this pragma is as shown in the following examples:
1885 pragma Source_File_Name (My_Utilities.Stacks,
1886 Spec_File_Name => "myutilst_a.ada");
1887 pragma Source_File_name (My_Utilities.Stacks,
1888 Body_File_Name => "myutilst.ada");
1891 As shown in this example, the first argument for the pragma is the unit
1892 name (in this example a child unit). The second argument has the form
1893 of a named association. The identifier
1894 indicates whether the file name is for a spec or a body;
1895 the file name itself is given by a string literal.
1897 The source file name pragma is a configuration pragma, which means that
1898 normally it will be placed in the @code{gnat.adc}
1899 file used to hold configuration
1900 pragmas that apply to a complete compilation environment.
1901 For more details on how the @code{gnat.adc} file is created and used
1902 see @ref{56,,Handling of Configuration Pragmas}.
1906 GNAT allows completely arbitrary file names to be specified using the
1907 source file name pragma. However, if the file name specified has an
1908 extension other than @code{.ads} or @code{.adb} it is necessary to use
1909 a special syntax when compiling the file. The name in this case must be
1910 preceded by the special sequence @code{-x} followed by a space and the name
1911 of the language, here @code{ada}, as in:
1914 $ gcc -c -x ada peculiar_file_name.sim
1917 @code{gnatmake} handles non-standard file names in the usual manner (the
1918 non-standard file name for the main program is simply used as the
1919 argument to gnatmake). Note that if the extension is also non-standard,
1920 then it must be included in the @code{gnatmake} command, it may not
1923 @node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
1924 @anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{57}@anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{58}
1925 @subsection Alternative File Naming Schemes
1928 @geindex File naming schemes
1929 @geindex alternative
1933 The previous section described the use of the @code{Source_File_Name}
1934 pragma to allow arbitrary names to be assigned to individual source files.
1935 However, this approach requires one pragma for each file, and especially in
1936 large systems can result in very long @code{gnat.adc} files, and also create
1937 a maintenance problem.
1939 @geindex Source_File_Name pragma
1941 GNAT also provides a facility for specifying systematic file naming schemes
1942 other than the standard default naming scheme previously described. An
1943 alternative scheme for naming is specified by the use of
1944 @code{Source_File_Name} pragmas having the following format:
1947 pragma Source_File_Name (
1948 Spec_File_Name => FILE_NAME_PATTERN
1949 [ , Casing => CASING_SPEC]
1950 [ , Dot_Replacement => STRING_LITERAL ] );
1952 pragma Source_File_Name (
1953 Body_File_Name => FILE_NAME_PATTERN
1954 [ , Casing => CASING_SPEC ]
1955 [ , Dot_Replacement => STRING_LITERAL ] ) ;
1957 pragma Source_File_Name (
1958 Subunit_File_Name => FILE_NAME_PATTERN
1959 [ , Casing => CASING_SPEC ]
1960 [ , Dot_Replacement => STRING_LITERAL ] ) ;
1962 FILE_NAME_PATTERN ::= STRING_LITERAL
1963 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1966 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1967 It contains a single asterisk character, and the unit name is substituted
1968 systematically for this asterisk. The optional parameter
1969 @code{Casing} indicates
1970 whether the unit name is to be all upper-case letters, all lower-case letters,
1971 or mixed-case. If no
1972 @code{Casing} parameter is used, then the default is all
1975 The optional @code{Dot_Replacement} string is used to replace any periods
1976 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1977 argument is used then separating dots appear unchanged in the resulting
1979 Although the above syntax indicates that the
1980 @code{Casing} argument must appear
1981 before the @code{Dot_Replacement} argument, but it
1982 is also permissible to write these arguments in the opposite order.
1984 As indicated, it is possible to specify different naming schemes for
1985 bodies, specs, and subunits. Quite often the rule for subunits is the
1986 same as the rule for bodies, in which case, there is no need to give
1987 a separate @code{Subunit_File_Name} rule, and in this case the
1988 @code{Body_File_name} rule is used for subunits as well.
1990 The separate rule for subunits can also be used to implement the rather
1991 unusual case of a compilation environment (e.g., a single directory) which
1992 contains a subunit and a child unit with the same unit name. Although
1993 both units cannot appear in the same partition, the Ada Reference Manual
1994 allows (but does not require) the possibility of the two units coexisting
1995 in the same environment.
1997 The file name translation works in the following steps:
2003 If there is a specific @code{Source_File_Name} pragma for the given unit,
2004 then this is always used, and any general pattern rules are ignored.
2007 If there is a pattern type @code{Source_File_Name} pragma that applies to
2008 the unit, then the resulting file name will be used if the file exists. If
2009 more than one pattern matches, the latest one will be tried first, and the
2010 first attempt resulting in a reference to a file that exists will be used.
2013 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2014 for which the corresponding file exists, then the standard GNAT default
2015 naming rules are used.
2018 As an example of the use of this mechanism, consider a commonly used scheme
2019 in which file names are all lower case, with separating periods copied
2020 unchanged to the resulting file name, and specs end with @code{.1.ada}, and
2021 bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
2025 pragma Source_File_Name
2026 (Spec_File_Name => ".1.ada");
2027 pragma Source_File_Name
2028 (Body_File_Name => ".2.ada");
2031 The default GNAT scheme is actually implemented by providing the following
2032 default pragmas internally:
2035 pragma Source_File_Name
2036 (Spec_File_Name => ".ads", Dot_Replacement => "-");
2037 pragma Source_File_Name
2038 (Body_File_Name => ".adb", Dot_Replacement => "-");
2041 Our final example implements a scheme typically used with one of the
2042 Ada 83 compilers, where the separator character for subunits was '__'
2043 (two underscores), specs were identified by adding @code{_.ADA}, bodies
2044 by adding @code{.ADA}, and subunits by
2045 adding @code{.SEP}. All file names were
2046 upper case. Child units were not present of course since this was an
2047 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2048 the same double underscore separator for child units.
2051 pragma Source_File_Name
2052 (Spec_File_Name => "_.ADA",
2053 Dot_Replacement => "__",
2054 Casing = Uppercase);
2055 pragma Source_File_Name
2056 (Body_File_Name => ".ADA",
2057 Dot_Replacement => "__",
2058 Casing = Uppercase);
2059 pragma Source_File_Name
2060 (Subunit_File_Name => ".SEP",
2061 Dot_Replacement => "__",
2062 Casing = Uppercase);
2067 @node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
2068 @anchor{gnat_ugn/the_gnat_compilation_model handling-arbitrary-file-naming-conventions-with-gnatname}@anchor{59}@anchor{gnat_ugn/the_gnat_compilation_model id12}@anchor{5a}
2069 @subsection Handling Arbitrary File Naming Conventions with @code{gnatname}
2072 @geindex File Naming Conventions
2075 * Arbitrary File Naming Conventions::
2076 * Running gnatname::
2077 * Switches for gnatname::
2078 * Examples of gnatname Usage::
2082 @node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
2083 @anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{5b}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{5c}
2084 @subsubsection Arbitrary File Naming Conventions
2087 The GNAT compiler must be able to know the source file name of a compilation
2088 unit. When using the standard GNAT default file naming conventions
2089 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
2090 does not need additional information.
2092 When the source file names do not follow the standard GNAT default file naming
2093 conventions, the GNAT compiler must be given additional information through
2094 a configuration pragmas file (@ref{14,,Configuration Pragmas})
2096 When the non-standard file naming conventions are well-defined,
2097 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
2098 (@ref{58,,Alternative File Naming Schemes}) may be sufficient. However,
2099 if the file naming conventions are irregular or arbitrary, a number
2100 of pragma @code{Source_File_Name} for individual compilation units
2102 To help maintain the correspondence between compilation unit names and
2103 source file names within the compiler,
2104 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
2107 @node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
2108 @anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{5d}@anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{5e}
2109 @subsubsection Running @code{gnatname}
2112 The usual form of the @code{gnatname} command is:
2115 $ gnatname [ switches ] naming_pattern [ naming_patterns ]
2116 [--and [ switches ] naming_pattern [ naming_patterns ]]
2119 All of the arguments are optional. If invoked without any argument,
2120 @code{gnatname} will display its usage.
2122 When used with at least one naming pattern, @code{gnatname} will attempt to
2123 find all the compilation units in files that follow at least one of the
2124 naming patterns. To find these compilation units,
2125 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
2128 One or several Naming Patterns may be given as arguments to @code{gnatname}.
2129 Each Naming Pattern is enclosed between double quotes (or single
2131 A Naming Pattern is a regular expression similar to the wildcard patterns
2132 used in file names by the Unix shells or the DOS prompt.
2134 @code{gnatname} may be called with several sections of directories/patterns.
2135 Sections are separated by the switch @code{--and}. In each section, there must be
2136 at least one pattern. If no directory is specified in a section, the current
2137 directory (or the project directory if @code{-P} is used) is implied.
2138 The options other that the directory switches and the patterns apply globally
2139 even if they are in different sections.
2141 Examples of Naming Patterns are:
2149 For a more complete description of the syntax of Naming Patterns,
2150 see the second kind of regular expressions described in @code{g-regexp.ads}
2151 (the 'Glob' regular expressions).
2153 When invoked without the switch @code{-P}, @code{gnatname} will create a
2154 configuration pragmas file @code{gnat.adc} in the current working directory,
2155 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
2158 @node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
2159 @anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{5f}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{60}
2160 @subsubsection Switches for @code{gnatname}
2163 Switches for @code{gnatname} must precede any specified Naming Pattern.
2165 You may specify any of the following switches to @code{gnatname}:
2167 @geindex --version (gnatname)
2172 @item @code{--version}
2174 Display Copyright and version, then exit disregarding all other options.
2177 @geindex --help (gnatname)
2184 If @code{--version} was not used, display usage, then exit disregarding
2187 @item @code{--subdirs=@emph{dir}}
2189 Real object, library or exec directories are subdirectories <dir> of the
2192 @item @code{--no-backup}
2194 Do not create a backup copy of an existing project file.
2198 Start another section of directories/patterns.
2201 @geindex -c (gnatname)
2206 @item @code{-c@emph{filename}}
2208 Create a configuration pragmas file @code{filename} (instead of the default
2210 There may be zero, one or more space between @code{-c} and
2212 @code{filename} may include directory information. @code{filename} must be
2213 writable. There may be only one switch @code{-c}.
2214 When a switch @code{-c} is
2215 specified, no switch @code{-P} may be specified (see below).
2218 @geindex -d (gnatname)
2223 @item @code{-d@emph{dir}}
2225 Look for source files in directory @code{dir}. There may be zero, one or more
2226 spaces between @code{-d} and @code{dir}.
2227 @code{dir} may end with @code{/**}, that is it may be of the form
2228 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
2229 subdirectories, recursively, have to be searched for sources.
2230 When a switch @code{-d}
2231 is specified, the current working directory will not be searched for source
2232 files, unless it is explicitly specified with a @code{-d}
2233 or @code{-D} switch.
2234 Several switches @code{-d} may be specified.
2235 If @code{dir} is a relative path, it is relative to the directory of
2236 the configuration pragmas file specified with switch
2238 or to the directory of the project file specified with switch
2240 if neither switch @code{-c}
2241 nor switch @code{-P} are specified, it is relative to the
2242 current working directory. The directory
2243 specified with switch @code{-d} must exist and be readable.
2246 @geindex -D (gnatname)
2251 @item @code{-D@emph{filename}}
2253 Look for source files in all directories listed in text file @code{filename}.
2254 There may be zero, one or more spaces between @code{-D}
2255 and @code{filename}.
2256 @code{filename} must be an existing, readable text file.
2257 Each nonempty line in @code{filename} must be a directory.
2258 Specifying switch @code{-D} is equivalent to specifying as many
2259 switches @code{-d} as there are nonempty lines in
2264 Follow symbolic links when processing project files.
2266 @geindex -f (gnatname)
2268 @item @code{-f@emph{pattern}}
2270 Foreign patterns. Using this switch, it is possible to add sources of languages
2271 other than Ada to the list of sources of a project file.
2272 It is only useful if a -P switch is used.
2276 gnatname -Pprj -f"*.c" "*.ada"
2279 will look for Ada units in all files with the @code{.ada} extension,
2280 and will add to the list of file for project @code{prj.gpr} the C files
2281 with extension @code{.c}.
2283 @geindex -h (gnatname)
2287 Output usage (help) information. The output is written to @code{stdout}.
2289 @geindex -P (gnatname)
2291 @item @code{-P@emph{proj}}
2293 Create or update project file @code{proj}. There may be zero, one or more space
2294 between @code{-P} and @code{proj}. @code{proj} may include directory
2295 information. @code{proj} must be writable.
2296 There may be only one switch @code{-P}.
2297 When a switch @code{-P} is specified,
2298 no switch @code{-c} may be specified.
2299 On all platforms, except on VMS, when @code{gnatname} is invoked for an
2300 existing project file <proj>.gpr, a backup copy of the project file is created
2301 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
2302 non negative number that makes this backup copy a new file.
2304 @geindex -v (gnatname)
2308 Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2309 This includes name of the file written, the name of the directories to search
2310 and, for each file in those directories whose name matches at least one of
2311 the Naming Patterns, an indication of whether the file contains a unit,
2312 and if so the name of the unit.
2315 @geindex -v -v (gnatname)
2322 Very Verbose mode. In addition to the output produced in verbose mode,
2323 for each file in the searched directories whose name matches none of
2324 the Naming Patterns, an indication is given that there is no match.
2326 @geindex -x (gnatname)
2328 @item @code{-x@emph{pattern}}
2330 Excluded patterns. Using this switch, it is possible to exclude some files
2331 that would match the name patterns. For example,
2334 gnatname -x "*_nt.ada" "*.ada"
2337 will look for Ada units in all files with the @code{.ada} extension,
2338 except those whose names end with @code{_nt.ada}.
2341 @node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2342 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{61}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{62}
2343 @subsubsection Examples of @code{gnatname} Usage
2347 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2350 In this example, the directory @code{/home/me} must already exist
2351 and be writable. In addition, the directory
2352 @code{/home/me/sources} (specified by
2353 @code{-d sources}) must exist and be readable.
2355 Note the optional spaces after @code{-c} and @code{-d}.
2358 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
2359 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2362 Note that several switches @code{-d} may be used,
2363 even in conjunction with one or several switches
2364 @code{-D}. Several Naming Patterns and one excluded pattern
2365 are used in this example.
2367 @node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2368 @anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{63}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{64}
2369 @subsection File Name Krunching with @code{gnatkr}
2374 This section discusses the method used by the compiler to shorten
2375 the default file names chosen for Ada units so that they do not
2376 exceed the maximum length permitted. It also describes the
2377 @code{gnatkr} utility that can be used to determine the result of
2378 applying this shortening.
2383 * Krunching Method::
2384 * Examples of gnatkr Usage::
2388 @node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2389 @anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{66}
2390 @subsubsection About @code{gnatkr}
2393 The default file naming rule in GNAT
2394 is that the file name must be derived from
2395 the unit name. The exact default rule is as follows:
2401 Take the unit name and replace all dots by hyphens.
2404 If such a replacement occurs in the
2405 second character position of a name, and the first character is
2406 @code{a}, @code{g}, @code{s}, or @code{i},
2407 then replace the dot by the character
2411 The reason for this exception is to avoid clashes
2412 with the standard names for children of System, Ada, Interfaces,
2413 and GNAT, which use the prefixes
2414 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
2418 The @code{-gnatk@emph{nn}}
2419 switch of the compiler activates a 'krunching'
2420 circuit that limits file names to nn characters (where nn is a decimal
2423 The @code{gnatkr} utility can be used to determine the krunched name for
2424 a given file, when krunched to a specified maximum length.
2426 @node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2427 @anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{67}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{54}
2428 @subsubsection Using @code{gnatkr}
2431 The @code{gnatkr} command has the form:
2434 $ gnatkr name [ length ]
2437 @code{name} is the uncrunched file name, derived from the name of the unit
2438 in the standard manner described in the previous section (i.e., in particular
2439 all dots are replaced by hyphens). The file name may or may not have an
2440 extension (defined as a suffix of the form period followed by arbitrary
2441 characters other than period). If an extension is present then it will
2442 be preserved in the output. For example, when krunching @code{hellofile.ads}
2443 to eight characters, the result will be hellofil.ads.
2445 Note: for compatibility with previous versions of @code{gnatkr} dots may
2446 appear in the name instead of hyphens, but the last dot will always be
2447 taken as the start of an extension. So if @code{gnatkr} is given an argument
2448 such as @code{Hello.World.adb} it will be treated exactly as if the first
2449 period had been a hyphen, and for example krunching to eight characters
2450 gives the result @code{hellworl.adb}.
2452 Note that the result is always all lower case.
2453 Characters of the other case are folded as required.
2455 @code{length} represents the length of the krunched name. The default
2456 when no argument is given is 8 characters. A length of zero stands for
2457 unlimited, in other words do not chop except for system files where the
2458 implied crunching length is always eight characters.
2460 The output is the krunched name. The output has an extension only if the
2461 original argument was a file name with an extension.
2463 @node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2464 @anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{68}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{69}
2465 @subsubsection Krunching Method
2468 The initial file name is determined by the name of the unit that the file
2469 contains. The name is formed by taking the full expanded name of the
2470 unit and replacing the separating dots with hyphens and
2472 for all letters, except that a hyphen in the second character position is
2473 replaced by a tilde if the first character is
2474 @code{a}, @code{i}, @code{g}, or @code{s}.
2475 The extension is @code{.ads} for a
2476 spec and @code{.adb} for a body.
2477 Krunching does not affect the extension, but the file name is shortened to
2478 the specified length by following these rules:
2484 The name is divided into segments separated by hyphens, tildes or
2485 underscores and all hyphens, tildes, and underscores are
2486 eliminated. If this leaves the name short enough, we are done.
2489 If the name is too long, the longest segment is located (left-most
2490 if there are two of equal length), and shortened by dropping
2491 its last character. This is repeated until the name is short enough.
2493 As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2494 to fit the name into 8 characters as required by some operating systems:
2497 our-strings-wide_fixed 22
2498 our strings wide fixed 19
2499 our string wide fixed 18
2500 our strin wide fixed 17
2501 our stri wide fixed 16
2502 our stri wide fixe 15
2503 our str wide fixe 14
2510 Final file name: oustwifi.adb
2514 The file names for all predefined units are always krunched to eight
2515 characters. The krunching of these predefined units uses the following
2516 special prefix replacements:
2519 @multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx}
2563 These system files have a hyphen in the second character position. That
2564 is why normal user files replace such a character with a
2565 tilde, to avoid confusion with system file names.
2567 As an example of this special rule, consider
2568 @code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2571 ada-strings-wide_fixed 22
2572 a- strings wide fixed 18
2573 a- string wide fixed 17
2574 a- strin wide fixed 16
2575 a- stri wide fixed 15
2576 a- stri wide fixe 14
2583 Final file name: a-stwifi.adb
2587 Of course no file shortening algorithm can guarantee uniqueness over all
2588 possible unit names, and if file name krunching is used then it is your
2589 responsibility to ensure that no name clashes occur. The utility
2590 program @code{gnatkr} is supplied for conveniently determining the
2591 krunched name of a file.
2593 @node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2594 @anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{6a}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{6b}
2595 @subsubsection Examples of @code{gnatkr} Usage
2599 $ gnatkr very_long_unit_name.ads --> velounna.ads
2600 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
2601 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2602 $ gnatkr grandparent-parent-child --> grparchi
2603 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2604 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2607 @node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2608 @anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{36}
2609 @subsection Renaming Files with @code{gnatchop}
2614 This section discusses how to handle files with multiple units by using
2615 the @code{gnatchop} utility. This utility is also useful in renaming
2616 files to meet the standard GNAT default file naming conventions.
2619 * Handling Files with Multiple Units::
2620 * Operating gnatchop in Compilation Mode::
2621 * Command Line for gnatchop::
2622 * Switches for gnatchop::
2623 * Examples of gnatchop Usage::
2627 @node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2628 @anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{6d}@anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{6e}
2629 @subsubsection Handling Files with Multiple Units
2632 The basic compilation model of GNAT requires that a file submitted to the
2633 compiler have only one unit and there be a strict correspondence
2634 between the file name and the unit name.
2636 The @code{gnatchop} utility allows both of these rules to be relaxed,
2637 allowing GNAT to process files which contain multiple compilation units
2638 and files with arbitrary file names. @code{gnatchop}
2639 reads the specified file and generates one or more output files,
2640 containing one unit per file. The unit and the file name correspond,
2641 as required by GNAT.
2643 If you want to permanently restructure a set of 'foreign' files so that
2644 they match the GNAT rules, and do the remaining development using the
2645 GNAT structure, you can simply use @code{gnatchop} once, generate the
2646 new set of files and work with them from that point on.
2648 Alternatively, if you want to keep your files in the 'foreign' format,
2649 perhaps to maintain compatibility with some other Ada compilation
2650 system, you can set up a procedure where you use @code{gnatchop} each
2651 time you compile, regarding the source files that it writes as temporary
2652 files that you throw away.
2654 Note that if your file containing multiple units starts with a byte order
2655 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2656 will each start with a copy of this BOM, meaning that they can be compiled
2657 automatically in UTF-8 mode without needing to specify an explicit encoding.
2659 @node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2660 @anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{6f}@anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{70}
2661 @subsubsection Operating gnatchop in Compilation Mode
2664 The basic function of @code{gnatchop} is to take a file with multiple units
2665 and split it into separate files. The boundary between files is reasonably
2666 clear, except for the issue of comments and pragmas. In default mode, the
2667 rule is that any pragmas between units belong to the previous unit, except
2668 that configuration pragmas always belong to the following unit. Any comments
2669 belong to the following unit. These rules
2670 almost always result in the right choice of
2671 the split point without needing to mark it explicitly and most users will
2672 find this default to be what they want. In this default mode it is incorrect to
2673 submit a file containing only configuration pragmas, or one that ends in
2674 configuration pragmas, to @code{gnatchop}.
2676 However, using a special option to activate 'compilation mode',
2678 can perform another function, which is to provide exactly the semantics
2679 required by the RM for handling of configuration pragmas in a compilation.
2680 In the absence of configuration pragmas (at the main file level), this
2681 option has no effect, but it causes such configuration pragmas to be handled
2682 in a quite different manner.
2684 First, in compilation mode, if @code{gnatchop} is given a file that consists of
2685 only configuration pragmas, then this file is appended to the
2686 @code{gnat.adc} file in the current directory. This behavior provides
2687 the required behavior described in the RM for the actions to be taken
2688 on submitting such a file to the compiler, namely that these pragmas
2689 should apply to all subsequent compilations in the same compilation
2690 environment. Using GNAT, the current directory, possibly containing a
2691 @code{gnat.adc} file is the representation
2692 of a compilation environment. For more information on the
2693 @code{gnat.adc} file, see @ref{56,,Handling of Configuration Pragmas}.
2695 Second, in compilation mode, if @code{gnatchop}
2696 is given a file that starts with
2697 configuration pragmas, and contains one or more units, then these
2698 configuration pragmas are prepended to each of the chopped files. This
2699 behavior provides the required behavior described in the RM for the
2700 actions to be taken on compiling such a file, namely that the pragmas
2701 apply to all units in the compilation, but not to subsequently compiled
2704 Finally, if configuration pragmas appear between units, they are appended
2705 to the previous unit. This results in the previous unit being illegal,
2706 since the compiler does not accept configuration pragmas that follow
2707 a unit. This provides the required RM behavior that forbids configuration
2708 pragmas other than those preceding the first compilation unit of a
2711 For most purposes, @code{gnatchop} will be used in default mode. The
2712 compilation mode described above is used only if you need exactly
2713 accurate behavior with respect to compilations, and you have files
2714 that contain multiple units and configuration pragmas. In this
2715 circumstance the use of @code{gnatchop} with the compilation mode
2716 switch provides the required behavior, and is for example the mode
2717 in which GNAT processes the ACVC tests.
2719 @node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2720 @anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{72}
2721 @subsubsection Command Line for @code{gnatchop}
2724 The @code{gnatchop} command has the form:
2727 $ gnatchop switches file_name [file_name ...]
2731 The only required argument is the file name of the file to be chopped.
2732 There are no restrictions on the form of this file name. The file itself
2733 contains one or more Ada units, in normal GNAT format, concatenated
2734 together. As shown, more than one file may be presented to be chopped.
2736 When run in default mode, @code{gnatchop} generates one output file in
2737 the current directory for each unit in each of the files.
2739 @code{directory}, if specified, gives the name of the directory to which
2740 the output files will be written. If it is not specified, all files are
2741 written to the current directory.
2743 For example, given a
2744 file called @code{hellofiles} containing
2749 with Ada.Text_IO; use Ada.Text_IO;
2759 $ gnatchop hellofiles
2762 generates two files in the current directory, one called
2763 @code{hello.ads} containing the single line that is the procedure spec,
2764 and the other called @code{hello.adb} containing the remaining text. The
2765 original file is not affected. The generated files can be compiled in
2768 When gnatchop is invoked on a file that is empty or that contains only empty
2769 lines and/or comments, gnatchop will not fail, but will not produce any
2772 For example, given a
2773 file called @code{toto.txt} containing
2785 will not produce any new file and will result in the following warnings:
2788 toto.txt:1:01: warning: empty file, contains no compilation units
2789 no compilation units found
2790 no source files written
2793 @node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2794 @anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{73}@anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{74}
2795 @subsubsection Switches for @code{gnatchop}
2798 @code{gnatchop} recognizes the following switches:
2800 @geindex --version (gnatchop)
2805 @item @code{--version}
2807 Display Copyright and version, then exit disregarding all other options.
2810 @geindex --help (gnatchop)
2817 If @code{--version} was not used, display usage, then exit disregarding
2821 @geindex -c (gnatchop)
2828 Causes @code{gnatchop} to operate in compilation mode, in which
2829 configuration pragmas are handled according to strict RM rules. See
2830 previous section for a full description of this mode.
2832 @item @code{-gnat@emph{xxx}}
2834 This passes the given @code{-gnat@emph{xxx}} switch to @code{gnat} which is
2835 used to parse the given file. Not all @emph{xxx} options make sense,
2836 but for example, the use of @code{-gnati2} allows @code{gnatchop} to
2837 process a source file that uses Latin-2 coding for identifiers.
2841 Causes @code{gnatchop} to generate a brief help summary to the standard
2842 output file showing usage information.
2845 @geindex -k (gnatchop)
2850 @item @code{-k@emph{mm}}
2852 Limit generated file names to the specified number @code{mm}
2854 This is useful if the
2855 resulting set of files is required to be interoperable with systems
2856 which limit the length of file names.
2857 No space is allowed between the @code{-k} and the numeric value. The numeric
2858 value may be omitted in which case a default of @code{-k8},
2860 with DOS-like file systems, is used. If no @code{-k} switch
2862 there is no limit on the length of file names.
2865 @geindex -p (gnatchop)
2872 Causes the file modification time stamp of the input file to be
2873 preserved and used for the time stamp of the output file(s). This may be
2874 useful for preserving coherency of time stamps in an environment where
2875 @code{gnatchop} is used as part of a standard build process.
2878 @geindex -q (gnatchop)
2885 Causes output of informational messages indicating the set of generated
2886 files to be suppressed. Warnings and error messages are unaffected.
2889 @geindex -r (gnatchop)
2891 @geindex Source_Reference pragmas
2898 Generate @code{Source_Reference} pragmas. Use this switch if the output
2899 files are regarded as temporary and development is to be done in terms
2900 of the original unchopped file. This switch causes
2901 @code{Source_Reference} pragmas to be inserted into each of the
2902 generated files to refers back to the original file name and line number.
2903 The result is that all error messages refer back to the original
2905 In addition, the debugging information placed into the object file (when
2906 the @code{-g} switch of @code{gcc} or @code{gnatmake} is
2908 also refers back to this original file so that tools like profilers and
2909 debuggers will give information in terms of the original unchopped file.
2911 If the original file to be chopped itself contains
2912 a @code{Source_Reference}
2913 pragma referencing a third file, then gnatchop respects
2914 this pragma, and the generated @code{Source_Reference} pragmas
2915 in the chopped file refer to the original file, with appropriate
2916 line numbers. This is particularly useful when @code{gnatchop}
2917 is used in conjunction with @code{gnatprep} to compile files that
2918 contain preprocessing statements and multiple units.
2921 @geindex -v (gnatchop)
2928 Causes @code{gnatchop} to operate in verbose mode. The version
2929 number and copyright notice are output, as well as exact copies of
2930 the gnat1 commands spawned to obtain the chop control information.
2933 @geindex -w (gnatchop)
2940 Overwrite existing file names. Normally @code{gnatchop} regards it as a
2941 fatal error if there is already a file with the same name as a
2942 file it would otherwise output, in other words if the files to be
2943 chopped contain duplicated units. This switch bypasses this
2944 check, and causes all but the last instance of such duplicated
2945 units to be skipped.
2948 @geindex --GCC= (gnatchop)
2953 @item @code{--GCC=@emph{xxxx}}
2955 Specify the path of the GNAT parser to be used. When this switch is used,
2956 no attempt is made to add the prefix to the GNAT parser executable.
2959 @node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
2960 @anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{75}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{76}
2961 @subsubsection Examples of @code{gnatchop} Usage
2965 $ gnatchop -w hello_s.ada prerelease/files
2968 Chops the source file @code{hello_s.ada}. The output files will be
2969 placed in the directory @code{prerelease/files},
2971 files with matching names in that directory (no files in the current
2972 directory are modified).
2978 Chops the source file @code{archive}
2979 into the current directory. One
2980 useful application of @code{gnatchop} is in sending sets of sources
2981 around, for example in email messages. The required sources are simply
2982 concatenated (for example, using a Unix @code{cat}
2984 @code{gnatchop} is used at the other end to reconstitute the original
2988 $ gnatchop file1 file2 file3 direc
2991 Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
2992 the resulting files in the directory @code{direc}. Note that if any units
2993 occur more than once anywhere within this set of files, an error message
2994 is generated, and no files are written. To override this check, use the
2996 in which case the last occurrence in the last file will
2997 be the one that is output, and earlier duplicate occurrences for a given
2998 unit will be skipped.
3000 @node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
3001 @anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{14}
3002 @section Configuration Pragmas
3005 @geindex Configuration pragmas
3008 @geindex configuration
3010 Configuration pragmas include those pragmas described as
3011 such in the Ada Reference Manual, as well as
3012 implementation-dependent pragmas that are configuration pragmas.
3013 See the @code{Implementation_Defined_Pragmas} chapter in the
3014 @cite{GNAT_Reference_Manual} for details on these
3015 additional GNAT-specific configuration pragmas.
3016 Most notably, the pragma @code{Source_File_Name}, which allows
3017 specifying non-default names for source files, is a configuration
3018 pragma. The following is a complete list of configuration pragmas
3028 Allow_Integer_Address
3031 Assume_No_Invalid_Values
3033 Check_Float_Overflow
3037 Compile_Time_Warning
3039 Compiler_Unit_Warning
3041 Convention_Identifier
3044 Default_Scalar_Storage_Order
3045 Default_Storage_Pool
3046 Disable_Atomic_Synchronization
3050 Enable_Atomic_Synchronization
3053 External_Name_Casing
3062 No_Component_Reordering
3063 No_Heap_Finalization
3069 Overriding_Renamings
3070 Partition_Elaboration_Policy
3073 Prefix_Exception_Messages
3074 Priority_Specific_Dispatching
3077 Propagate_Exceptions
3084 Restrictions_Warnings
3086 Short_Circuit_And_Or
3089 Source_File_Name_Project
3093 Suppress_Exception_Locations
3094 Task_Dispatching_Policy
3095 Unevaluated_Use_Of_Old
3102 Wide_Character_Encoding
3106 * Handling of Configuration Pragmas::
3107 * The Configuration Pragmas Files::
3111 @node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
3112 @anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{78}@anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{56}
3113 @subsection Handling of Configuration Pragmas
3116 Configuration pragmas may either appear at the start of a compilation
3117 unit, or they can appear in a configuration pragma file to apply to
3118 all compilations performed in a given compilation environment.
3120 GNAT also provides the @code{gnatchop} utility to provide an automatic
3121 way to handle configuration pragmas following the semantics for
3122 compilations (that is, files with multiple units), described in the RM.
3123 See @ref{6f,,Operating gnatchop in Compilation Mode} for details.
3124 However, for most purposes, it will be more convenient to edit the
3125 @code{gnat.adc} file that contains configuration pragmas directly,
3126 as described in the following section.
3128 In the case of @code{Restrictions} pragmas appearing as configuration
3129 pragmas in individual compilation units, the exact handling depends on
3130 the type of restriction.
3132 Restrictions that require partition-wide consistency (like
3133 @code{No_Tasking}) are
3134 recognized wherever they appear
3135 and can be freely inherited, e.g. from a @emph{with}ed unit to the @emph{with}ing
3136 unit. This makes sense since the binder will in any case insist on seeing
3137 consistent use, so any unit not conforming to any restrictions that are
3138 anywhere in the partition will be rejected, and you might as well find
3139 that out at compile time rather than at bind time.
3141 For restrictions that do not require partition-wide consistency, e.g.
3142 SPARK or No_Implementation_Attributes, in general the restriction applies
3143 only to the unit in which the pragma appears, and not to any other units.
3145 The exception is No_Elaboration_Code which always applies to the entire
3146 object file from a compilation, i.e. to the body, spec, and all subunits.
3147 This restriction can be specified in a configuration pragma file, or it
3148 can be on the body and/or the spec (in eithe case it applies to all the
3149 relevant units). It can appear on a subunit only if it has previously
3150 appeared in the body of spec.
3152 @node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
3153 @anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{79}@anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{7a}
3154 @subsection The Configuration Pragmas Files
3159 In GNAT a compilation environment is defined by the current
3160 directory at the time that a compile command is given. This current
3161 directory is searched for a file whose name is @code{gnat.adc}. If
3162 this file is present, it is expected to contain one or more
3163 configuration pragmas that will be applied to the current compilation.
3164 However, if the switch @code{-gnatA} is used, @code{gnat.adc} is not
3165 considered. When taken into account, @code{gnat.adc} is added to the
3166 dependencies, so that if @code{gnat.adc} is modified later, an invocation of
3167 @code{gnatmake} will recompile the source.
3169 Configuration pragmas may be entered into the @code{gnat.adc} file
3170 either by running @code{gnatchop} on a source file that consists only of
3171 configuration pragmas, or more conveniently by direct editing of the
3172 @code{gnat.adc} file, which is a standard format source file.
3174 Besides @code{gnat.adc}, additional files containing configuration
3175 pragmas may be applied to the current compilation using the switch
3176 @code{-gnatec=@emph{path}} where @code{path} must designate an existing file that
3177 contains only configuration pragmas. These configuration pragmas are
3178 in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
3179 is present and switch @code{-gnatA} is not used).
3181 It is allowable to specify several switches @code{-gnatec=}, all of which
3182 will be taken into account.
3184 Files containing configuration pragmas specified with switches
3185 @code{-gnatec=} are added to the dependencies, unless they are
3186 temporary files. A file is considered temporary if its name ends in
3187 @code{.tmp} or @code{.TMP}. Certain tools follow this naming
3188 convention because they pass information to @code{gcc} via
3189 temporary files that are immediately deleted; it doesn't make sense to
3190 depend on a file that no longer exists. Such tools include
3191 @code{gprbuild}, @code{gnatmake}, and @code{gnatcheck}.
3193 If you are using project file, a separate mechanism is provided using
3197 @c See :ref:`Specifying_Configuration_Pragmas` for more details.
3199 @node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
3200 @anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{7b}
3201 @section Generating Object Files
3204 An Ada program consists of a set of source files, and the first step in
3205 compiling the program is to generate the corresponding object files.
3206 These are generated by compiling a subset of these source files.
3207 The files you need to compile are the following:
3213 If a package spec has no body, compile the package spec to produce the
3214 object file for the package.
3217 If a package has both a spec and a body, compile the body to produce the
3218 object file for the package. The source file for the package spec need
3219 not be compiled in this case because there is only one object file, which
3220 contains the code for both the spec and body of the package.
3223 For a subprogram, compile the subprogram body to produce the object file
3224 for the subprogram. The spec, if one is present, is as usual in a
3225 separate file, and need not be compiled.
3234 In the case of subunits, only compile the parent unit. A single object
3235 file is generated for the entire subunit tree, which includes all the
3239 Compile child units independently of their parent units
3240 (though, of course, the spec of all the ancestor unit must be present in order
3241 to compile a child unit).
3246 Compile generic units in the same manner as any other units. The object
3247 files in this case are small dummy files that contain at most the
3248 flag used for elaboration checking. This is because GNAT always handles generic
3249 instantiation by means of macro expansion. However, it is still necessary to
3250 compile generic units, for dependency checking and elaboration purposes.
3253 The preceding rules describe the set of files that must be compiled to
3254 generate the object files for a program. Each object file has the same
3255 name as the corresponding source file, except that the extension is
3258 You may wish to compile other files for the purpose of checking their
3259 syntactic and semantic correctness. For example, in the case where a
3260 package has a separate spec and body, you would not normally compile the
3261 spec. However, it is convenient in practice to compile the spec to make
3262 sure it is error-free before compiling clients of this spec, because such
3263 compilations will fail if there is an error in the spec.
3265 GNAT provides an option for compiling such files purely for the
3266 purposes of checking correctness; such compilations are not required as
3267 part of the process of building a program. To compile a file in this
3268 checking mode, use the @code{-gnatc} switch.
3270 @node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3271 @anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{7c}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{41}
3272 @section Source Dependencies
3275 A given object file clearly depends on the source file which is compiled
3276 to produce it. Here we are using "depends" in the sense of a typical
3277 @code{make} utility; in other words, an object file depends on a source
3278 file if changes to the source file require the object file to be
3280 In addition to this basic dependency, a given object may depend on
3281 additional source files as follows:
3287 If a file being compiled @emph{with}s a unit @code{X}, the object file
3288 depends on the file containing the spec of unit @code{X}. This includes
3289 files that are @emph{with}ed implicitly either because they are parents
3290 of @emph{with}ed child units or they are run-time units required by the
3291 language constructs used in a particular unit.
3294 If a file being compiled instantiates a library level generic unit, the
3295 object file depends on both the spec and body files for this generic
3299 If a file being compiled instantiates a generic unit defined within a
3300 package, the object file depends on the body file for the package as
3301 well as the spec file.
3306 @geindex -gnatn switch
3312 If a file being compiled contains a call to a subprogram for which
3313 pragma @code{Inline} applies and inlining is activated with the
3314 @code{-gnatn} switch, the object file depends on the file containing the
3315 body of this subprogram as well as on the file containing the spec. Note
3316 that for inlining to actually occur as a result of the use of this switch,
3317 it is necessary to compile in optimizing mode.
3319 @geindex -gnatN switch
3321 The use of @code{-gnatN} activates inlining optimization
3322 that is performed by the front end of the compiler. This inlining does
3323 not require that the code generation be optimized. Like @code{-gnatn},
3324 the use of this switch generates additional dependencies.
3326 When using a gcc-based back end (in practice this means using any version
3327 of GNAT other than for the JVM, .NET or GNAAMP platforms), then the use of
3328 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
3329 Historically front end inlining was more extensive than the gcc back end
3330 inlining, but that is no longer the case.
3333 If an object file @code{O} depends on the proper body of a subunit through
3334 inlining or instantiation, it depends on the parent unit of the subunit.
3335 This means that any modification of the parent unit or one of its subunits
3336 affects the compilation of @code{O}.
3339 The object file for a parent unit depends on all its subunit body files.
3342 The previous two rules meant that for purposes of computing dependencies and
3343 recompilation, a body and all its subunits are treated as an indivisible whole.
3345 These rules are applied transitively: if unit @code{A} @emph{with}s
3346 unit @code{B}, whose elaboration calls an inlined procedure in package
3347 @code{C}, the object file for unit @code{A} will depend on the body of
3348 @code{C}, in file @code{c.adb}.
3350 The set of dependent files described by these rules includes all the
3351 files on which the unit is semantically dependent, as dictated by the
3352 Ada language standard. However, it is a superset of what the
3353 standard describes, because it includes generic, inline, and subunit
3356 An object file must be recreated by recompiling the corresponding source
3357 file if any of the source files on which it depends are modified. For
3358 example, if the @code{make} utility is used to control compilation,
3359 the rule for an Ada object file must mention all the source files on
3360 which the object file depends, according to the above definition.
3361 The determination of the necessary
3362 recompilations is done automatically when one uses @code{gnatmake}.
3365 @node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3366 @anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{7d}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{42}
3367 @section The Ada Library Information Files
3370 @geindex Ada Library Information files
3374 Each compilation actually generates two output files. The first of these
3375 is the normal object file that has a @code{.o} extension. The second is a
3376 text file containing full dependency information. It has the same
3377 name as the source file, but an @code{.ali} extension.
3378 This file is known as the Ada Library Information (@code{ALI}) file.
3379 The following information is contained in the @code{ALI} file.
3385 Version information (indicates which version of GNAT was used to compile
3386 the unit(s) in question)
3389 Main program information (including priority and time slice settings,
3390 as well as the wide character encoding used during compilation).
3393 List of arguments used in the @code{gcc} command for the compilation
3396 Attributes of the unit, including configuration pragmas used, an indication
3397 of whether the compilation was successful, exception model used etc.
3400 A list of relevant restrictions applying to the unit (used for consistency)
3404 Categorization information (e.g., use of pragma @code{Pure}).
3407 Information on all @emph{with}ed units, including presence of
3408 @code{Elaborate} or @code{Elaborate_All} pragmas.
3411 Information from any @code{Linker_Options} pragmas used in the unit
3414 Information on the use of @code{Body_Version} or @code{Version}
3415 attributes in the unit.
3418 Dependency information. This is a list of files, together with
3419 time stamp and checksum information. These are files on which
3420 the unit depends in the sense that recompilation is required
3421 if any of these units are modified.
3424 Cross-reference data. Contains information on all entities referenced
3425 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
3426 provide cross-reference information.
3429 For a full detailed description of the format of the @code{ALI} file,
3430 see the source of the body of unit @code{Lib.Writ}, contained in file
3431 @code{lib-writ.adb} in the GNAT compiler sources.
3433 @node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3434 @anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{7e}@anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{43}
3435 @section Binding an Ada Program
3438 When using languages such as C and C++, once the source files have been
3439 compiled the only remaining step in building an executable program
3440 is linking the object modules together. This means that it is possible to
3441 link an inconsistent version of a program, in which two units have
3442 included different versions of the same header.
3444 The rules of Ada do not permit such an inconsistent program to be built.
3445 For example, if two clients have different versions of the same package,
3446 it is illegal to build a program containing these two clients.
3447 These rules are enforced by the GNAT binder, which also determines an
3448 elaboration order consistent with the Ada rules.
3450 The GNAT binder is run after all the object files for a program have
3451 been created. It is given the name of the main program unit, and from
3452 this it determines the set of units required by the program, by reading the
3453 corresponding ALI files. It generates error messages if the program is
3454 inconsistent or if no valid order of elaboration exists.
3456 If no errors are detected, the binder produces a main program, in Ada by
3457 default, that contains calls to the elaboration procedures of those
3458 compilation unit that require them, followed by
3459 a call to the main program. This Ada program is compiled to generate the
3460 object file for the main program. The name of
3461 the Ada file is @code{b~xxx}.adb` (with the corresponding spec
3462 @code{b~xxx}.ads`) where @code{xxx} is the name of the
3465 Finally, the linker is used to build the resulting executable program,
3466 using the object from the main program from the bind step as well as the
3467 object files for the Ada units of the program.
3469 @node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3470 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{15}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{7f}
3471 @section GNAT and Libraries
3474 @geindex Library building and using
3476 This section describes how to build and use libraries with GNAT, and also shows
3477 how to recompile the GNAT run-time library. You should be familiar with the
3478 Project Manager facility (see the @emph{GNAT_Project_Manager} chapter of the
3479 @emph{GPRbuild User's Guide}) before reading this chapter.
3482 * Introduction to Libraries in GNAT::
3483 * General Ada Libraries::
3484 * Stand-alone Ada Libraries::
3485 * Rebuilding the GNAT Run-Time Library::
3489 @node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3490 @anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{80}@anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{81}
3491 @subsection Introduction to Libraries in GNAT
3494 A library is, conceptually, a collection of objects which does not have its
3495 own main thread of execution, but rather provides certain services to the
3496 applications that use it. A library can be either statically linked with the
3497 application, in which case its code is directly included in the application,
3498 or, on platforms that support it, be dynamically linked, in which case
3499 its code is shared by all applications making use of this library.
3501 GNAT supports both types of libraries.
3502 In the static case, the compiled code can be provided in different ways. The
3503 simplest approach is to provide directly the set of objects resulting from
3504 compilation of the library source files. Alternatively, you can group the
3505 objects into an archive using whatever commands are provided by the operating
3506 system. For the latter case, the objects are grouped into a shared library.
3508 In the GNAT environment, a library has three types of components:
3517 @code{ALI} files (see @ref{42,,The Ada Library Information Files}), and
3520 Object files, an archive or a shared library.
3523 A GNAT library may expose all its source files, which is useful for
3524 documentation purposes. Alternatively, it may expose only the units needed by
3525 an external user to make use of the library. That is to say, the specs
3526 reflecting the library services along with all the units needed to compile
3527 those specs, which can include generic bodies or any body implementing an
3528 inlined routine. In the case of @emph{stand-alone libraries} those exposed
3529 units are called @emph{interface units} (@ref{82,,Stand-alone Ada Libraries}).
3531 All compilation units comprising an application, including those in a library,
3532 need to be elaborated in an order partially defined by Ada's semantics. GNAT
3533 computes the elaboration order from the @code{ALI} files and this is why they
3534 constitute a mandatory part of GNAT libraries.
3535 @emph{Stand-alone libraries} are the exception to this rule because a specific
3536 library elaboration routine is produced independently of the application(s)
3539 @node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3540 @anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{83}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{84}
3541 @subsection General Ada Libraries
3545 * Building a library::
3546 * Installing a library::
3551 @node Building a library,Installing a library,,General Ada Libraries
3552 @anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{85}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{86}
3553 @subsubsection Building a library
3556 The easiest way to build a library is to use the Project Manager,
3557 which supports a special type of project called a @emph{Library Project}
3558 (see the @emph{Library Projects} section in the @emph{GNAT Project Manager}
3559 chapter of the @emph{GPRbuild User's Guide}).
3561 A project is considered a library project, when two project-level attributes
3562 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
3563 control different aspects of library configuration, additional optional
3564 project-level attributes can be specified:
3573 @item @code{Library_Kind}
3575 This attribute controls whether the library is to be static or dynamic
3582 @item @code{Library_Version}
3584 This attribute specifies the library version; this value is used
3585 during dynamic linking of shared libraries to determine if the currently
3586 installed versions of the binaries are compatible.
3590 @code{Library_Options}
3596 @item @code{Library_GCC}
3598 These attributes specify additional low-level options to be used during
3599 library generation, and redefine the actual application used to generate
3604 The GNAT Project Manager takes full care of the library maintenance task,
3605 including recompilation of the source files for which objects do not exist
3606 or are not up to date, assembly of the library archive, and installation of
3607 the library (i.e., copying associated source, object and @code{ALI} files
3608 to the specified location).
3610 Here is a simple library project file:
3614 for Source_Dirs use ("src1", "src2");
3615 for Object_Dir use "obj";
3616 for Library_Name use "mylib";
3617 for Library_Dir use "lib";
3618 for Library_Kind use "dynamic";
3622 and the compilation command to build and install the library:
3628 It is not entirely trivial to perform manually all the steps required to
3629 produce a library. We recommend that you use the GNAT Project Manager
3630 for this task. In special cases where this is not desired, the necessary
3631 steps are discussed below.
3633 There are various possibilities for compiling the units that make up the
3634 library: for example with a Makefile (@ref{1f,,Using the GNU make Utility}) or
3635 with a conventional script. For simple libraries, it is also possible to create
3636 a dummy main program which depends upon all the packages that comprise the
3637 interface of the library. This dummy main program can then be given to
3638 @code{gnatmake}, which will ensure that all necessary objects are built.
3640 After this task is accomplished, you should follow the standard procedure
3641 of the underlying operating system to produce the static or shared library.
3643 Here is an example of such a dummy program:
3646 with My_Lib.Service1;
3647 with My_Lib.Service2;
3648 with My_Lib.Service3;
3649 procedure My_Lib_Dummy is
3655 Here are the generic commands that will build an archive or a shared library.
3658 # compiling the library
3659 $ gnatmake -c my_lib_dummy.adb
3661 # we don't need the dummy object itself
3662 $ rm my_lib_dummy.o my_lib_dummy.ali
3664 # create an archive with the remaining objects
3665 $ ar rc libmy_lib.a *.o
3666 # some systems may require "ranlib" to be run as well
3668 # or create a shared library
3669 $ gcc -shared -o libmy_lib.so *.o
3670 # some systems may require the code to have been compiled with -fPIC
3672 # remove the object files that are now in the library
3675 # Make the ALI files read-only so that gnatmake will not try to
3676 # regenerate the objects that are in the library
3680 Please note that the library must have a name of the form @code{lib@emph{xxx}.a}
3681 or @code{lib@emph{xxx}.so} (or @code{lib@emph{xxx}.dll} on Windows) in order to
3682 be accessed by the directive @code{-l@emph{xxx}} at link time.
3684 @node Installing a library,Using a library,Building a library,General Ada Libraries
3685 @anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{87}@anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{88}
3686 @subsubsection Installing a library
3689 @geindex ADA_PROJECT_PATH
3691 @geindex GPR_PROJECT_PATH
3693 If you use project files, library installation is part of the library build
3694 process (see the @emph{Installing a Library with Project Files} section of the
3695 @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}).
3697 When project files are not an option, it is also possible, but not recommended,
3698 to install the library so that the sources needed to use the library are on the
3699 Ada source path and the ALI files & libraries be on the Ada Object path (see
3700 @ref{89,,Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
3701 administrator can place general-purpose libraries in the default compiler
3702 paths, by specifying the libraries' location in the configuration files
3703 @code{ada_source_path} and @code{ada_object_path}. These configuration files
3704 must be located in the GNAT installation tree at the same place as the gcc spec
3705 file. The location of the gcc spec file can be determined as follows:
3711 The configuration files mentioned above have a simple format: each line
3712 must contain one unique directory name.
3713 Those names are added to the corresponding path
3714 in their order of appearance in the file. The names can be either absolute
3715 or relative; in the latter case, they are relative to where theses files
3718 The files @code{ada_source_path} and @code{ada_object_path} might not be
3720 GNAT installation, in which case, GNAT will look for its run-time library in
3721 the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3722 objects and @code{ALI} files). When the files exist, the compiler does not
3723 look in @code{adainclude} and @code{adalib}, and thus the
3724 @code{ada_source_path} file
3725 must contain the location for the GNAT run-time sources (which can simply
3726 be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3727 contain the location for the GNAT run-time objects (which can simply
3730 You can also specify a new default path to the run-time library at compilation
3731 time with the switch @code{--RTS=rts-path}. You can thus choose / change
3732 the run-time library you want your program to be compiled with. This switch is
3733 recognized by @code{gcc}, @code{gnatmake}, @code{gnatbind},
3734 @code{gnatls}, @code{gnatfind} and @code{gnatxref}.
3736 It is possible to install a library before or after the standard GNAT
3737 library, by reordering the lines in the configuration files. In general, a
3738 library must be installed before the GNAT library if it redefines
3741 @node Using a library,,Installing a library,General Ada Libraries
3742 @anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{8a}@anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{8b}
3743 @subsubsection Using a library
3746 Once again, the project facility greatly simplifies the use of
3747 libraries. In this context, using a library is just a matter of adding a
3748 @emph{with} clause in the user project. For instance, to make use of the
3749 library @code{My_Lib} shown in examples in earlier sections, you can
3759 Even if you have a third-party, non-Ada library, you can still use GNAT's
3760 Project Manager facility to provide a wrapper for it. For example, the
3761 following project, when @emph{with}ed by your main project, will link with the
3762 third-party library @code{liba.a}:
3766 for Externally_Built use "true";
3767 for Source_Files use ();
3768 for Library_Dir use "lib";
3769 for Library_Name use "a";
3770 for Library_Kind use "static";
3774 This is an alternative to the use of @code{pragma Linker_Options}. It is
3775 especially interesting in the context of systems with several interdependent
3776 static libraries where finding a proper linker order is not easy and best be
3777 left to the tools having visibility over project dependence information.
3779 In order to use an Ada library manually, you need to make sure that this
3780 library is on both your source and object path
3781 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}
3782 and @ref{8c,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3783 in an archive or a shared library, you need to specify the desired
3784 library at link time.
3786 For example, you can use the library @code{mylib} installed in
3787 @code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3790 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3794 This can be expressed more simply:
3800 when the following conditions are met:
3806 @code{/dir/my_lib_src} has been added by the user to the environment
3808 @geindex ADA_INCLUDE_PATH
3809 @geindex environment variable; ADA_INCLUDE_PATH
3810 @code{ADA_INCLUDE_PATH}, or by the administrator to the file
3811 @code{ada_source_path}
3814 @code{/dir/my_lib_obj} has been added by the user to the environment
3816 @geindex ADA_OBJECTS_PATH
3817 @geindex environment variable; ADA_OBJECTS_PATH
3818 @code{ADA_OBJECTS_PATH}, or by the administrator to the file
3819 @code{ada_object_path}
3822 a pragma @code{Linker_Options} has been added to one of the sources.
3826 pragma Linker_Options ("-lmy_lib");
3830 Note that you may also load a library dynamically at
3831 run time given its filename, as illustrated in the GNAT @code{plugins} example
3832 in the directory @code{share/examples/gnat/plugins} within the GNAT
3835 @node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3836 @anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{82}@anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{8d}
3837 @subsection Stand-alone Ada Libraries
3840 @geindex Stand-alone libraries
3843 * Introduction to Stand-alone Libraries::
3844 * Building a Stand-alone Library::
3845 * Creating a Stand-alone Library to be used in a non-Ada context::
3846 * Restrictions in Stand-alone Libraries::
3850 @node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3851 @anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{8e}@anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{8f}
3852 @subsubsection Introduction to Stand-alone Libraries
3855 A Stand-alone Library (abbreviated 'SAL') is a library that contains the
3857 elaborate the Ada units that are included in the library. In contrast with
3858 an ordinary library, which consists of all sources, objects and @code{ALI}
3860 library, a SAL may specify a restricted subset of compilation units
3861 to serve as a library interface. In this case, the fully
3862 self-sufficient set of files will normally consist of an objects
3863 archive, the sources of interface units' specs, and the @code{ALI}
3864 files of interface units.
3865 If an interface spec contains a generic unit or an inlined subprogram,
3867 source must also be provided; if the units that must be provided in the source
3868 form depend on other units, the source and @code{ALI} files of those must
3871 The main purpose of a SAL is to minimize the recompilation overhead of client
3872 applications when a new version of the library is installed. Specifically,
3873 if the interface sources have not changed, client applications do not need to
3874 be recompiled. If, furthermore, a SAL is provided in the shared form and its
3875 version, controlled by @code{Library_Version} attribute, is not changed,
3876 then the clients do not need to be relinked.
3878 SALs also allow the library providers to minimize the amount of library source
3879 text exposed to the clients. Such 'information hiding' might be useful or
3880 necessary for various reasons.
3882 Stand-alone libraries are also well suited to be used in an executable whose
3883 main routine is not written in Ada.
3885 @node Building a Stand-alone Library,Creating a Stand-alone Library to be used in a non-Ada context,Introduction to Stand-alone Libraries,Stand-alone Ada Libraries
3886 @anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{90}@anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{91}
3887 @subsubsection Building a Stand-alone Library
3890 GNAT's Project facility provides a simple way of building and installing
3891 stand-alone libraries; see the @emph{Stand-alone Library Projects} section
3892 in the @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}.
3893 To be a Stand-alone Library Project, in addition to the two attributes
3894 that make a project a Library Project (@code{Library_Name} and
3895 @code{Library_Dir}; see the @emph{Library Projects} section in the
3896 @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}),
3897 the attribute @code{Library_Interface} must be defined. For example:
3900 for Library_Dir use "lib_dir";
3901 for Library_Name use "dummy";
3902 for Library_Interface use ("int1", "int1.child");
3905 Attribute @code{Library_Interface} has a non-empty string list value,
3906 each string in the list designating a unit contained in an immediate source
3907 of the project file.
3909 When a Stand-alone Library is built, first the binder is invoked to build
3910 a package whose name depends on the library name
3911 (@code{b~dummy.ads/b} in the example above).
3912 This binder-generated package includes initialization and
3913 finalization procedures whose
3914 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
3916 above). The object corresponding to this package is included in the library.
3918 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
3919 calling of these procedures if a static SAL is built, or if a shared SAL
3921 with the project-level attribute @code{Library_Auto_Init} set to
3924 For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
3925 (those that are listed in attribute @code{Library_Interface}) are copied to
3926 the Library Directory. As a consequence, only the Interface Units may be
3927 imported from Ada units outside of the library. If other units are imported,
3928 the binding phase will fail.
3930 It is also possible to build an encapsulated library where not only
3931 the code to elaborate and finalize the library is embedded but also
3932 ensuring that the library is linked only against static
3933 libraries. So an encapsulated library only depends on system
3934 libraries, all other code, including the GNAT runtime, is embedded. To
3935 build an encapsulated library the attribute
3936 @code{Library_Standalone} must be set to @code{encapsulated}:
3939 for Library_Dir use "lib_dir";
3940 for Library_Name use "dummy";
3941 for Library_Kind use "dynamic";
3942 for Library_Interface use ("int1", "int1.child");
3943 for Library_Standalone use "encapsulated";
3946 The default value for this attribute is @code{standard} in which case
3947 a stand-alone library is built.
3949 The attribute @code{Library_Src_Dir} may be specified for a
3950 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
3951 single string value. Its value must be the path (absolute or relative to the
3952 project directory) of an existing directory. This directory cannot be the
3953 object directory or one of the source directories, but it can be the same as
3954 the library directory. The sources of the Interface
3955 Units of the library that are needed by an Ada client of the library will be
3956 copied to the designated directory, called the Interface Copy directory.
3957 These sources include the specs of the Interface Units, but they may also
3958 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
3959 are used, or when there is a generic unit in the spec. Before the sources
3960 are copied to the Interface Copy directory, an attempt is made to delete all
3961 files in the Interface Copy directory.
3963 Building stand-alone libraries by hand is somewhat tedious, but for those
3964 occasions when it is necessary here are the steps that you need to perform:
3970 Compile all library sources.
3973 Invoke the binder with the switch @code{-n} (No Ada main program),
3974 with all the @code{ALI} files of the interfaces, and
3975 with the switch @code{-L} to give specific names to the @code{init}
3976 and @code{final} procedures. For example:
3979 $ gnatbind -n int1.ali int2.ali -Lsal1
3983 Compile the binder generated file:
3990 Link the dynamic library with all the necessary object files,
3991 indicating to the linker the names of the @code{init} (and possibly
3992 @code{final}) procedures for automatic initialization (and finalization).
3993 The built library should be placed in a directory different from
3994 the object directory.
3997 Copy the @code{ALI} files of the interface to the library directory,
3998 add in this copy an indication that it is an interface to a SAL
3999 (i.e., add a word @code{SL} on the line in the @code{ALI} file that starts
4000 with letter 'P') and make the modified copy of the @code{ALI} file
4004 Using SALs is not different from using other libraries
4005 (see @ref{8a,,Using a library}).
4007 @node Creating a Stand-alone Library to be used in a non-Ada context,Restrictions in Stand-alone Libraries,Building a Stand-alone Library,Stand-alone Ada Libraries
4008 @anchor{gnat_ugn/the_gnat_compilation_model creating-a-stand-alone-library-to-be-used-in-a-non-ada-context}@anchor{92}@anchor{gnat_ugn/the_gnat_compilation_model id44}@anchor{93}
4009 @subsubsection Creating a Stand-alone Library to be used in a non-Ada context
4012 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
4015 The only extra step required is to ensure that library interface subprograms
4016 are compatible with the main program, by means of @code{pragma Export}
4017 or @code{pragma Convention}.
4019 Here is an example of simple library interface for use with C main program:
4022 package My_Package is
4024 procedure Do_Something;
4025 pragma Export (C, Do_Something, "do_something");
4027 procedure Do_Something_Else;
4028 pragma Export (C, Do_Something_Else, "do_something_else");
4033 On the foreign language side, you must provide a 'foreign' view of the
4034 library interface; remember that it should contain elaboration routines in
4035 addition to interface subprograms.
4037 The example below shows the content of @code{mylib_interface.h} (note
4038 that there is no rule for the naming of this file, any name can be used)
4041 /* the library elaboration procedure */
4042 extern void mylibinit (void);
4044 /* the library finalization procedure */
4045 extern void mylibfinal (void);
4047 /* the interface exported by the library */
4048 extern void do_something (void);
4049 extern void do_something_else (void);
4052 Libraries built as explained above can be used from any program, provided
4053 that the elaboration procedures (named @code{mylibinit} in the previous
4054 example) are called before the library services are used. Any number of
4055 libraries can be used simultaneously, as long as the elaboration
4056 procedure of each library is called.
4058 Below is an example of a C program that uses the @code{mylib} library.
4061 #include "mylib_interface.h"
4066 /* First, elaborate the library before using it */
4069 /* Main program, using the library exported entities */
4071 do_something_else ();
4073 /* Library finalization at the end of the program */
4079 Note that invoking any library finalization procedure generated by
4080 @code{gnatbind} shuts down the Ada run-time environment.
4082 finalization of all Ada libraries must be performed at the end of the program.
4083 No call to these libraries or to the Ada run-time library should be made
4084 after the finalization phase.
4086 Note also that special care must be taken with multi-tasks
4087 applications. The initialization and finalization routines are not
4088 protected against concurrent access. If such requirement is needed it
4089 must be ensured at the application level using a specific operating
4090 system services like a mutex or a critical-section.
4092 @node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
4093 @anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{94}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{95}
4094 @subsubsection Restrictions in Stand-alone Libraries
4097 The pragmas listed below should be used with caution inside libraries,
4098 as they can create incompatibilities with other Ada libraries:
4104 pragma @code{Locking_Policy}
4107 pragma @code{Partition_Elaboration_Policy}
4110 pragma @code{Queuing_Policy}
4113 pragma @code{Task_Dispatching_Policy}
4116 pragma @code{Unreserve_All_Interrupts}
4119 When using a library that contains such pragmas, the user must make sure
4120 that all libraries use the same pragmas with the same values. Otherwise,
4121 @code{Program_Error} will
4122 be raised during the elaboration of the conflicting
4123 libraries. The usage of these pragmas and its consequences for the user
4124 should therefore be well documented.
4126 Similarly, the traceback in the exception occurrence mechanism should be
4127 enabled or disabled in a consistent manner across all libraries.
4128 Otherwise, Program_Error will be raised during the elaboration of the
4129 conflicting libraries.
4131 If the @code{Version} or @code{Body_Version}
4132 attributes are used inside a library, then you need to
4133 perform a @code{gnatbind} step that specifies all @code{ALI} files in all
4134 libraries, so that version identifiers can be properly computed.
4135 In practice these attributes are rarely used, so this is unlikely
4136 to be a consideration.
4138 @node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
4139 @anchor{gnat_ugn/the_gnat_compilation_model id46}@anchor{96}@anchor{gnat_ugn/the_gnat_compilation_model rebuilding-the-gnat-run-time-library}@anchor{97}
4140 @subsection Rebuilding the GNAT Run-Time Library
4143 @geindex GNAT Run-Time Library
4146 @geindex Building the GNAT Run-Time Library
4148 @geindex Rebuilding the GNAT Run-Time Library
4150 @geindex Run-Time Library
4153 It may be useful to recompile the GNAT library in various contexts, the
4154 most important one being the use of partition-wide configuration pragmas
4155 such as @code{Normalize_Scalars}. A special Makefile called
4156 @code{Makefile.adalib} is provided to that effect and can be found in
4157 the directory containing the GNAT library. The location of this
4158 directory depends on the way the GNAT environment has been installed and can
4159 be determined by means of the command:
4165 The last entry in the object search path usually contains the
4166 gnat library. This Makefile contains its own documentation and in
4167 particular the set of instructions needed to rebuild a new library and
4170 @geindex Conditional compilation
4172 @node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
4173 @anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{98}@anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{16}
4174 @section Conditional Compilation
4177 This section presents some guidelines for modeling conditional compilation in Ada and describes the
4178 gnatprep preprocessor utility.
4180 @geindex Conditional compilation
4183 * Modeling Conditional Compilation in Ada::
4184 * Preprocessing with gnatprep::
4185 * Integrated Preprocessing::
4189 @node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
4190 @anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{99}@anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{9a}
4191 @subsection Modeling Conditional Compilation in Ada
4194 It is often necessary to arrange for a single source program
4195 to serve multiple purposes, where it is compiled in different
4196 ways to achieve these different goals. Some examples of the
4197 need for this feature are
4203 Adapting a program to a different hardware environment
4206 Adapting a program to a different target architecture
4209 Turning debugging features on and off
4212 Arranging for a program to compile with different compilers
4215 In C, or C++, the typical approach would be to use the preprocessor
4216 that is defined as part of the language. The Ada language does not
4217 contain such a feature. This is not an oversight, but rather a very
4218 deliberate design decision, based on the experience that overuse of
4219 the preprocessing features in C and C++ can result in programs that
4220 are extremely difficult to maintain. For example, if we have ten
4221 switches that can be on or off, this means that there are a thousand
4222 separate programs, any one of which might not even be syntactically
4223 correct, and even if syntactically correct, the resulting program
4224 might not work correctly. Testing all combinations can quickly become
4227 Nevertheless, the need to tailor programs certainly exists, and in
4228 this section we will discuss how this can
4229 be achieved using Ada in general, and GNAT in particular.
4232 * Use of Boolean Constants::
4233 * Debugging - A Special Case::
4234 * Conditionalizing Declarations::
4235 * Use of Alternative Implementations::
4240 @node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4241 @anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{9b}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{9c}
4242 @subsubsection Use of Boolean Constants
4245 In the case where the difference is simply which code
4246 sequence is executed, the cleanest solution is to use Boolean
4247 constants to control which code is executed.
4250 FP_Initialize_Required : constant Boolean := True;
4252 if FP_Initialize_Required then
4257 Not only will the code inside the @code{if} statement not be executed if
4258 the constant Boolean is @code{False}, but it will also be completely
4259 deleted from the program.
4260 However, the code is only deleted after the @code{if} statement
4261 has been checked for syntactic and semantic correctness.
4262 (In contrast, with preprocessors the code is deleted before the
4263 compiler ever gets to see it, so it is not checked until the switch
4266 @geindex Preprocessors (contrasted with conditional compilation)
4268 Typically the Boolean constants will be in a separate package,
4273 FP_Initialize_Required : constant Boolean := True;
4274 Reset_Available : constant Boolean := False;
4279 The @code{Config} package exists in multiple forms for the various targets,
4280 with an appropriate script selecting the version of @code{Config} needed.
4281 Then any other unit requiring conditional compilation can do a @emph{with}
4282 of @code{Config} to make the constants visible.
4284 @node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4285 @anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{9d}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{9e}
4286 @subsubsection Debugging - A Special Case
4289 A common use of conditional code is to execute statements (for example
4290 dynamic checks, or output of intermediate results) under control of a
4291 debug switch, so that the debugging behavior can be turned on and off.
4292 This can be done using a Boolean constant to control whether the code
4297 Put_Line ("got to the first stage!");
4304 if Debugging and then Temperature > 999.0 then
4305 raise Temperature_Crazy;
4309 @geindex pragma Assert
4311 Since this is a common case, there are special features to deal with
4312 this in a convenient manner. For the case of tests, Ada 2005 has added
4313 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
4314 on the @code{Assert} pragma that has always been available in GNAT, so this
4315 feature may be used with GNAT even if you are not using Ada 2005 features.
4316 The use of pragma @code{Assert} is described in the
4317 @cite{GNAT_Reference_Manual}, but as an
4318 example, the last test could be written:
4321 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4327 pragma Assert (Temperature <= 999.0);
4330 In both cases, if assertions are active and the temperature is excessive,
4331 the exception @code{Assert_Failure} will be raised, with the given string in
4332 the first case or a string indicating the location of the pragma in the second
4333 case used as the exception message.
4335 @geindex pragma Assertion_Policy
4337 You can turn assertions on and off by using the @code{Assertion_Policy}
4340 @geindex -gnata switch
4342 This is an Ada 2005 pragma which is implemented in all modes by
4343 GNAT. Alternatively, you can use the @code{-gnata} switch
4344 to enable assertions from the command line, which applies to
4345 all versions of Ada.
4347 @geindex pragma Debug
4349 For the example above with the @code{Put_Line}, the GNAT-specific pragma
4350 @code{Debug} can be used:
4353 pragma Debug (Put_Line ("got to the first stage!"));
4356 If debug pragmas are enabled, the argument, which must be of the form of
4357 a procedure call, is executed (in this case, @code{Put_Line} will be called).
4358 Only one call can be present, but of course a special debugging procedure
4359 containing any code you like can be included in the program and then
4360 called in a pragma @code{Debug} argument as needed.
4362 One advantage of pragma @code{Debug} over the @code{if Debugging then}
4363 construct is that pragma @code{Debug} can appear in declarative contexts,
4364 such as at the very beginning of a procedure, before local declarations have
4367 @geindex pragma Debug_Policy
4369 Debug pragmas are enabled using either the @code{-gnata} switch that also
4370 controls assertions, or with a separate Debug_Policy pragma.
4372 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4373 in Ada 95 and Ada 83 programs as well), and is analogous to
4374 pragma @code{Assertion_Policy} to control assertions.
4376 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
4377 and thus they can appear in @code{gnat.adc} if you are not using a
4378 project file, or in the file designated to contain configuration pragmas
4380 They then apply to all subsequent compilations. In practice the use of
4381 the @code{-gnata} switch is often the most convenient method of controlling
4382 the status of these pragmas.
4384 Note that a pragma is not a statement, so in contexts where a statement
4385 sequence is required, you can't just write a pragma on its own. You have
4386 to add a @code{null} statement.
4390 ... -- some statements
4392 pragma Assert (Num_Cases < 10);
4397 @node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4398 @anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{9f}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{a0}
4399 @subsubsection Conditionalizing Declarations
4402 In some cases it may be necessary to conditionalize declarations to meet
4403 different requirements. For example we might want a bit string whose length
4404 is set to meet some hardware message requirement.
4406 This may be possible using declare blocks controlled
4407 by conditional constants:
4410 if Small_Machine then
4412 X : Bit_String (1 .. 10);
4418 X : Large_Bit_String (1 .. 1000);
4425 Note that in this approach, both declarations are analyzed by the
4426 compiler so this can only be used where both declarations are legal,
4427 even though one of them will not be used.
4429 Another approach is to define integer constants, e.g., @code{Bits_Per_Word},
4430 or Boolean constants, e.g., @code{Little_Endian}, and then write declarations
4431 that are parameterized by these constants. For example
4435 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4439 If @code{Bits_Per_Word} is set to 32, this generates either
4443 Field1 at 0 range 0 .. 32;
4447 for the big endian case, or
4451 Field1 at 0 range 10 .. 32;
4455 for the little endian case. Since a powerful subset of Ada expression
4456 notation is usable for creating static constants, clever use of this
4457 feature can often solve quite difficult problems in conditionalizing
4458 compilation (note incidentally that in Ada 95, the little endian
4459 constant was introduced as @code{System.Default_Bit_Order}, so you do not
4460 need to define this one yourself).
4462 @node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4463 @anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{a2}
4464 @subsubsection Use of Alternative Implementations
4467 In some cases, none of the approaches described above are adequate. This
4468 can occur for example if the set of declarations required is radically
4469 different for two different configurations.
4471 In this situation, the official Ada way of dealing with conditionalizing
4472 such code is to write separate units for the different cases. As long as
4473 this does not result in excessive duplication of code, this can be done
4474 without creating maintenance problems. The approach is to share common
4475 code as far as possible, and then isolate the code and declarations
4476 that are different. Subunits are often a convenient method for breaking
4477 out a piece of a unit that is to be conditionalized, with separate files
4478 for different versions of the subunit for different targets, where the
4479 build script selects the right one to give to the compiler.
4481 @geindex Subunits (and conditional compilation)
4483 As an example, consider a situation where a new feature in Ada 2005
4484 allows something to be done in a really nice way. But your code must be able
4485 to compile with an Ada 95 compiler. Conceptually you want to say:
4489 ... neat Ada 2005 code
4491 ... not quite as neat Ada 95 code
4495 where @code{Ada_2005} is a Boolean constant.
4497 But this won't work when @code{Ada_2005} is set to @code{False},
4498 since the @code{then} clause will be illegal for an Ada 95 compiler.
4499 (Recall that although such unreachable code would eventually be deleted
4500 by the compiler, it still needs to be legal. If it uses features
4501 introduced in Ada 2005, it will be illegal in Ada 95.)
4506 procedure Insert is separate;
4509 Then we have two files for the subunit @code{Insert}, with the two sets of
4511 If the package containing this is called @code{File_Queries}, then we might
4518 @code{file_queries-insert-2005.adb}
4521 @code{file_queries-insert-95.adb}
4524 and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4526 This can also be done with project files' naming schemes. For example:
4529 for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4532 Note also that with project files it is desirable to use a different extension
4533 than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4534 conflict may arise through another commonly used feature: to declare as part
4535 of the project a set of directories containing all the sources obeying the
4536 default naming scheme.
4538 The use of alternative units is certainly feasible in all situations,
4539 and for example the Ada part of the GNAT run-time is conditionalized
4540 based on the target architecture using this approach. As a specific example,
4541 consider the implementation of the AST feature in VMS. There is one
4542 spec: @code{s-asthan.ads} which is the same for all architectures, and three
4552 @item @code{s-asthan.adb}
4554 used for all non-VMS operating systems
4561 @item @code{s-asthan-vms-alpha.adb}
4563 used for VMS on the Alpha
4570 @item @code{s-asthan-vms-ia64.adb}
4572 used for VMS on the ia64
4576 The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4577 this operating system feature is not available, and the two remaining
4578 versions interface with the corresponding versions of VMS to provide
4579 VMS-compatible AST handling. The GNAT build script knows the architecture
4580 and operating system, and automatically selects the right version,
4581 renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4583 Another style for arranging alternative implementations is through Ada's
4584 access-to-subprogram facility.
4585 In case some functionality is to be conditionally included,
4586 you can declare an access-to-procedure variable @code{Ref} that is initialized
4587 to designate a 'do nothing' procedure, and then invoke @code{Ref.all}
4589 In some library package, set @code{Ref} to @code{Proc'Access} for some
4590 procedure @code{Proc} that performs the relevant processing.
4591 The initialization only occurs if the library package is included in the
4593 The same idea can also be implemented using tagged types and dispatching
4596 @node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4597 @anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{a3}@anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{a4}
4598 @subsubsection Preprocessing
4601 @geindex Preprocessing
4603 Although it is quite possible to conditionalize code without the use of
4604 C-style preprocessing, as described earlier in this section, it is
4605 nevertheless convenient in some cases to use the C approach. Moreover,
4606 older Ada compilers have often provided some preprocessing capability,
4607 so legacy code may depend on this approach, even though it is not
4610 To accommodate such use, GNAT provides a preprocessor (modeled to a large
4611 extent on the various preprocessors that have been used
4612 with legacy code on other compilers, to enable easier transition).
4616 The preprocessor may be used in two separate modes. It can be used quite
4617 separately from the compiler, to generate a separate output source file
4618 that is then fed to the compiler as a separate step. This is the
4619 @code{gnatprep} utility, whose use is fully described in
4620 @ref{17,,Preprocessing with gnatprep}.
4622 The preprocessing language allows such constructs as
4625 #if DEBUG or else (PRIORITY > 4) then
4626 sequence of declarations
4628 completely different sequence of declarations
4632 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
4633 defined either on the command line or in a separate file.
4635 The other way of running the preprocessor is even closer to the C style and
4636 often more convenient. In this approach the preprocessing is integrated into
4637 the compilation process. The compiler is given the preprocessor input which
4638 includes @code{#if} lines etc, and then the compiler carries out the
4639 preprocessing internally and processes the resulting output.
4640 For more details on this approach, see @ref{18,,Integrated Preprocessing}.
4642 @node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4643 @anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{17}
4644 @subsection Preprocessing with @code{gnatprep}
4649 @geindex Preprocessing (gnatprep)
4651 This section discusses how to use GNAT's @code{gnatprep} utility for simple
4653 Although designed for use with GNAT, @code{gnatprep} does not depend on any
4654 special GNAT features.
4655 For further discussion of conditional compilation in general, see
4656 @ref{16,,Conditional Compilation}.
4659 * Preprocessing Symbols::
4661 * Switches for gnatprep::
4662 * Form of Definitions File::
4663 * Form of Input Text for gnatprep::
4667 @node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4668 @anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{a6}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{a7}
4669 @subsubsection Preprocessing Symbols
4672 Preprocessing symbols are defined in @emph{definition files} and referenced in the
4673 sources to be preprocessed. A preprocessing symbol is an identifier, following
4674 normal Ada (case-insensitive) rules for its syntax, with the restriction that
4675 all characters need to be in the ASCII set (no accented letters).
4677 @node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4678 @anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{a8}@anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{a9}
4679 @subsubsection Using @code{gnatprep}
4682 To call @code{gnatprep} use:
4685 $ gnatprep [ switches ] infile outfile [ deffile ]
4697 @item @emph{switches}
4699 is an optional sequence of switches as described in the next section.
4708 is the full name of the input file, which is an Ada source
4709 file containing preprocessor directives.
4716 @item @emph{outfile}
4718 is the full name of the output file, which is an Ada source
4719 in standard Ada form. When used with GNAT, this file name will
4720 normally have an @code{ads} or @code{adb} suffix.
4727 @item @code{deffile}
4729 is the full name of a text file containing definitions of
4730 preprocessing symbols to be referenced by the preprocessor. This argument is
4731 optional, and can be replaced by the use of the @code{-D} switch.
4735 @node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4736 @anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{aa}@anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{ab}
4737 @subsubsection Switches for @code{gnatprep}
4740 @geindex --version (gnatprep)
4745 @item @code{--version}
4747 Display Copyright and version, then exit disregarding all other options.
4750 @geindex --help (gnatprep)
4757 If @code{--version} was not used, display usage and then exit disregarding
4761 @geindex -b (gnatprep)
4768 Causes both preprocessor lines and the lines deleted by
4769 preprocessing to be replaced by blank lines in the output source file,
4770 preserving line numbers in the output file.
4773 @geindex -c (gnatprep)
4780 Causes both preprocessor lines and the lines deleted
4781 by preprocessing to be retained in the output source as comments marked
4782 with the special string @code{"--! "}. This option will result in line numbers
4783 being preserved in the output file.
4786 @geindex -C (gnatprep)
4793 Causes comments to be scanned. Normally comments are ignored by gnatprep.
4794 If this option is specified, then comments are scanned and any $symbol
4795 substitutions performed as in program text. This is particularly useful
4796 when structured comments are used (e.g., for programs written in a
4797 pre-2014 version of the SPARK Ada subset). Note that this switch is not
4798 available when doing integrated preprocessing (it would be useless in
4799 this context since comments are ignored by the compiler in any case).
4802 @geindex -D (gnatprep)
4807 @item @code{-D@emph{symbol}[=@emph{value}]}
4809 Defines a new preprocessing symbol with the specified value. If no value is given
4810 on the command line, then symbol is considered to be @code{True}. This switch
4811 can be used in place of a definition file.
4814 @geindex -r (gnatprep)
4821 Causes a @code{Source_Reference} pragma to be generated that
4822 references the original input file, so that error messages will use
4823 the file name of this original file. The use of this switch implies
4824 that preprocessor lines are not to be removed from the file, so its
4825 use will force @code{-b} mode if @code{-c}
4826 has not been specified explicitly.
4828 Note that if the file to be preprocessed contains multiple units, then
4829 it will be necessary to @code{gnatchop} the output file from
4830 @code{gnatprep}. If a @code{Source_Reference} pragma is present
4831 in the preprocessed file, it will be respected by
4833 so that the final chopped files will correctly refer to the original
4834 input source file for @code{gnatprep}.
4837 @geindex -s (gnatprep)
4844 Causes a sorted list of symbol names and values to be
4845 listed on the standard output file.
4848 @geindex -T (gnatprep)
4855 Use LF as line terminators when writing files. By default the line terminator
4856 of the host (LF under unix, CR/LF under Windows) is used.
4859 @geindex -u (gnatprep)
4866 Causes undefined symbols to be treated as having the value FALSE in the context
4867 of a preprocessor test. In the absence of this option, an undefined symbol in
4868 a @code{#if} or @code{#elsif} test will be treated as an error.
4871 @geindex -v (gnatprep)
4878 Verbose mode: generates more output about work done.
4881 Note: if neither @code{-b} nor @code{-c} is present,
4882 then preprocessor lines and
4883 deleted lines are completely removed from the output, unless -r is
4884 specified, in which case -b is assumed.
4886 @node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4887 @anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{ad}
4888 @subsubsection Form of Definitions File
4891 The definitions file contains lines of the form:
4897 where @code{symbol} is a preprocessing symbol, and @code{value} is one of the following:
4903 Empty, corresponding to a null substitution,
4906 A string literal using normal Ada syntax, or
4909 Any sequence of characters from the set @{letters, digits, period, underline@}.
4912 Comment lines may also appear in the definitions file, starting with
4913 the usual @code{--},
4914 and comments may be added to the definitions lines.
4916 @node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4917 @anchor{gnat_ugn/the_gnat_compilation_model id59}@anchor{ae}@anchor{gnat_ugn/the_gnat_compilation_model form-of-input-text-for-gnatprep}@anchor{af}
4918 @subsubsection Form of Input Text for @code{gnatprep}
4921 The input text may contain preprocessor conditional inclusion lines,
4922 as well as general symbol substitution sequences.
4924 The preprocessor conditional inclusion commands have the form:
4927 #if <expression> [then]
4929 #elsif <expression> [then]
4931 #elsif <expression> [then]
4939 In this example, <expression> is defined by the following grammar:
4942 <expression> ::= <symbol>
4943 <expression> ::= <symbol> = "<value>"
4944 <expression> ::= <symbol> = <symbol>
4945 <expression> ::= <symbol> = <integer>
4946 <expression> ::= <symbol> > <integer>
4947 <expression> ::= <symbol> >= <integer>
4948 <expression> ::= <symbol> < <integer>
4949 <expression> ::= <symbol> <= <integer>
4950 <expression> ::= <symbol> 'Defined
4951 <expression> ::= not <expression>
4952 <expression> ::= <expression> and <expression>
4953 <expression> ::= <expression> or <expression>
4954 <expression> ::= <expression> and then <expression>
4955 <expression> ::= <expression> or else <expression>
4956 <expression> ::= ( <expression> )
4959 Note the following restriction: it is not allowed to have "and" or "or"
4960 following "not" in the same expression without parentheses. For example, this
4967 This can be expressed instead as one of the following forms:
4974 For the first test (<expression> ::= <symbol>) the symbol must have
4975 either the value true or false, that is to say the right-hand of the
4976 symbol definition must be one of the (case-insensitive) literals
4977 @code{True} or @code{False}. If the value is true, then the
4978 corresponding lines are included, and if the value is false, they are
4981 When comparing a symbol to an integer, the integer is any non negative
4982 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
4983 2#11#. The symbol value must also be a non negative integer. Integer values
4984 in the range 0 .. 2**31-1 are supported.
4986 The test (<expression> ::= <symbol>'Defined) is true only if
4987 the symbol has been defined in the definition file or by a @code{-D}
4988 switch on the command line. Otherwise, the test is false.
4990 The equality tests are case insensitive, as are all the preprocessor lines.
4992 If the symbol referenced is not defined in the symbol definitions file,
4993 then the effect depends on whether or not switch @code{-u}
4994 is specified. If so, then the symbol is treated as if it had the value
4995 false and the test fails. If this switch is not specified, then
4996 it is an error to reference an undefined symbol. It is also an error to
4997 reference a symbol that is defined with a value other than @code{True}
5000 The use of the @code{not} operator inverts the sense of this logical test.
5001 The @code{not} operator cannot be combined with the @code{or} or @code{and}
5002 operators, without parentheses. For example, "if not X or Y then" is not
5003 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
5005 The @code{then} keyword is optional as shown
5007 The @code{#} must be the first non-blank character on a line, but
5008 otherwise the format is free form. Spaces or tabs may appear between
5009 the @code{#} and the keyword. The keywords and the symbols are case
5010 insensitive as in normal Ada code. Comments may be used on a
5011 preprocessor line, but other than that, no other tokens may appear on a
5012 preprocessor line. Any number of @code{elsif} clauses can be present,
5013 including none at all. The @code{else} is optional, as in Ada.
5015 The @code{#} marking the start of a preprocessor line must be the first
5016 non-blank character on the line, i.e., it must be preceded only by
5017 spaces or horizontal tabs.
5019 Symbol substitution outside of preprocessor lines is obtained by using
5026 anywhere within a source line, except in a comment or within a
5027 string literal. The identifier
5028 following the @code{$} must match one of the symbols defined in the symbol
5029 definition file, and the result is to substitute the value of the
5030 symbol in place of @code{$symbol} in the output file.
5032 Note that although the substitution of strings within a string literal
5033 is not possible, it is possible to have a symbol whose defined value is
5034 a string literal. So instead of setting XYZ to @code{hello} and writing:
5037 Header : String := "$XYZ";
5040 you should set XYZ to @code{"hello"} and write:
5043 Header : String := $XYZ;
5046 and then the substitution will occur as desired.
5048 @node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
5049 @anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{b0}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{18}
5050 @subsection Integrated Preprocessing
5053 As noted above, a file to be preprocessed consists of Ada source code
5054 in which preprocessing lines have been inserted. However,
5055 instead of using @code{gnatprep} to explicitly preprocess a file as a separate
5056 step before compilation, you can carry out the preprocessing implicitly
5057 as part of compilation. Such @emph{integrated preprocessing}, which is the common
5058 style with C, is performed when either or both of the following switches
5059 are passed to the compiler:
5067 @code{-gnatep}, which specifies the @emph{preprocessor data file}.
5068 This file dictates how the source files will be preprocessed (e.g., which
5069 symbol definition files apply to which sources).
5072 @code{-gnateD}, which defines values for preprocessing symbols.
5076 Integrated preprocessing applies only to Ada source files, it is
5077 not available for configuration pragma files.
5079 With integrated preprocessing, the output from the preprocessor is not,
5080 by default, written to any external file. Instead it is passed
5081 internally to the compiler. To preserve the result of
5082 preprocessing in a file, either run @code{gnatprep}
5083 in standalone mode or else supply the @code{-gnateG} switch
5084 (described below) to the compiler.
5086 When using project files:
5094 the builder switch @code{-x} should be used if any Ada source is
5095 compiled with @code{gnatep=}, so that the compiler finds the
5096 @emph{preprocessor data file}.
5099 the preprocessing data file and the symbol definition files should be
5100 located in the source directories of the project.
5104 Note that the @code{gnatmake} switch @code{-m} will almost
5105 always trigger recompilation for sources that are preprocessed,
5106 because @code{gnatmake} cannot compute the checksum of the source after
5109 The actual preprocessing function is described in detail in
5110 @ref{17,,Preprocessing with gnatprep}. This section explains the switches
5111 that relate to integrated preprocessing.
5113 @geindex -gnatep (gcc)
5118 @item @code{-gnatep=@emph{preprocessor_data_file}}
5120 This switch specifies the file name (without directory
5121 information) of the preprocessor data file. Either place this file
5122 in one of the source directories, or, when using project
5123 files, reference the project file's directory via the
5124 @code{project_name'Project_Dir} project attribute; e.g:
5131 for Switches ("Ada") use
5132 ("-gnatep=" & Prj'Project_Dir & "prep.def");
5138 A preprocessor data file is a text file that contains @emph{preprocessor
5139 control lines}. A preprocessor control line directs the preprocessing of
5140 either a particular source file, or, analogous to @code{others} in Ada,
5141 all sources not specified elsewhere in the preprocessor data file.
5142 A preprocessor control line
5143 can optionally identify a @emph{definition file} that assigns values to
5144 preprocessor symbols, as well as a list of switches that relate to
5146 Empty lines and comments (using Ada syntax) are also permitted, with no
5149 Here's an example of a preprocessor data file:
5154 "toto.adb" "prep.def" -u
5155 -- Preprocess toto.adb, using definition file prep.def
5156 -- Undefined symbols are treated as False
5159 -- Preprocess all other sources without using a definition file
5160 -- Suppressed lined are commented
5161 -- Symbol VERSION has the value V101
5163 "tata.adb" "prep2.def" -s
5164 -- Preprocess tata.adb, using definition file prep2.def
5165 -- List all symbols with their values
5169 A preprocessor control line has the following syntax:
5174 <preprocessor_control_line> ::=
5175 <preprocessor_input> [ <definition_file_name> ] @{ <switch> @}
5177 <preprocessor_input> ::= <source_file_name> | '*'
5179 <definition_file_name> ::= <string_literal>
5181 <source_file_name> := <string_literal>
5183 <switch> := (See below for list)
5187 Thus each preprocessor control line starts with either a literal string or
5194 A literal string is the file name (without directory information) of the source
5195 file that will be input to the preprocessor.
5198 The character '*' is a wild-card indicator; the additional parameters on the line
5199 indicate the preprocessing for all the sources
5200 that are not specified explicitly on other lines (the order of the lines is not
5204 It is an error to have two lines with the same file name or two
5205 lines starting with the character '*'.
5207 After the file name or '*', an optional literal string specifies the name of
5208 the definition file to be used for preprocessing
5209 (@ref{ac,,Form of Definitions File}). The definition files are found by the
5210 compiler in one of the source directories. In some cases, when compiling
5211 a source in a directory other than the current directory, if the definition
5212 file is in the current directory, it may be necessary to add the current
5213 directory as a source directory through the @code{-I} switch; otherwise
5214 the compiler would not find the definition file.
5216 Finally, switches similar to those of @code{gnatprep} may optionally appear:
5223 Causes both preprocessor lines and the lines deleted by
5224 preprocessing to be replaced by blank lines, preserving the line number.
5225 This switch is always implied; however, if specified after @code{-c}
5226 it cancels the effect of @code{-c}.
5230 Causes both preprocessor lines and the lines deleted
5231 by preprocessing to be retained as comments marked
5232 with the special string '@cite{--!}'.
5234 @item @code{-D@emph{symbol}=@emph{new_value}}
5236 Define or redefine @code{symbol} to have @code{new_value} as its value.
5237 The permitted form for @code{symbol} is either an Ada identifier, or any Ada reserved word
5238 aside from @code{if},
5239 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5240 The permitted form for @code{new_value} is a literal string, an Ada identifier or any Ada reserved
5241 word. A symbol declared with this switch replaces a symbol with the
5242 same name defined in a definition file.
5246 Causes a sorted list of symbol names and values to be
5247 listed on the standard output file.
5251 Causes undefined symbols to be treated as having the value @code{FALSE}
5253 of a preprocessor test. In the absence of this option, an undefined symbol in
5254 a @code{#if} or @code{#elsif} test will be treated as an error.
5258 @geindex -gnateD (gcc)
5263 @item @code{-gnateD@emph{symbol}[=@emph{new_value}]}
5265 Define or redefine @code{symbol} to have @code{new_value} as its value. If no value
5266 is supplied, then the value of @code{symbol} is @code{True}.
5267 The form of @code{symbol} is an identifier, following normal Ada (case-insensitive)
5268 rules for its syntax, and @code{new_value} is either an arbitrary string between double
5269 quotes or any sequence (including an empty sequence) of characters from the
5270 set (letters, digits, period, underline).
5271 Ada reserved words may be used as symbols, with the exceptions of @code{if},
5272 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5281 -gnateDFoo=\"Foo-Bar\"
5285 A symbol declared with this switch on the command line replaces a
5286 symbol with the same name either in a definition file or specified with a
5287 switch @code{-D} in the preprocessor data file.
5289 This switch is similar to switch @code{-D} of @code{gnatprep}.
5291 @item @code{-gnateG}
5293 When integrated preprocessing is performed on source file @code{filename.extension},
5294 create or overwrite @code{filename.extension.prep} to contain
5295 the result of the preprocessing.
5296 For example if the source file is @code{foo.adb} then
5297 the output file will be @code{foo.adb.prep}.
5300 @node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5301 @anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{44}@anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{b1}
5302 @section Mixed Language Programming
5305 @geindex Mixed Language Programming
5307 This section describes how to develop a mixed-language program,
5308 with a focus on combining Ada with C or C++.
5311 * Interfacing to C::
5312 * Calling Conventions::
5313 * Building Mixed Ada and C++ Programs::
5314 * Generating Ada Bindings for C and C++ headers::
5315 * Generating C Headers for Ada Specifications::
5319 @node Interfacing to C,Calling Conventions,,Mixed Language Programming
5320 @anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{b2}@anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{b3}
5321 @subsection Interfacing to C
5324 Interfacing Ada with a foreign language such as C involves using
5325 compiler directives to import and/or export entity definitions in each
5326 language -- using @code{extern} statements in C, for instance, and the
5327 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
5328 A full treatment of these topics is provided in Appendix B, section 1
5329 of the Ada Reference Manual.
5331 There are two ways to build a program using GNAT that contains some Ada
5332 sources and some foreign language sources, depending on whether or not
5333 the main subprogram is written in Ada. Here is a source example with
5334 the main subprogram in Ada:
5340 void print_num (int num)
5342 printf ("num is %d.\\n", num);
5350 /* num_from_Ada is declared in my_main.adb */
5351 extern int num_from_Ada;
5355 return num_from_Ada;
5361 procedure My_Main is
5363 -- Declare then export an Integer entity called num_from_Ada
5364 My_Num : Integer := 10;
5365 pragma Export (C, My_Num, "num_from_Ada");
5367 -- Declare an Ada function spec for Get_Num, then use
5368 -- C function get_num for the implementation.
5369 function Get_Num return Integer;
5370 pragma Import (C, Get_Num, "get_num");
5372 -- Declare an Ada procedure spec for Print_Num, then use
5373 -- C function print_num for the implementation.
5374 procedure Print_Num (Num : Integer);
5375 pragma Import (C, Print_Num, "print_num");
5378 Print_Num (Get_Num);
5382 To build this example:
5388 First compile the foreign language files to
5389 generate object files:
5397 Then, compile the Ada units to produce a set of object files and ALI
5401 $ gnatmake -c my_main.adb
5405 Run the Ada binder on the Ada main program:
5408 $ gnatbind my_main.ali
5412 Link the Ada main program, the Ada objects and the other language
5416 $ gnatlink my_main.ali file1.o file2.o
5420 The last three steps can be grouped in a single command:
5423 $ gnatmake my_main.adb -largs file1.o file2.o
5426 @geindex Binder output file
5428 If the main program is in a language other than Ada, then you may have
5429 more than one entry point into the Ada subsystem. You must use a special
5430 binder option to generate callable routines that initialize and
5431 finalize the Ada units (@ref{b4,,Binding with Non-Ada Main Programs}).
5432 Calls to the initialization and finalization routines must be inserted
5433 in the main program, or some other appropriate point in the code. The
5434 call to initialize the Ada units must occur before the first Ada
5435 subprogram is called, and the call to finalize the Ada units must occur
5436 after the last Ada subprogram returns. The binder will place the
5437 initialization and finalization subprograms into the
5438 @code{b~xxx.adb} file where they can be accessed by your C
5439 sources. To illustrate, we have the following example:
5443 extern void adainit (void);
5444 extern void adafinal (void);
5445 extern int add (int, int);
5446 extern int sub (int, int);
5448 int main (int argc, char *argv[])
5454 /* Should print "21 + 7 = 28" */
5455 printf ("%d + %d = %d\\n", a, b, add (a, b));
5457 /* Should print "21 - 7 = 14" */
5458 printf ("%d - %d = %d\\n", a, b, sub (a, b));
5467 function Add (A, B : Integer) return Integer;
5468 pragma Export (C, Add, "add");
5474 package body Unit1 is
5475 function Add (A, B : Integer) return Integer is
5485 function Sub (A, B : Integer) return Integer;
5486 pragma Export (C, Sub, "sub");
5492 package body Unit2 is
5493 function Sub (A, B : Integer) return Integer is
5500 The build procedure for this application is similar to the last
5507 First, compile the foreign language files to generate object files:
5514 Next, compile the Ada units to produce a set of object files and ALI
5518 $ gnatmake -c unit1.adb
5519 $ gnatmake -c unit2.adb
5523 Run the Ada binder on every generated ALI file. Make sure to use the
5524 @code{-n} option to specify a foreign main program:
5527 $ gnatbind -n unit1.ali unit2.ali
5531 Link the Ada main program, the Ada objects and the foreign language
5532 objects. You need only list the last ALI file here:
5535 $ gnatlink unit2.ali main.o -o exec_file
5538 This procedure yields a binary executable called @code{exec_file}.
5541 Depending on the circumstances (for example when your non-Ada main object
5542 does not provide symbol @code{main}), you may also need to instruct the
5543 GNAT linker not to include the standard startup objects by passing the
5544 @code{-nostartfiles} switch to @code{gnatlink}.
5546 @node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5547 @anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{b5}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{b6}
5548 @subsection Calling Conventions
5551 @geindex Foreign Languages
5553 @geindex Calling Conventions
5555 GNAT follows standard calling sequence conventions and will thus interface
5556 to any other language that also follows these conventions. The following
5557 Convention identifiers are recognized by GNAT:
5559 @geindex Interfacing to Ada
5561 @geindex Other Ada compilers
5563 @geindex Convention Ada
5570 This indicates that the standard Ada calling sequence will be
5571 used and all Ada data items may be passed without any limitations in the
5572 case where GNAT is used to generate both the caller and callee. It is also
5573 possible to mix GNAT generated code and code generated by another Ada
5574 compiler. In this case, the data types should be restricted to simple
5575 cases, including primitive types. Whether complex data types can be passed
5576 depends on the situation. Probably it is safe to pass simple arrays, such
5577 as arrays of integers or floats. Records may or may not work, depending
5578 on whether both compilers lay them out identically. Complex structures
5579 involving variant records, access parameters, tasks, or protected types,
5580 are unlikely to be able to be passed.
5582 Note that in the case of GNAT running
5583 on a platform that supports HP Ada 83, a higher degree of compatibility
5584 can be guaranteed, and in particular records are laid out in an identical
5585 manner in the two compilers. Note also that if output from two different
5586 compilers is mixed, the program is responsible for dealing with elaboration
5587 issues. Probably the safest approach is to write the main program in the
5588 version of Ada other than GNAT, so that it takes care of its own elaboration
5589 requirements, and then call the GNAT-generated adainit procedure to ensure
5590 elaboration of the GNAT components. Consult the documentation of the other
5591 Ada compiler for further details on elaboration.
5593 However, it is not possible to mix the tasking run time of GNAT and
5594 HP Ada 83, All the tasking operations must either be entirely within
5595 GNAT compiled sections of the program, or entirely within HP Ada 83
5596 compiled sections of the program.
5599 @geindex Interfacing to Assembly
5601 @geindex Convention Assembler
5606 @item @code{Assembler}
5608 Specifies assembler as the convention. In practice this has the
5609 same effect as convention Ada (but is not equivalent in the sense of being
5610 considered the same convention).
5613 @geindex Convention Asm
5622 Equivalent to Assembler.
5624 @geindex Interfacing to COBOL
5626 @geindex Convention COBOL
5636 Data will be passed according to the conventions described
5637 in section B.4 of the Ada Reference Manual.
5642 @geindex Interfacing to C
5644 @geindex Convention C
5651 Data will be passed according to the conventions described
5652 in section B.3 of the Ada Reference Manual.
5654 A note on interfacing to a C 'varargs' function:
5658 @geindex C varargs function
5660 @geindex Interfacing to C varargs function
5662 @geindex varargs function interfaces
5664 In C, @code{varargs} allows a function to take a variable number of
5665 arguments. There is no direct equivalent in this to Ada. One
5666 approach that can be used is to create a C wrapper for each
5667 different profile and then interface to this C wrapper. For
5668 example, to print an @code{int} value using @code{printf},
5669 create a C function @code{printfi} that takes two arguments, a
5670 pointer to a string and an int, and calls @code{printf}.
5671 Then in the Ada program, use pragma @code{Import} to
5672 interface to @code{printfi}.
5674 It may work on some platforms to directly interface to
5675 a @code{varargs} function by providing a specific Ada profile
5676 for a particular call. However, this does not work on
5677 all platforms, since there is no guarantee that the
5678 calling sequence for a two argument normal C function
5679 is the same as for calling a @code{varargs} C function with
5680 the same two arguments.
5684 @geindex Convention Default
5691 @item @code{Default}
5696 @geindex Convention External
5703 @item @code{External}
5710 @geindex Interfacing to C++
5712 @geindex Convention C++
5717 @item @code{C_Plus_Plus} (or @code{CPP})
5719 This stands for C++. For most purposes this is identical to C.
5720 See the separate description of the specialized GNAT pragmas relating to
5721 C++ interfacing for further details.
5726 @geindex Interfacing to Fortran
5728 @geindex Convention Fortran
5733 @item @code{Fortran}
5735 Data will be passed according to the conventions described
5736 in section B.5 of the Ada Reference Manual.
5738 @item @code{Intrinsic}
5740 This applies to an intrinsic operation, as defined in the Ada
5741 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5742 this means that the body of the subprogram is provided by the compiler itself,
5743 usually by means of an efficient code sequence, and that the user does not
5744 supply an explicit body for it. In an application program, the pragma may
5745 be applied to the following sets of names:
5751 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5752 The corresponding subprogram declaration must have
5753 two formal parameters. The
5754 first one must be a signed integer type or a modular type with a binary
5755 modulus, and the second parameter must be of type Natural.
5756 The return type must be the same as the type of the first argument. The size
5757 of this type can only be 8, 16, 32, or 64.
5760 Binary arithmetic operators: '+', '-', '*', '/'.
5761 The corresponding operator declaration must have parameters and result type
5762 that have the same root numeric type (for example, all three are long_float
5763 types). This simplifies the definition of operations that use type checking
5764 to perform dimensional checks:
5768 type Distance is new Long_Float;
5769 type Time is new Long_Float;
5770 type Velocity is new Long_Float;
5771 function "/" (D : Distance; T : Time)
5773 pragma Import (Intrinsic, "/");
5775 This common idiom is often programmed with a generic definition and an
5776 explicit body. The pragma makes it simpler to introduce such declarations.
5777 It incurs no overhead in compilation time or code size, because it is
5778 implemented as a single machine instruction.
5785 General subprogram entities. This is used to bind an Ada subprogram
5787 a compiler builtin by name with back-ends where such interfaces are
5788 available. A typical example is the set of @code{__builtin} functions
5789 exposed by the GCC back-end, as in the following example:
5792 function builtin_sqrt (F : Float) return Float;
5793 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5796 Most of the GCC builtins are accessible this way, and as for other
5797 import conventions (e.g. C), it is the user's responsibility to ensure
5798 that the Ada subprogram profile matches the underlying builtin
5805 @geindex Convention Stdcall
5810 @item @code{Stdcall}
5812 This is relevant only to Windows implementations of GNAT,
5813 and specifies that the @code{Stdcall} calling sequence will be used,
5814 as defined by the NT API. Nevertheless, to ease building
5815 cross-platform bindings this convention will be handled as a @code{C} calling
5816 convention on non-Windows platforms.
5821 @geindex Convention DLL
5828 This is equivalent to @code{Stdcall}.
5833 @geindex Convention Win32
5840 This is equivalent to @code{Stdcall}.
5845 @geindex Convention Stubbed
5850 @item @code{Stubbed}
5852 This is a special convention that indicates that the compiler
5853 should provide a stub body that raises @code{Program_Error}.
5856 GNAT additionally provides a useful pragma @code{Convention_Identifier}
5857 that can be used to parameterize conventions and allow additional synonyms
5858 to be specified. For example if you have legacy code in which the convention
5859 identifier Fortran77 was used for Fortran, you can use the configuration
5863 pragma Convention_Identifier (Fortran77, Fortran);
5866 And from now on the identifier Fortran77 may be used as a convention
5867 identifier (for example in an @code{Import} pragma) with the same
5870 @node Building Mixed Ada and C++ Programs,Generating Ada Bindings for C and C++ headers,Calling Conventions,Mixed Language Programming
5871 @anchor{gnat_ugn/the_gnat_compilation_model id64}@anchor{b7}@anchor{gnat_ugn/the_gnat_compilation_model building-mixed-ada-and-c-programs}@anchor{b8}
5872 @subsection Building Mixed Ada and C++ Programs
5875 A programmer inexperienced with mixed-language development may find that
5876 building an application containing both Ada and C++ code can be a
5877 challenge. This section gives a few hints that should make this task easier.
5880 * Interfacing to C++::
5881 * Linking a Mixed C++ & Ada Program::
5882 * A Simple Example::
5883 * Interfacing with C++ constructors::
5884 * Interfacing with C++ at the Class Level::
5888 @node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5889 @anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{b9}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{ba}
5890 @subsubsection Interfacing to C++
5893 GNAT supports interfacing with the G++ compiler (or any C++ compiler
5894 generating code that is compatible with the G++ Application Binary
5895 Interface ---see @indicateurl{http://www.codesourcery.com/archives/cxx-abi}).
5897 Interfacing can be done at 3 levels: simple data, subprograms, and
5898 classes. In the first two cases, GNAT offers a specific @code{Convention C_Plus_Plus}
5899 (or @code{CPP}) that behaves exactly like @code{Convention C}.
5900 Usually, C++ mangles the names of subprograms. To generate proper mangled
5901 names automatically, see @ref{19,,Generating Ada Bindings for C and C++ headers}).
5902 This problem can also be addressed manually in two ways:
5908 by modifying the C++ code in order to force a C convention using
5909 the @code{extern "C"} syntax.
5912 by figuring out the mangled name (using e.g. @code{nm}) and using it as the
5913 Link_Name argument of the pragma import.
5916 Interfacing at the class level can be achieved by using the GNAT specific
5917 pragmas such as @code{CPP_Constructor}. See the @cite{GNAT_Reference_Manual} for additional information.
5919 @node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5920 @anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-ada-program}@anchor{bb}@anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-and-ada-program}@anchor{bc}
5921 @subsubsection Linking a Mixed C++ & Ada Program
5924 Usually the linker of the C++ development system must be used to link
5925 mixed applications because most C++ systems will resolve elaboration
5926 issues (such as calling constructors on global class instances)
5927 transparently during the link phase. GNAT has been adapted to ease the
5928 use of a foreign linker for the last phase. Three cases can be
5935 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5936 The C++ linker can simply be called by using the C++ specific driver
5939 Note that if the C++ code uses inline functions, you will need to
5940 compile your C++ code with the @code{-fkeep-inline-functions} switch in
5941 order to provide an existing function implementation that the Ada code can
5945 $ g++ -c -fkeep-inline-functions file1.C
5946 $ g++ -c -fkeep-inline-functions file2.C
5947 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5951 Using GNAT and G++ from two different GCC installations: If both
5952 compilers are on the :envvar`PATH`, the previous method may be used. It is
5953 important to note that environment variables such as
5954 @geindex C_INCLUDE_PATH
5955 @geindex environment variable; C_INCLUDE_PATH
5956 @code{C_INCLUDE_PATH},
5957 @geindex GCC_EXEC_PREFIX
5958 @geindex environment variable; GCC_EXEC_PREFIX
5959 @code{GCC_EXEC_PREFIX},
5960 @geindex BINUTILS_ROOT
5961 @geindex environment variable; BINUTILS_ROOT
5962 @code{BINUTILS_ROOT}, and
5964 @geindex environment variable; GCC_ROOT
5965 @code{GCC_ROOT} will affect both compilers
5966 at the same time and may make one of the two compilers operate
5967 improperly if set during invocation of the wrong compiler. It is also
5968 very important that the linker uses the proper @code{libgcc.a} GCC
5969 library -- that is, the one from the C++ compiler installation. The
5970 implicit link command as suggested in the @code{gnatmake} command
5971 from the former example can be replaced by an explicit link command with
5972 the full-verbosity option in order to verify which library is used:
5976 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5979 If there is a problem due to interfering environment variables, it can
5980 be worked around by using an intermediate script. The following example
5981 shows the proper script to use when GNAT has not been installed at its
5982 default location and g++ has been installed at its default location:
5990 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5994 Using a non-GNU C++ compiler: The commands previously described can be
5995 used to insure that the C++ linker is used. Nonetheless, you need to add
5996 a few more parameters to the link command line, depending on the exception
5999 If the @code{setjmp} / @code{longjmp} exception mechanism is used, only the paths
6000 to the @code{libgcc} libraries are required:
6005 CC $* gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a
6006 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
6009 where CC is the name of the non-GNU C++ compiler.
6011 If the "zero cost" exception mechanism is used, and the platform
6012 supports automatic registration of exception tables (e.g., Solaris),
6013 paths to more objects are required:
6018 CC gcc -print-file-name=crtbegin.o $* \\
6019 gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a \\
6020 gcc -print-file-name=crtend.o
6021 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
6024 If the "zero cost exception" mechanism is used, and the platform
6025 doesn't support automatic registration of exception tables (e.g., HP-UX
6026 or AIX), the simple approach described above will not work and
6027 a pre-linking phase using GNAT will be necessary.
6030 Another alternative is to use the @code{gprbuild} multi-language builder
6031 which has a large knowledge base and knows how to link Ada and C++ code
6032 together automatically in most cases.
6034 @node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
6035 @anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{bd}@anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{be}
6036 @subsubsection A Simple Example
6039 The following example, provided as part of the GNAT examples, shows how
6040 to achieve procedural interfacing between Ada and C++ in both
6041 directions. The C++ class A has two methods. The first method is exported
6042 to Ada by the means of an extern C wrapper function. The second method
6043 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
6044 a limited record with a layout comparable to the C++ class. The Ada
6045 subprogram, in turn, calls the C++ method. So, starting from the C++
6046 main program, the process passes back and forth between the two
6049 Here are the compilation commands:
6052 $ gnatmake -c simple_cpp_interface
6055 $ gnatbind -n simple_cpp_interface
6056 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
6059 Here are the corresponding sources:
6067 void adainit (void);
6068 void adafinal (void);
6069 void method1 (A *t);
6093 class A : public Origin @{
6095 void method1 (void);
6096 void method2 (int v);
6108 extern "C" @{ void ada_method2 (A *t, int v);@}
6110 void A::method1 (void)
6113 printf ("in A::method1, a_value = %d \\n",a_value);
6116 void A::method2 (int v)
6118 ada_method2 (this, v);
6119 printf ("in A::method2, a_value = %d \\n",a_value);
6125 printf ("in A::A, a_value = %d \\n",a_value);
6130 -- simple_cpp_interface.ads
6132 package Simple_Cpp_Interface is
6135 Vptr : System.Address;
6139 pragma Convention (C, A);
6141 procedure Method1 (This : in out A);
6142 pragma Import (C, Method1);
6144 procedure Ada_Method2 (This : in out A; V : Integer);
6145 pragma Export (C, Ada_Method2);
6147 end Simple_Cpp_Interface;
6151 -- simple_cpp_interface.adb
6152 package body Simple_Cpp_Interface is
6154 procedure Ada_Method2 (This : in out A; V : Integer) is
6160 end Simple_Cpp_Interface;
6163 @node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
6164 @anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{bf}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{c0}
6165 @subsubsection Interfacing with C++ constructors
6168 In order to interface with C++ constructors GNAT provides the
6169 @code{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
6170 for additional information).
6171 In this section we present some common uses of C++ constructors
6172 in mixed-languages programs in GNAT.
6174 Let us assume that we need to interface with the following
6182 virtual int Get_Value ();
6183 Root(); // Default constructor
6184 Root(int v); // 1st non-default constructor
6185 Root(int v, int w); // 2nd non-default constructor
6189 For this purpose we can write the following package spec (further
6190 information on how to build this spec is available in
6191 @ref{c1,,Interfacing with C++ at the Class Level} and
6192 @ref{19,,Generating Ada Bindings for C and C++ headers}).
6195 with Interfaces.C; use Interfaces.C;
6197 type Root is tagged limited record
6201 pragma Import (CPP, Root);
6203 function Get_Value (Obj : Root) return int;
6204 pragma Import (CPP, Get_Value);
6206 function Constructor return Root;
6207 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
6209 function Constructor (v : Integer) return Root;
6210 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
6212 function Constructor (v, w : Integer) return Root;
6213 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
6217 On the Ada side the constructor is represented by a function (whose
6218 name is arbitrary) that returns the classwide type corresponding to
6219 the imported C++ class. Although the constructor is described as a
6220 function, it is typically a procedure with an extra implicit argument
6221 (the object being initialized) at the implementation level. GNAT
6222 issues the appropriate call, whatever it is, to get the object
6223 properly initialized.
6225 Constructors can only appear in the following contexts:
6231 On the right side of an initialization of an object of type @code{T}.
6234 On the right side of an initialization of a record component of type @code{T}.
6237 In an Ada 2005 limited aggregate.
6240 In an Ada 2005 nested limited aggregate.
6243 In an Ada 2005 limited aggregate that initializes an object built in
6244 place by an extended return statement.
6247 In a declaration of an object whose type is a class imported from C++,
6248 either the default C++ constructor is implicitly called by GNAT, or
6249 else the required C++ constructor must be explicitly called in the
6250 expression that initializes the object. For example:
6254 Obj2 : Root := Constructor;
6255 Obj3 : Root := Constructor (v => 10);
6256 Obj4 : Root := Constructor (30, 40);
6259 The first two declarations are equivalent: in both cases the default C++
6260 constructor is invoked (in the former case the call to the constructor is
6261 implicit, and in the latter case the call is explicit in the object
6262 declaration). @code{Obj3} is initialized by the C++ non-default constructor
6263 that takes an integer argument, and @code{Obj4} is initialized by the
6264 non-default C++ constructor that takes two integers.
6266 Let us derive the imported C++ class in the Ada side. For example:
6269 type DT is new Root with record
6270 C_Value : Natural := 2009;
6274 In this case the components DT inherited from the C++ side must be
6275 initialized by a C++ constructor, and the additional Ada components
6276 of type DT are initialized by GNAT. The initialization of such an
6277 object is done either by default, or by means of a function returning
6278 an aggregate of type DT, or by means of an extension aggregate.
6282 Obj6 : DT := Function_Returning_DT (50);
6283 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6286 The declaration of @code{Obj5} invokes the default constructors: the
6287 C++ default constructor of the parent type takes care of the initialization
6288 of the components inherited from Root, and GNAT takes care of the default
6289 initialization of the additional Ada components of type DT (that is,
6290 @code{C_Value} is initialized to value 2009). The order of invocation of
6291 the constructors is consistent with the order of elaboration required by
6292 Ada and C++. That is, the constructor of the parent type is always called
6293 before the constructor of the derived type.
6295 Let us now consider a record that has components whose type is imported
6296 from C++. For example:
6299 type Rec1 is limited record
6300 Data1 : Root := Constructor (10);
6301 Value : Natural := 1000;
6304 type Rec2 (D : Integer := 20) is limited record
6306 Data2 : Root := Constructor (D, 30);
6310 The initialization of an object of type @code{Rec2} will call the
6311 non-default C++ constructors specified for the imported components.
6318 Using Ada 2005 we can use limited aggregates to initialize an object
6319 invoking C++ constructors that differ from those specified in the type
6320 declarations. For example:
6323 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6328 The above declaration uses an Ada 2005 limited aggregate to
6329 initialize @code{Obj9}, and the C++ constructor that has two integer
6330 arguments is invoked to initialize the @code{Data1} component instead
6331 of the constructor specified in the declaration of type @code{Rec1}. In
6332 Ada 2005 the box in the aggregate indicates that unspecified components
6333 are initialized using the expression (if any) available in the component
6334 declaration. That is, in this case discriminant @code{D} is initialized
6335 to value @code{20}, @code{Value} is initialized to value 1000, and the
6336 non-default C++ constructor that handles two integers takes care of
6337 initializing component @code{Data2} with values @code{20,30}.
6339 In Ada 2005 we can use the extended return statement to build the Ada
6340 equivalent to C++ non-default constructors. For example:
6343 function Constructor (V : Integer) return Rec2 is
6345 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
6348 -- Further actions required for construction of
6349 -- objects of type Rec2
6355 In this example the extended return statement construct is used to
6356 build in place the returned object whose components are initialized
6357 by means of a limited aggregate. Any further action associated with
6358 the constructor can be placed inside the construct.
6360 @node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6361 @anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-at-the-class-level}@anchor{c1}@anchor{gnat_ugn/the_gnat_compilation_model id69}@anchor{c2}
6362 @subsubsection Interfacing with C++ at the Class Level
6365 In this section we demonstrate the GNAT features for interfacing with
6366 C++ by means of an example making use of Ada 2005 abstract interface
6367 types. This example consists of a classification of animals; classes
6368 have been used to model our main classification of animals, and
6369 interfaces provide support for the management of secondary
6370 classifications. We first demonstrate a case in which the types and
6371 constructors are defined on the C++ side and imported from the Ada
6372 side, and latter the reverse case.
6374 The root of our derivation will be the @code{Animal} class, with a
6375 single private attribute (the @code{Age} of the animal), a constructor,
6376 and two public primitives to set and get the value of this attribute.
6381 virtual void Set_Age (int New_Age);
6383 Animal() @{Age_Count = 0;@};
6389 Abstract interface types are defined in C++ by means of classes with pure
6390 virtual functions and no data members. In our example we will use two
6391 interfaces that provide support for the common management of @code{Carnivore}
6392 and @code{Domestic} animals:
6397 virtual int Number_Of_Teeth () = 0;
6402 virtual void Set_Owner (char* Name) = 0;
6406 Using these declarations, we can now say that a @code{Dog} is an animal that is
6407 both Carnivore and Domestic, that is:
6410 class Dog : Animal, Carnivore, Domestic @{
6412 virtual int Number_Of_Teeth ();
6413 virtual void Set_Owner (char* Name);
6415 Dog(); // Constructor
6422 In the following examples we will assume that the previous declarations are
6423 located in a file named @code{animals.h}. The following package demonstrates
6424 how to import these C++ declarations from the Ada side:
6427 with Interfaces.C.Strings; use Interfaces.C.Strings;
6429 type Carnivore is limited interface;
6430 pragma Convention (C_Plus_Plus, Carnivore);
6431 function Number_Of_Teeth (X : Carnivore)
6432 return Natural is abstract;
6434 type Domestic is limited interface;
6435 pragma Convention (C_Plus_Plus, Domestic);
6437 (X : in out Domestic;
6438 Name : Chars_Ptr) is abstract;
6440 type Animal is tagged limited record
6443 pragma Import (C_Plus_Plus, Animal);
6445 procedure Set_Age (X : in out Animal; Age : Integer);
6446 pragma Import (C_Plus_Plus, Set_Age);
6448 function Age (X : Animal) return Integer;
6449 pragma Import (C_Plus_Plus, Age);
6451 function New_Animal return Animal;
6452 pragma CPP_Constructor (New_Animal);
6453 pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6455 type Dog is new Animal and Carnivore and Domestic with record
6456 Tooth_Count : Natural;
6457 Owner : String (1 .. 30);
6459 pragma Import (C_Plus_Plus, Dog);
6461 function Number_Of_Teeth (A : Dog) return Natural;
6462 pragma Import (C_Plus_Plus, Number_Of_Teeth);
6464 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6465 pragma Import (C_Plus_Plus, Set_Owner);
6467 function New_Dog return Dog;
6468 pragma CPP_Constructor (New_Dog);
6469 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6473 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6474 interfacing with these C++ classes is easy. The only requirement is that all
6475 the primitives and components must be declared exactly in the same order in
6478 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6479 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
6480 the arguments to the called primitives will be the same as for C++. For the
6481 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
6482 to indicate that they have been defined on the C++ side; this is required
6483 because the dispatch table associated with these tagged types will be built
6484 in the C++ side and therefore will not contain the predefined Ada primitives
6485 which Ada would otherwise expect.
6487 As the reader can see there is no need to indicate the C++ mangled names
6488 associated with each subprogram because it is assumed that all the calls to
6489 these primitives will be dispatching calls. The only exception is the
6490 constructor, which must be registered with the compiler by means of
6491 @code{pragma CPP_Constructor} and needs to provide its associated C++
6492 mangled name because the Ada compiler generates direct calls to it.
6494 With the above packages we can now declare objects of type Dog on the Ada side
6495 and dispatch calls to the corresponding subprograms on the C++ side. We can
6496 also extend the tagged type Dog with further fields and primitives, and
6497 override some of its C++ primitives on the Ada side. For example, here we have
6498 a type derivation defined on the Ada side that inherits all the dispatching
6499 primitives of the ancestor from the C++ side.
6502 with Animals; use Animals;
6503 package Vaccinated_Animals is
6504 type Vaccinated_Dog is new Dog with null record;
6505 function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6506 end Vaccinated_Animals;
6509 It is important to note that, because of the ABI compatibility, the programmer
6510 does not need to add any further information to indicate either the object
6511 layout or the dispatch table entry associated with each dispatching operation.
6513 Now let us define all the types and constructors on the Ada side and export
6514 them to C++, using the same hierarchy of our previous example:
6517 with Interfaces.C.Strings;
6518 use Interfaces.C.Strings;
6520 type Carnivore is limited interface;
6521 pragma Convention (C_Plus_Plus, Carnivore);
6522 function Number_Of_Teeth (X : Carnivore)
6523 return Natural is abstract;
6525 type Domestic is limited interface;
6526 pragma Convention (C_Plus_Plus, Domestic);
6528 (X : in out Domestic;
6529 Name : Chars_Ptr) is abstract;
6531 type Animal is tagged record
6534 pragma Convention (C_Plus_Plus, Animal);
6536 procedure Set_Age (X : in out Animal; Age : Integer);
6537 pragma Export (C_Plus_Plus, Set_Age);
6539 function Age (X : Animal) return Integer;
6540 pragma Export (C_Plus_Plus, Age);
6542 function New_Animal return Animal'Class;
6543 pragma Export (C_Plus_Plus, New_Animal);
6545 type Dog is new Animal and Carnivore and Domestic with record
6546 Tooth_Count : Natural;
6547 Owner : String (1 .. 30);
6549 pragma Convention (C_Plus_Plus, Dog);
6551 function Number_Of_Teeth (A : Dog) return Natural;
6552 pragma Export (C_Plus_Plus, Number_Of_Teeth);
6554 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6555 pragma Export (C_Plus_Plus, Set_Owner);
6557 function New_Dog return Dog'Class;
6558 pragma Export (C_Plus_Plus, New_Dog);
6562 Compared with our previous example the only differences are the use of
6563 @code{pragma Convention} (instead of @code{pragma Import}), and the use of
6564 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
6565 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6566 nothing else to be done; as explained above, the only requirement is that all
6567 the primitives and components are declared in exactly the same order.
6569 For completeness, let us see a brief C++ main program that uses the
6570 declarations available in @code{animals.h} (presented in our first example) to
6571 import and use the declarations from the Ada side, properly initializing and
6572 finalizing the Ada run-time system along the way:
6575 #include "animals.h"
6577 using namespace std;
6579 void Check_Carnivore (Carnivore *obj) @{...@}
6580 void Check_Domestic (Domestic *obj) @{...@}
6581 void Check_Animal (Animal *obj) @{...@}
6582 void Check_Dog (Dog *obj) @{...@}
6585 void adainit (void);
6586 void adafinal (void);
6592 Dog *obj = new_dog(); // Ada constructor
6593 Check_Carnivore (obj); // Check secondary DT
6594 Check_Domestic (obj); // Check secondary DT
6595 Check_Animal (obj); // Check primary DT
6596 Check_Dog (obj); // Check primary DT
6601 adainit (); test(); adafinal ();
6606 @node Generating Ada Bindings for C and C++ headers,Generating C Headers for Ada Specifications,Building Mixed Ada and C++ Programs,Mixed Language Programming
6607 @anchor{gnat_ugn/the_gnat_compilation_model id70}@anchor{c3}@anchor{gnat_ugn/the_gnat_compilation_model generating-ada-bindings-for-c-and-c-headers}@anchor{19}
6608 @subsection Generating Ada Bindings for C and C++ headers
6611 @geindex Binding generation (for C and C++ headers)
6613 @geindex C headers (binding generation)
6615 @geindex C++ headers (binding generation)
6617 GNAT includes a binding generator for C and C++ headers which is
6618 intended to do 95% of the tedious work of generating Ada specs from C
6619 or C++ header files.
6621 Note that this capability is not intended to generate 100% correct Ada specs,
6622 and will is some cases require manual adjustments, although it can often
6623 be used out of the box in practice.
6625 Some of the known limitations include:
6631 only very simple character constant macros are translated into Ada
6632 constants. Function macros (macros with arguments) are partially translated
6633 as comments, to be completed manually if needed.
6636 some extensions (e.g. vector types) are not supported
6639 pointers to pointers or complex structures are mapped to System.Address
6642 identifiers with identical name (except casing) will generate compilation
6643 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
6646 The code generated is using the Ada 2005 syntax, which makes it
6647 easier to interface with other languages than previous versions of Ada.
6650 * Running the Binding Generator::
6651 * Generating Bindings for C++ Headers::
6656 @node Running the Binding Generator,Generating Bindings for C++ Headers,,Generating Ada Bindings for C and C++ headers
6657 @anchor{gnat_ugn/the_gnat_compilation_model id71}@anchor{c4}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{c5}
6658 @subsubsection Running the Binding Generator
6661 The binding generator is part of the @code{gcc} compiler and can be
6662 invoked via the @code{-fdump-ada-spec} switch, which will generate Ada
6663 spec files for the header files specified on the command line, and all
6664 header files needed by these files transitively. For example:
6667 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
6668 $ gcc -c -gnat05 *.ads
6671 will generate, under GNU/Linux, the following files: @code{time_h.ads},
6672 @code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6673 correspond to the files @code{/usr/include/time.h},
6674 @code{/usr/include/bits/time.h}, etc..., and will then compile these Ada specs
6677 The @code{-C} switch tells @code{gcc} to extract comments from headers,
6678 and will attempt to generate corresponding Ada comments.
6680 If you want to generate a single Ada file and not the transitive closure, you
6681 can use instead the @code{-fdump-ada-spec-slim} switch.
6683 You can optionally specify a parent unit, of which all generated units will
6684 be children, using @code{-fada-spec-parent=@emph{unit}}.
6686 Note that we recommend when possible to use the @emph{g++} driver to
6687 generate bindings, even for most C headers, since this will in general
6688 generate better Ada specs. For generating bindings for C++ headers, it is
6689 mandatory to use the @emph{g++} command, or @emph{gcc -x c++} which
6690 is equivalent in this case. If @emph{g++} cannot work on your C headers
6691 because of incompatibilities between C and C++, then you can fallback to
6694 For an example of better bindings generated from the C++ front-end,
6695 the name of the parameters (when available) are actually ignored by the C
6696 front-end. Consider the following C header:
6699 extern void foo (int variable);
6702 with the C front-end, @code{variable} is ignored, and the above is handled as:
6705 extern void foo (int);
6708 generating a generic:
6711 procedure foo (param1 : int);
6714 with the C++ front-end, the name is available, and we generate:
6717 procedure foo (variable : int);
6720 In some cases, the generated bindings will be more complete or more meaningful
6721 when defining some macros, which you can do via the @code{-D} switch. This
6722 is for example the case with @code{Xlib.h} under GNU/Linux:
6725 $ g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6728 The above will generate more complete bindings than a straight call without
6729 the @code{-DXLIB_ILLEGAL_ACCESS} switch.
6731 In other cases, it is not possible to parse a header file in a stand-alone
6732 manner, because other include files need to be included first. In this
6733 case, the solution is to create a small header file including the needed
6734 @code{#include} and possible @code{#define} directives. For example, to
6735 generate Ada bindings for @code{readline/readline.h}, you need to first
6736 include @code{stdio.h}, so you can create a file with the following two
6737 lines in e.g. @code{readline1.h}:
6741 #include <readline/readline.h>
6744 and then generate Ada bindings from this file:
6747 $ g++ -c -fdump-ada-spec readline1.h
6750 @node Generating Bindings for C++ Headers,Switches,Running the Binding Generator,Generating Ada Bindings for C and C++ headers
6751 @anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{c6}@anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{c7}
6752 @subsubsection Generating Bindings for C++ Headers
6755 Generating bindings for C++ headers is done using the same options, always
6756 with the @emph{g++} compiler. Note that generating Ada spec from C++ headers is a
6757 much more complex job and support for C++ headers is much more limited that
6758 support for C headers. As a result, you will need to modify the resulting
6759 bindings by hand more extensively when using C++ headers.
6761 In this mode, C++ classes will be mapped to Ada tagged types, constructors
6762 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
6763 multiple inheritance of abstract classes will be mapped to Ada interfaces
6764 (see the @emph{Interfacing to C++} section in the @cite{GNAT Reference Manual}
6765 for additional information on interfacing to C++).
6767 For example, given the following C++ header file:
6772 virtual int Number_Of_Teeth () = 0;
6777 virtual void Set_Owner (char* Name) = 0;
6783 virtual void Set_Age (int New_Age);
6786 class Dog : Animal, Carnivore, Domestic @{
6791 virtual int Number_Of_Teeth ();
6792 virtual void Set_Owner (char* Name);
6798 The corresponding Ada code is generated:
6801 package Class_Carnivore is
6802 type Carnivore is limited interface;
6803 pragma Import (CPP, Carnivore);
6805 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6807 use Class_Carnivore;
6809 package Class_Domestic is
6810 type Domestic is limited interface;
6811 pragma Import (CPP, Domestic);
6814 (this : access Domestic;
6815 Name : Interfaces.C.Strings.chars_ptr) is abstract;
6819 package Class_Animal is
6820 type Animal is tagged limited record
6821 Age_Count : aliased int;
6823 pragma Import (CPP, Animal);
6825 procedure Set_Age (this : access Animal; New_Age : int);
6826 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6830 package Class_Dog is
6831 type Dog is new Animal and Carnivore and Domestic with record
6832 Tooth_Count : aliased int;
6833 Owner : Interfaces.C.Strings.chars_ptr;
6835 pragma Import (CPP, Dog);
6837 function Number_Of_Teeth (this : access Dog) return int;
6838 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6841 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6842 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6844 function New_Dog return Dog;
6845 pragma CPP_Constructor (New_Dog);
6846 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6851 @node Switches,,Generating Bindings for C++ Headers,Generating Ada Bindings for C and C++ headers
6852 @anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{c8}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{c9}
6853 @subsubsection Switches
6856 @geindex -fdump-ada-spec (gcc)
6861 @item @code{-fdump-ada-spec}
6863 Generate Ada spec files for the given header files transitively (including
6864 all header files that these headers depend upon).
6867 @geindex -fdump-ada-spec-slim (gcc)
6872 @item @code{-fdump-ada-spec-slim}
6874 Generate Ada spec files for the header files specified on the command line
6878 @geindex -fada-spec-parent (gcc)
6883 @item @code{-fada-spec-parent=@emph{unit}}
6885 Specifies that all files generated by @code{-fdump-ada-spec} are
6886 to be child units of the specified parent unit.
6896 Extract comments from headers and generate Ada comments in the Ada spec files.
6899 @node Generating C Headers for Ada Specifications,,Generating Ada Bindings for C and C++ headers,Mixed Language Programming
6900 @anchor{gnat_ugn/the_gnat_compilation_model generating-c-headers-for-ada-specifications}@anchor{ca}@anchor{gnat_ugn/the_gnat_compilation_model id73}@anchor{cb}
6901 @subsection Generating C Headers for Ada Specifications
6904 @geindex Binding generation (for Ada specs)
6906 @geindex C headers (binding generation)
6908 GNAT includes a C header generator for Ada specifications which supports
6909 Ada types that have a direct mapping to C types. This includes in particular
6925 Composition of the above types
6928 Constant declarations
6934 Subprogram declarations
6938 * Running the C Header Generator::
6942 @node Running the C Header Generator,,,Generating C Headers for Ada Specifications
6943 @anchor{gnat_ugn/the_gnat_compilation_model running-the-c-header-generator}@anchor{cc}
6944 @subsubsection Running the C Header Generator
6947 The C header generator is part of the GNAT compiler and can be invoked via
6948 the @code{-gnatceg} combination of switches, which will generate a @code{.h}
6949 file corresponding to the given input file (Ada spec or body). Note that
6950 only spec files are processed in any case, so giving a spec or a body file
6951 as input is equivalent. For example:
6954 $ gcc -c -gnatceg pack1.ads
6957 will generate a self-contained file called @code{pack1.h} including
6958 common definitions from the Ada Standard package, followed by the
6959 definitions included in @code{pack1.ads}, as well as all the other units
6960 withed by this file.
6962 For instance, given the following Ada files:
6966 type Int is range 1 .. 10;
6975 Field1, Field2 : Pack2.Int;
6978 Global : Rec := (1, 2);
6980 procedure Proc1 (R : Rec);
6981 procedure Proc2 (R : in out Rec);
6985 The above @code{gcc} command will generate the following @code{pack1.h} file:
6988 /* Standard definitions skipped */
6991 typedef short_short_integer pack2__TintB;
6992 typedef pack2__TintB pack2__int;
6993 #endif /* PACK2_ADS */
6997 typedef struct _pack1__rec @{
7001 extern pack1__rec pack1__global;
7002 extern void pack1__proc1(const pack1__rec r);
7003 extern void pack1__proc2(pack1__rec *r);
7004 #endif /* PACK1_ADS */
7007 You can then @code{include} @code{pack1.h} from a C source file and use the types,
7008 call subprograms, reference objects, and constants.
7010 @node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
7011 @anchor{gnat_ugn/the_gnat_compilation_model id74}@anchor{cd}@anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{45}
7012 @section GNAT and Other Compilation Models
7015 This section compares the GNAT model with the approaches taken in
7016 other environents, first the C/C++ model and then the mechanism that
7017 has been used in other Ada systems, in particular those traditionally
7021 * Comparison between GNAT and C/C++ Compilation Models::
7022 * Comparison between GNAT and Conventional Ada Library Models::
7026 @node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
7027 @anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-c-c-compilation-models}@anchor{ce}@anchor{gnat_ugn/the_gnat_compilation_model id75}@anchor{cf}
7028 @subsection Comparison between GNAT and C/C++ Compilation Models
7031 The GNAT model of compilation is close to the C and C++ models. You can
7032 think of Ada specs as corresponding to header files in C. As in C, you
7033 don't need to compile specs; they are compiled when they are used. The
7034 Ada @emph{with} is similar in effect to the @code{#include} of a C
7037 One notable difference is that, in Ada, you may compile specs separately
7038 to check them for semantic and syntactic accuracy. This is not always
7039 possible with C headers because they are fragments of programs that have
7040 less specific syntactic or semantic rules.
7042 The other major difference is the requirement for running the binder,
7043 which performs two important functions. First, it checks for
7044 consistency. In C or C++, the only defense against assembling
7045 inconsistent programs lies outside the compiler, in a makefile, for
7046 example. The binder satisfies the Ada requirement that it be impossible
7047 to construct an inconsistent program when the compiler is used in normal
7050 @geindex Elaboration order control
7052 The other important function of the binder is to deal with elaboration
7053 issues. There are also elaboration issues in C++ that are handled
7054 automatically. This automatic handling has the advantage of being
7055 simpler to use, but the C++ programmer has no control over elaboration.
7056 Where @code{gnatbind} might complain there was no valid order of
7057 elaboration, a C++ compiler would simply construct a program that
7058 malfunctioned at run time.
7060 @node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
7061 @anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-conventional-ada-library-models}@anchor{d0}@anchor{gnat_ugn/the_gnat_compilation_model id76}@anchor{d1}
7062 @subsection Comparison between GNAT and Conventional Ada Library Models
7065 This section is intended for Ada programmers who have
7066 used an Ada compiler implementing the traditional Ada library
7067 model, as described in the Ada Reference Manual.
7069 @geindex GNAT library
7071 In GNAT, there is no 'library' in the normal sense. Instead, the set of
7072 source files themselves acts as the library. Compiling Ada programs does
7073 not generate any centralized information, but rather an object file and
7074 a ALI file, which are of interest only to the binder and linker.
7075 In a traditional system, the compiler reads information not only from
7076 the source file being compiled, but also from the centralized library.
7077 This means that the effect of a compilation depends on what has been
7078 previously compiled. In particular:
7084 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7085 to the version of the unit most recently compiled into the library.
7088 Inlining is effective only if the necessary body has already been
7089 compiled into the library.
7092 Compiling a unit may obsolete other units in the library.
7095 In GNAT, compiling one unit never affects the compilation of any other
7096 units because the compiler reads only source files. Only changes to source
7097 files can affect the results of a compilation. In particular:
7103 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7104 to the source version of the unit that is currently accessible to the
7110 Inlining requires the appropriate source files for the package or
7111 subprogram bodies to be available to the compiler. Inlining is always
7112 effective, independent of the order in which units are compiled.
7115 Compiling a unit never affects any other compilations. The editing of
7116 sources may cause previous compilations to be out of date if they
7117 depended on the source file being modified.
7120 The most important result of these differences is that order of compilation
7121 is never significant in GNAT. There is no situation in which one is
7122 required to do one compilation before another. What shows up as order of
7123 compilation requirements in the traditional Ada library becomes, in
7124 GNAT, simple source dependencies; in other words, there is only a set
7125 of rules saying what source files must be present when a file is
7128 @node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
7129 @anchor{gnat_ugn/the_gnat_compilation_model using-gnat-files-with-external-tools}@anchor{1a}@anchor{gnat_ugn/the_gnat_compilation_model id77}@anchor{d2}
7130 @section Using GNAT Files with External Tools
7133 This section explains how files that are produced by GNAT may be
7134 used with tools designed for other languages.
7137 * Using Other Utility Programs with GNAT::
7138 * The External Symbol Naming Scheme of GNAT::
7142 @node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
7143 @anchor{gnat_ugn/the_gnat_compilation_model using-other-utility-programs-with-gnat}@anchor{d3}@anchor{gnat_ugn/the_gnat_compilation_model id78}@anchor{d4}
7144 @subsection Using Other Utility Programs with GNAT
7147 The object files generated by GNAT are in standard system format and in
7148 particular the debugging information uses this format. This means
7149 programs generated by GNAT can be used with existing utilities that
7150 depend on these formats.
7152 In general, any utility program that works with C will also often work with
7153 Ada programs generated by GNAT. This includes software utilities such as
7154 gprof (a profiling program), gdb (the FSF debugger), and utilities such
7157 @node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
7158 @anchor{gnat_ugn/the_gnat_compilation_model the-external-symbol-naming-scheme-of-gnat}@anchor{d5}@anchor{gnat_ugn/the_gnat_compilation_model id79}@anchor{d6}
7159 @subsection The External Symbol Naming Scheme of GNAT
7162 In order to interpret the output from GNAT, when using tools that are
7163 originally intended for use with other languages, it is useful to
7164 understand the conventions used to generate link names from the Ada
7167 All link names are in all lowercase letters. With the exception of library
7168 procedure names, the mechanism used is simply to use the full expanded
7169 Ada name with dots replaced by double underscores. For example, suppose
7170 we have the following package spec:
7178 @geindex pragma Export
7180 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
7181 the corresponding link name is @code{qrs__mn}.
7182 Of course if a @code{pragma Export} is used this may be overridden:
7187 pragma Export (Var1, C, External_Name => "var1_name");
7189 pragma Export (Var2, C, Link_Name => "var2_link_name");
7193 In this case, the link name for @code{Var1} is whatever link name the
7194 C compiler would assign for the C function @code{var1_name}. This typically
7195 would be either @code{var1_name} or @code{_var1_name}, depending on operating
7196 system conventions, but other possibilities exist. The link name for
7197 @code{Var2} is @code{var2_link_name}, and this is not operating system
7200 One exception occurs for library level procedures. A potential ambiguity
7201 arises between the required name @code{_main} for the C main program,
7202 and the name we would otherwise assign to an Ada library level procedure
7203 called @code{Main} (which might well not be the main program).
7205 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
7206 names. So if we have a library level procedure such as:
7209 procedure Hello (S : String);
7212 the external name of this procedure will be @code{_ada_hello}.
7214 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7216 @node Building Executable Programs with GNAT,GNAT Utility Programs,The GNAT Compilation Model,Top
7217 @anchor{gnat_ugn/building_executable_programs_with_gnat building-executable-programs-with-gnat}@anchor{a}@anchor{gnat_ugn/building_executable_programs_with_gnat doc}@anchor{d7}@anchor{gnat_ugn/building_executable_programs_with_gnat id1}@anchor{d8}
7218 @chapter Building Executable Programs with GNAT
7221 This chapter describes first the gnatmake tool
7222 (@ref{1b,,Building with gnatmake}),
7223 which automatically determines the set of sources
7224 needed by an Ada compilation unit and executes the necessary
7225 (re)compilations, binding and linking.
7226 It also explains how to use each tool individually: the
7227 compiler (gcc, see @ref{1c,,Compiling with gcc}),
7228 binder (gnatbind, see @ref{1d,,Binding with gnatbind}),
7229 and linker (gnatlink, see @ref{1e,,Linking with gnatlink})
7230 to build executable programs.
7231 Finally, this chapter provides examples of
7232 how to make use of the general GNU make mechanism
7233 in a GNAT context (see @ref{1f,,Using the GNU make Utility}).
7237 * Building with gnatmake::
7238 * Compiling with gcc::
7239 * Compiler Switches::
7241 * Binding with gnatbind::
7242 * Linking with gnatlink::
7243 * Using the GNU make Utility::
7247 @node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
7248 @anchor{gnat_ugn/building_executable_programs_with_gnat the-gnat-make-program-gnatmake}@anchor{1b}@anchor{gnat_ugn/building_executable_programs_with_gnat building-with-gnatmake}@anchor{d9}
7249 @section Building with @code{gnatmake}
7254 A typical development cycle when working on an Ada program consists of
7255 the following steps:
7261 Edit some sources to fix bugs;
7267 Compile all sources affected;
7270 Rebind and relink; and
7276 @geindex Dependency rules (compilation)
7278 The third step in particular can be tricky, because not only do the modified
7279 files have to be compiled, but any files depending on these files must also be
7280 recompiled. The dependency rules in Ada can be quite complex, especially
7281 in the presence of overloading, @code{use} clauses, generics and inlined
7284 @code{gnatmake} automatically takes care of the third and fourth steps
7285 of this process. It determines which sources need to be compiled,
7286 compiles them, and binds and links the resulting object files.
7288 Unlike some other Ada make programs, the dependencies are always
7289 accurately recomputed from the new sources. The source based approach of
7290 the GNAT compilation model makes this possible. This means that if
7291 changes to the source program cause corresponding changes in
7292 dependencies, they will always be tracked exactly correctly by
7295 Note that for advanced forms of project structure, we recommend creating
7296 a project file as explained in the @emph{GNAT_Project_Manager} chapter in the
7297 @emph{GPRbuild User's Guide}, and using the
7298 @code{gprbuild} tool which supports building with project files and works similarly
7302 * Running gnatmake::
7303 * Switches for gnatmake::
7304 * Mode Switches for gnatmake::
7305 * Notes on the Command Line::
7306 * How gnatmake Works::
7307 * Examples of gnatmake Usage::
7311 @node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7312 @anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{da}@anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{db}
7313 @subsection Running @code{gnatmake}
7316 The usual form of the @code{gnatmake} command is
7319 $ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7322 The only required argument is one @code{file_name}, which specifies
7323 a compilation unit that is a main program. Several @code{file_names} can be
7324 specified: this will result in several executables being built.
7325 If @code{switches} are present, they can be placed before the first
7326 @code{file_name}, between @code{file_names} or after the last @code{file_name}.
7327 If @code{mode_switches} are present, they must always be placed after
7328 the last @code{file_name} and all @code{switches}.
7330 If you are using standard file extensions (@code{.adb} and
7331 @code{.ads}), then the
7332 extension may be omitted from the @code{file_name} arguments. However, if
7333 you are using non-standard extensions, then it is required that the
7334 extension be given. A relative or absolute directory path can be
7335 specified in a @code{file_name}, in which case, the input source file will
7336 be searched for in the specified directory only. Otherwise, the input
7337 source file will first be searched in the directory where
7338 @code{gnatmake} was invoked and if it is not found, it will be search on
7339 the source path of the compiler as described in
7340 @ref{89,,Search Paths and the Run-Time Library (RTL)}.
7342 All @code{gnatmake} output (except when you specify @code{-M}) is sent to
7343 @code{stderr}. The output produced by the
7344 @code{-M} switch is sent to @code{stdout}.
7346 @node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7347 @anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{dc}@anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{dd}
7348 @subsection Switches for @code{gnatmake}
7351 You may specify any of the following switches to @code{gnatmake}:
7353 @geindex --version (gnatmake)
7358 @item @code{--version}
7360 Display Copyright and version, then exit disregarding all other options.
7363 @geindex --help (gnatmake)
7370 If @code{--version} was not used, display usage, then exit disregarding
7374 @geindex --GCC=compiler_name (gnatmake)
7379 @item @code{--GCC=@emph{compiler_name}}
7381 Program used for compiling. The default is @code{gcc}. You need to use
7382 quotes around @code{compiler_name} if @code{compiler_name} contains
7383 spaces or other separator characters.
7384 As an example @code{--GCC="foo -x -y"}
7385 will instruct @code{gnatmake} to use @code{foo -x -y} as your
7386 compiler. A limitation of this syntax is that the name and path name of
7387 the executable itself must not include any embedded spaces. Note that
7388 switch @code{-c} is always inserted after your command name. Thus in the
7389 above example the compiler command that will be used by @code{gnatmake}
7390 will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7391 used, only the last @code{compiler_name} is taken into account. However,
7392 all the additional switches are also taken into account. Thus,
7393 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7394 @code{--GCC="bar -x -y -z -t"}.
7397 @geindex --GNATBIND=binder_name (gnatmake)
7402 @item @code{--GNATBIND=@emph{binder_name}}
7404 Program used for binding. The default is @code{gnatbind}. You need to
7405 use quotes around @code{binder_name} if @code{binder_name} contains spaces
7406 or other separator characters.
7407 As an example @code{--GNATBIND="bar -x -y"}
7408 will instruct @code{gnatmake} to use @code{bar -x -y} as your
7409 binder. Binder switches that are normally appended by @code{gnatmake}
7410 to @code{gnatbind} are now appended to the end of @code{bar -x -y}.
7411 A limitation of this syntax is that the name and path name of the executable
7412 itself must not include any embedded spaces.
7415 @geindex --GNATLINK=linker_name (gnatmake)
7420 @item @code{--GNATLINK=@emph{linker_name}}
7422 Program used for linking. The default is @code{gnatlink}. You need to
7423 use quotes around @code{linker_name} if @code{linker_name} contains spaces
7424 or other separator characters.
7425 As an example @code{--GNATLINK="lan -x -y"}
7426 will instruct @code{gnatmake} to use @code{lan -x -y} as your
7427 linker. Linker switches that are normally appended by @code{gnatmake} to
7428 @code{gnatlink} are now appended to the end of @code{lan -x -y}.
7429 A limitation of this syntax is that the name and path name of the executable
7430 itself must not include any embedded spaces.
7432 @item @code{--create-map-file}
7434 When linking an executable, create a map file. The name of the map file
7435 has the same name as the executable with extension ".map".
7437 @item @code{--create-map-file=@emph{mapfile}}
7439 When linking an executable, create a map file with the specified name.
7442 @geindex --create-missing-dirs (gnatmake)
7447 @item @code{--create-missing-dirs}
7449 When using project files (@code{-P@emph{project}}), automatically create
7450 missing object directories, library directories and exec
7453 @item @code{--single-compile-per-obj-dir}
7455 Disallow simultaneous compilations in the same object directory when
7456 project files are used.
7458 @item @code{--subdirs=@emph{subdir}}
7460 Actual object directory of each project file is the subdirectory subdir of the
7461 object directory specified or defaulted in the project file.
7463 @item @code{--unchecked-shared-lib-imports}
7465 By default, shared library projects are not allowed to import static library
7466 projects. When this switch is used on the command line, this restriction is
7469 @item @code{--source-info=@emph{source info file}}
7471 Specify a source info file. This switch is active only when project files
7472 are used. If the source info file is specified as a relative path, then it is
7473 relative to the object directory of the main project. If the source info file
7474 does not exist, then after the Project Manager has successfully parsed and
7475 processed the project files and found the sources, it creates the source info
7476 file. If the source info file already exists and can be read successfully,
7477 then the Project Manager will get all the needed information about the sources
7478 from the source info file and will not look for them. This reduces the time
7479 to process the project files, especially when looking for sources that take a
7480 long time. If the source info file exists but cannot be parsed successfully,
7481 the Project Manager will attempt to recreate it. If the Project Manager fails
7482 to create the source info file, a message is issued, but gnatmake does not
7483 fail. @code{gnatmake} "trusts" the source info file. This means that
7484 if the source files have changed (addition, deletion, moving to a different
7485 source directory), then the source info file need to be deleted and recreated.
7488 @geindex -a (gnatmake)
7495 Consider all files in the make process, even the GNAT internal system
7496 files (for example, the predefined Ada library files), as well as any
7497 locked files. Locked files are files whose ALI file is write-protected.
7499 @code{gnatmake} does not check these files,
7500 because the assumption is that the GNAT internal files are properly up
7501 to date, and also that any write protected ALI files have been properly
7502 installed. Note that if there is an installation problem, such that one
7503 of these files is not up to date, it will be properly caught by the
7505 You may have to specify this switch if you are working on GNAT
7506 itself. The switch @code{-a} is also useful
7507 in conjunction with @code{-f}
7508 if you need to recompile an entire application,
7509 including run-time files, using special configuration pragmas,
7510 such as a @code{Normalize_Scalars} pragma.
7513 @code{gnatmake -a} compiles all GNAT
7515 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7518 @geindex -b (gnatmake)
7525 Bind only. Can be combined with @code{-c} to do
7526 compilation and binding, but no link.
7527 Can be combined with @code{-l}
7528 to do binding and linking. When not combined with
7530 all the units in the closure of the main program must have been previously
7531 compiled and must be up to date. The root unit specified by @code{file_name}
7532 may be given without extension, with the source extension or, if no GNAT
7533 Project File is specified, with the ALI file extension.
7536 @geindex -c (gnatmake)
7543 Compile only. Do not perform binding, except when @code{-b}
7544 is also specified. Do not perform linking, except if both
7546 @code{-l} are also specified.
7547 If the root unit specified by @code{file_name} is not a main unit, this is the
7548 default. Otherwise @code{gnatmake} will attempt binding and linking
7549 unless all objects are up to date and the executable is more recent than
7553 @geindex -C (gnatmake)
7560 Use a temporary mapping file. A mapping file is a way to communicate
7561 to the compiler two mappings: from unit names to file names (without
7562 any directory information) and from file names to path names (with
7563 full directory information). A mapping file can make the compiler's
7564 file searches faster, especially if there are many source directories,
7565 or the sources are read over a slow network connection. If
7566 @code{-P} is used, a mapping file is always used, so
7567 @code{-C} is unnecessary; in this case the mapping file
7568 is initially populated based on the project file. If
7569 @code{-C} is used without
7571 the mapping file is initially empty. Each invocation of the compiler
7572 will add any newly accessed sources to the mapping file.
7575 @geindex -C= (gnatmake)
7580 @item @code{-C=@emph{file}}
7582 Use a specific mapping file. The file, specified as a path name (absolute or
7583 relative) by this switch, should already exist, otherwise the switch is
7584 ineffective. The specified mapping file will be communicated to the compiler.
7585 This switch is not compatible with a project file
7586 (-P`file`) or with multiple compiling processes
7587 (-jnnn, when nnn is greater than 1).
7590 @geindex -d (gnatmake)
7597 Display progress for each source, up to date or not, as a single line:
7600 completed x out of y (zz%)
7603 If the file needs to be compiled this is displayed after the invocation of
7604 the compiler. These lines are displayed even in quiet output mode.
7607 @geindex -D (gnatmake)
7612 @item @code{-D @emph{dir}}
7614 Put all object files and ALI file in directory @code{dir}.
7615 If the @code{-D} switch is not used, all object files
7616 and ALI files go in the current working directory.
7618 This switch cannot be used when using a project file.
7621 @geindex -eI (gnatmake)
7626 @item @code{-eI@emph{nnn}}
7628 Indicates that the main source is a multi-unit source and the rank of the unit
7629 in the source file is nnn. nnn needs to be a positive number and a valid
7630 index in the source. This switch cannot be used when @code{gnatmake} is
7631 invoked for several mains.
7634 @geindex -eL (gnatmake)
7636 @geindex symbolic links
7643 Follow all symbolic links when processing project files.
7644 This should be used if your project uses symbolic links for files or
7645 directories, but is not needed in other cases.
7647 @geindex naming scheme
7649 This also assumes that no directory matches the naming scheme for files (for
7650 instance that you do not have a directory called "sources.ads" when using the
7651 default GNAT naming scheme).
7653 When you do not have to use this switch (i.e., by default), gnatmake is able to
7654 save a lot of system calls (several per source file and object file), which
7655 can result in a significant speed up to load and manipulate a project file,
7656 especially when using source files from a remote system.
7659 @geindex -eS (gnatmake)
7666 Output the commands for the compiler, the binder and the linker
7668 instead of standard error.
7671 @geindex -f (gnatmake)
7678 Force recompilations. Recompile all sources, even though some object
7679 files may be up to date, but don't recompile predefined or GNAT internal
7680 files or locked files (files with a write-protected ALI file),
7681 unless the @code{-a} switch is also specified.
7684 @geindex -F (gnatmake)
7691 When using project files, if some errors or warnings are detected during
7692 parsing and verbose mode is not in effect (no use of switch
7693 -v), then error lines start with the full path name of the project
7694 file, rather than its simple file name.
7697 @geindex -g (gnatmake)
7704 Enable debugging. This switch is simply passed to the compiler and to the
7708 @geindex -i (gnatmake)
7715 In normal mode, @code{gnatmake} compiles all object files and ALI files
7716 into the current directory. If the @code{-i} switch is used,
7717 then instead object files and ALI files that already exist are overwritten
7718 in place. This means that once a large project is organized into separate
7719 directories in the desired manner, then @code{gnatmake} will automatically
7720 maintain and update this organization. If no ALI files are found on the
7721 Ada object path (see @ref{89,,Search Paths and the Run-Time Library (RTL)}),
7722 the new object and ALI files are created in the
7723 directory containing the source being compiled. If another organization
7724 is desired, where objects and sources are kept in different directories,
7725 a useful technique is to create dummy ALI files in the desired directories.
7726 When detecting such a dummy file, @code{gnatmake} will be forced to
7727 recompile the corresponding source file, and it will be put the resulting
7728 object and ALI files in the directory where it found the dummy file.
7731 @geindex -j (gnatmake)
7733 @geindex Parallel make
7738 @item @code{-j@emph{n}}
7740 Use @code{n} processes to carry out the (re)compilations. On a multiprocessor
7741 machine compilations will occur in parallel. If @code{n} is 0, then the
7742 maximum number of parallel compilations is the number of core processors
7743 on the platform. In the event of compilation errors, messages from various
7744 compilations might get interspersed (but @code{gnatmake} will give you the
7745 full ordered list of failing compiles at the end). If this is problematic,
7746 rerun the make process with n set to 1 to get a clean list of messages.
7749 @geindex -k (gnatmake)
7756 Keep going. Continue as much as possible after a compilation error. To
7757 ease the programmer's task in case of compilation errors, the list of
7758 sources for which the compile fails is given when @code{gnatmake}
7761 If @code{gnatmake} is invoked with several @code{file_names} and with this
7762 switch, if there are compilation errors when building an executable,
7763 @code{gnatmake} will not attempt to build the following executables.
7766 @geindex -l (gnatmake)
7773 Link only. Can be combined with @code{-b} to binding
7774 and linking. Linking will not be performed if combined with
7776 but not with @code{-b}.
7777 When not combined with @code{-b}
7778 all the units in the closure of the main program must have been previously
7779 compiled and must be up to date, and the main program needs to have been bound.
7780 The root unit specified by @code{file_name}
7781 may be given without extension, with the source extension or, if no GNAT
7782 Project File is specified, with the ALI file extension.
7785 @geindex -m (gnatmake)
7792 Specify that the minimum necessary amount of recompilations
7793 be performed. In this mode @code{gnatmake} ignores time
7794 stamp differences when the only
7795 modifications to a source file consist in adding/removing comments,
7796 empty lines, spaces or tabs. This means that if you have changed the
7797 comments in a source file or have simply reformatted it, using this
7798 switch will tell @code{gnatmake} not to recompile files that depend on it
7799 (provided other sources on which these files depend have undergone no
7800 semantic modifications). Note that the debugging information may be
7801 out of date with respect to the sources if the @code{-m} switch causes
7802 a compilation to be switched, so the use of this switch represents a
7803 trade-off between compilation time and accurate debugging information.
7806 @geindex Dependencies
7807 @geindex producing list
7809 @geindex -M (gnatmake)
7816 Check if all objects are up to date. If they are, output the object
7817 dependences to @code{stdout} in a form that can be directly exploited in
7818 a @code{Makefile}. By default, each source file is prefixed with its
7819 (relative or absolute) directory name. This name is whatever you
7820 specified in the various @code{-aI}
7821 and @code{-I} switches. If you use
7822 @code{gnatmake -M} @code{-q}
7823 (see below), only the source file names,
7824 without relative paths, are output. If you just specify the @code{-M}
7825 switch, dependencies of the GNAT internal system files are omitted. This
7826 is typically what you want. If you also specify
7827 the @code{-a} switch,
7828 dependencies of the GNAT internal files are also listed. Note that
7829 dependencies of the objects in external Ada libraries (see
7830 switch @code{-aL@emph{dir}} in the following list)
7834 @geindex -n (gnatmake)
7841 Don't compile, bind, or link. Checks if all objects are up to date.
7842 If they are not, the full name of the first file that needs to be
7843 recompiled is printed.
7844 Repeated use of this option, followed by compiling the indicated source
7845 file, will eventually result in recompiling all required units.
7848 @geindex -o (gnatmake)
7853 @item @code{-o @emph{exec_name}}
7855 Output executable name. The name of the final executable program will be
7856 @code{exec_name}. If the @code{-o} switch is omitted the default
7857 name for the executable will be the name of the input file in appropriate form
7858 for an executable file on the host system.
7860 This switch cannot be used when invoking @code{gnatmake} with several
7864 @geindex -p (gnatmake)
7871 Same as @code{--create-missing-dirs}
7874 @geindex -P (gnatmake)
7879 @item @code{-P@emph{project}}
7881 Use project file @code{project}. Only one such switch can be used.
7885 @c :ref:`gnatmake_and_Project_Files`.
7887 @geindex -q (gnatmake)
7894 Quiet. When this flag is not set, the commands carried out by
7895 @code{gnatmake} are displayed.
7898 @geindex -s (gnatmake)
7905 Recompile if compiler switches have changed since last compilation.
7906 All compiler switches but -I and -o are taken into account in the
7908 orders between different 'first letter' switches are ignored, but
7909 orders between same switches are taken into account. For example,
7910 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O}
7911 is equivalent to @code{-O -g}.
7913 This switch is recommended when Integrated Preprocessing is used.
7916 @geindex -u (gnatmake)
7923 Unique. Recompile at most the main files. It implies -c. Combined with
7924 -f, it is equivalent to calling the compiler directly. Note that using
7925 -u with a project file and no main has a special meaning.
7929 @c (See :ref:`Project_Files_and_Main_Subprograms`.)
7931 @geindex -U (gnatmake)
7938 When used without a project file or with one or several mains on the command
7939 line, is equivalent to -u. When used with a project file and no main
7940 on the command line, all sources of all project files are checked and compiled
7941 if not up to date, and libraries are rebuilt, if necessary.
7944 @geindex -v (gnatmake)
7951 Verbose. Display the reason for all recompilations @code{gnatmake}
7952 decides are necessary, with the highest verbosity level.
7955 @geindex -vl (gnatmake)
7962 Verbosity level Low. Display fewer lines than in verbosity Medium.
7965 @geindex -vm (gnatmake)
7972 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7975 @geindex -vm (gnatmake)
7982 Verbosity level High. Equivalent to -v.
7984 @item @code{-vP@emph{x}}
7986 Indicate the verbosity of the parsing of GNAT project files.
7987 See @ref{de,,Switches Related to Project Files}.
7990 @geindex -x (gnatmake)
7997 Indicate that sources that are not part of any Project File may be compiled.
7998 Normally, when using Project Files, only sources that are part of a Project
7999 File may be compile. When this switch is used, a source outside of all Project
8000 Files may be compiled. The ALI file and the object file will be put in the
8001 object directory of the main Project. The compilation switches used will only
8002 be those specified on the command line. Even when
8003 @code{-x} is used, mains specified on the
8004 command line need to be sources of a project file.
8006 @item @code{-X@emph{name}=@emph{value}}
8008 Indicate that external variable @code{name} has the value @code{value}.
8009 The Project Manager will use this value for occurrences of
8010 @code{external(name)} when parsing the project file.
8011 @ref{de,,Switches Related to Project Files}.
8014 @geindex -z (gnatmake)
8021 No main subprogram. Bind and link the program even if the unit name
8022 given on the command line is a package name. The resulting executable
8023 will execute the elaboration routines of the package and its closure,
8024 then the finalization routines.
8027 @subsubheading GCC switches
8030 Any uppercase or multi-character switch that is not a @code{gnatmake} switch
8031 is passed to @code{gcc} (e.g., @code{-O}, @code{-gnato,} etc.)
8033 @subsubheading Source and library search path switches
8036 @geindex -aI (gnatmake)
8041 @item @code{-aI@emph{dir}}
8043 When looking for source files also look in directory @code{dir}.
8044 The order in which source files search is undertaken is
8045 described in @ref{89,,Search Paths and the Run-Time Library (RTL)}.
8048 @geindex -aL (gnatmake)
8053 @item @code{-aL@emph{dir}}
8055 Consider @code{dir} as being an externally provided Ada library.
8056 Instructs @code{gnatmake} to skip compilation units whose @code{.ALI}
8057 files have been located in directory @code{dir}. This allows you to have
8058 missing bodies for the units in @code{dir} and to ignore out of date bodies
8059 for the same units. You still need to specify
8060 the location of the specs for these units by using the switches
8061 @code{-aI@emph{dir}} or @code{-I@emph{dir}}.
8062 Note: this switch is provided for compatibility with previous versions
8063 of @code{gnatmake}. The easier method of causing standard libraries
8064 to be excluded from consideration is to write-protect the corresponding
8068 @geindex -aO (gnatmake)
8073 @item @code{-aO@emph{dir}}
8075 When searching for library and object files, look in directory
8076 @code{dir}. The order in which library files are searched is described in
8077 @ref{8c,,Search Paths for gnatbind}.
8080 @geindex Search paths
8081 @geindex for gnatmake
8083 @geindex -A (gnatmake)
8088 @item @code{-A@emph{dir}}
8090 Equivalent to @code{-aL@emph{dir}} @code{-aI@emph{dir}}.
8092 @geindex -I (gnatmake)
8094 @item @code{-I@emph{dir}}
8096 Equivalent to @code{-aO@emph{dir} -aI@emph{dir}}.
8099 @geindex -I- (gnatmake)
8101 @geindex Source files
8102 @geindex suppressing search
8109 Do not look for source files in the directory containing the source
8110 file named in the command line.
8111 Do not look for ALI or object files in the directory
8112 where @code{gnatmake} was invoked.
8115 @geindex -L (gnatmake)
8117 @geindex Linker libraries
8122 @item @code{-L@emph{dir}}
8124 Add directory @code{dir} to the list of directories in which the linker
8125 will search for libraries. This is equivalent to
8126 @code{-largs} @code{-L@emph{dir}}.
8127 Furthermore, under Windows, the sources pointed to by the libraries path
8128 set in the registry are not searched for.
8131 @geindex -nostdinc (gnatmake)
8136 @item @code{-nostdinc}
8138 Do not look for source files in the system default directory.
8141 @geindex -nostdlib (gnatmake)
8146 @item @code{-nostdlib}
8148 Do not look for library files in the system default directory.
8151 @geindex --RTS (gnatmake)
8156 @item @code{--RTS=@emph{rts-path}}
8158 Specifies the default location of the runtime library. GNAT looks for the
8160 in the following directories, and stops as soon as a valid runtime is found
8161 (@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
8162 @code{ada_object_path} present):
8168 @emph{<current directory>/$rts_path}
8171 @emph{<default-search-dir>/$rts_path}
8174 @emph{<default-search-dir>/rts-$rts_path}
8177 The selected path is handled like a normal RTS path.
8181 @node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
8182 @anchor{gnat_ugn/building_executable_programs_with_gnat id4}@anchor{df}@anchor{gnat_ugn/building_executable_programs_with_gnat mode-switches-for-gnatmake}@anchor{e0}
8183 @subsection Mode Switches for @code{gnatmake}
8186 The mode switches (referred to as @code{mode_switches}) allow the
8187 inclusion of switches that are to be passed to the compiler itself, the
8188 binder or the linker. The effect of a mode switch is to cause all
8189 subsequent switches up to the end of the switch list, or up to the next
8190 mode switch, to be interpreted as switches to be passed on to the
8191 designated component of GNAT.
8193 @geindex -cargs (gnatmake)
8198 @item @code{-cargs @emph{switches}}
8200 Compiler switches. Here @code{switches} is a list of switches
8201 that are valid switches for @code{gcc}. They will be passed on to
8202 all compile steps performed by @code{gnatmake}.
8205 @geindex -bargs (gnatmake)
8210 @item @code{-bargs @emph{switches}}
8212 Binder switches. Here @code{switches} is a list of switches
8213 that are valid switches for @code{gnatbind}. They will be passed on to
8214 all bind steps performed by @code{gnatmake}.
8217 @geindex -largs (gnatmake)
8222 @item @code{-largs @emph{switches}}
8224 Linker switches. Here @code{switches} is a list of switches
8225 that are valid switches for @code{gnatlink}. They will be passed on to
8226 all link steps performed by @code{gnatmake}.
8229 @geindex -margs (gnatmake)
8234 @item @code{-margs @emph{switches}}
8236 Make switches. The switches are directly interpreted by @code{gnatmake},
8237 regardless of any previous occurrence of @code{-cargs}, @code{-bargs}
8241 @node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
8242 @anchor{gnat_ugn/building_executable_programs_with_gnat id5}@anchor{e1}@anchor{gnat_ugn/building_executable_programs_with_gnat notes-on-the-command-line}@anchor{e2}
8243 @subsection Notes on the Command Line
8246 This section contains some additional useful notes on the operation
8247 of the @code{gnatmake} command.
8249 @geindex Recompilation (by gnatmake)
8255 If @code{gnatmake} finds no ALI files, it recompiles the main program
8256 and all other units required by the main program.
8257 This means that @code{gnatmake}
8258 can be used for the initial compile, as well as during subsequent steps of
8259 the development cycle.
8262 If you enter @code{gnatmake foo.adb}, where @code{foo}
8263 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8264 @code{foo.adb} (because it finds no ALI) and stops, issuing a
8268 In @code{gnatmake} the switch @code{-I}
8269 is used to specify both source and
8270 library file paths. Use @code{-aI}
8271 instead if you just want to specify
8272 source paths only and @code{-aO}
8273 if you want to specify library paths
8277 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8278 This may conveniently be used to exclude standard libraries from
8279 consideration and in particular it means that the use of the
8280 @code{-f} switch will not recompile these files
8281 unless @code{-a} is also specified.
8284 @code{gnatmake} has been designed to make the use of Ada libraries
8285 particularly convenient. Assume you have an Ada library organized
8286 as follows: @emph{obj-dir} contains the objects and ALI files for
8287 of your Ada compilation units,
8288 whereas @emph{include-dir} contains the
8289 specs of these units, but no bodies. Then to compile a unit
8290 stored in @code{main.adb}, which uses this Ada library you would just type:
8293 $ gnatmake -aI`include-dir` -aL`obj-dir` main
8297 Using @code{gnatmake} along with the @code{-m (minimal recompilation)}
8298 switch provides a mechanism for avoiding unnecessary recompilations. Using
8300 you can update the comments/format of your
8301 source files without having to recompile everything. Note, however, that
8302 adding or deleting lines in a source files may render its debugging
8303 info obsolete. If the file in question is a spec, the impact is rather
8304 limited, as that debugging info will only be useful during the
8305 elaboration phase of your program. For bodies the impact can be more
8306 significant. In all events, your debugger will warn you if a source file
8307 is more recent than the corresponding object, and alert you to the fact
8308 that the debugging information may be out of date.
8311 @node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8312 @anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{e3}@anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{e4}
8313 @subsection How @code{gnatmake} Works
8316 Generally @code{gnatmake} automatically performs all necessary
8317 recompilations and you don't need to worry about how it works. However,
8318 it may be useful to have some basic understanding of the @code{gnatmake}
8319 approach and in particular to understand how it uses the results of
8320 previous compilations without incorrectly depending on them.
8322 First a definition: an object file is considered @emph{up to date} if the
8323 corresponding ALI file exists and if all the source files listed in the
8324 dependency section of this ALI file have time stamps matching those in
8325 the ALI file. This means that neither the source file itself nor any
8326 files that it depends on have been modified, and hence there is no need
8327 to recompile this file.
8329 @code{gnatmake} works by first checking if the specified main unit is up
8330 to date. If so, no compilations are required for the main unit. If not,
8331 @code{gnatmake} compiles the main program to build a new ALI file that
8332 reflects the latest sources. Then the ALI file of the main unit is
8333 examined to find all the source files on which the main program depends,
8334 and @code{gnatmake} recursively applies the above procedure on all these
8337 This process ensures that @code{gnatmake} only trusts the dependencies
8338 in an existing ALI file if they are known to be correct. Otherwise it
8339 always recompiles to determine a new, guaranteed accurate set of
8340 dependencies. As a result the program is compiled 'upside down' from what may
8341 be more familiar as the required order of compilation in some other Ada
8342 systems. In particular, clients are compiled before the units on which
8343 they depend. The ability of GNAT to compile in any order is critical in
8344 allowing an order of compilation to be chosen that guarantees that
8345 @code{gnatmake} will recompute a correct set of new dependencies if
8348 When invoking @code{gnatmake} with several @code{file_names}, if a unit is
8349 imported by several of the executables, it will be recompiled at most once.
8351 Note: when using non-standard naming conventions
8352 (@ref{35,,Using Other File Names}), changing through a configuration pragmas
8353 file the version of a source and invoking @code{gnatmake} to recompile may
8354 have no effect, if the previous version of the source is still accessible
8355 by @code{gnatmake}. It may be necessary to use the switch
8358 @node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8359 @anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatmake-usage}@anchor{e5}@anchor{gnat_ugn/building_executable_programs_with_gnat id7}@anchor{e6}
8360 @subsection Examples of @code{gnatmake} Usage
8366 @item @emph{gnatmake hello.adb}
8368 Compile all files necessary to bind and link the main program
8369 @code{hello.adb} (containing unit @code{Hello}) and bind and link the
8370 resulting object files to generate an executable file @code{hello}.
8372 @item @emph{gnatmake main1 main2 main3}
8374 Compile all files necessary to bind and link the main programs
8375 @code{main1.adb} (containing unit @code{Main1}), @code{main2.adb}
8376 (containing unit @code{Main2}) and @code{main3.adb}
8377 (containing unit @code{Main3}) and bind and link the resulting object files
8378 to generate three executable files @code{main1},
8379 @code{main2} and @code{main3}.
8381 @item @emph{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8383 Compile all files necessary to bind and link the main program unit
8384 @code{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8385 be done with optimization level 2 and the order of elaboration will be
8386 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8387 displaying commands it is executing.
8390 @node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8391 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{1c}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{e7}
8392 @section Compiling with @code{gcc}
8395 This section discusses how to compile Ada programs using the @code{gcc}
8396 command. It also describes the set of switches
8397 that can be used to control the behavior of the compiler.
8400 * Compiling Programs::
8401 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL.
8402 * Order of Compilation Issues::
8407 @node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8408 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{e8}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{e9}
8409 @subsection Compiling Programs
8412 The first step in creating an executable program is to compile the units
8413 of the program using the @code{gcc} command. You must compile the
8420 the body file (@code{.adb}) for a library level subprogram or generic
8424 the spec file (@code{.ads}) for a library level package or generic
8425 package that has no body
8428 the body file (@code{.adb}) for a library level package
8429 or generic package that has a body
8432 You need @emph{not} compile the following files
8438 the spec of a library unit which has a body
8444 because they are compiled as part of compiling related units. GNAT
8446 when the corresponding body is compiled, and subunits when the parent is
8449 @geindex cannot generate code
8451 If you attempt to compile any of these files, you will get one of the
8452 following error messages (where @code{fff} is the name of the file you
8458 cannot generate code for file `@w{`}fff`@w{`} (package spec)
8459 to check package spec, use -gnatc
8461 cannot generate code for file `@w{`}fff`@w{`} (missing subunits)
8462 to check parent unit, use -gnatc
8464 cannot generate code for file `@w{`}fff`@w{`} (subprogram spec)
8465 to check subprogram spec, use -gnatc
8467 cannot generate code for file `@w{`}fff`@w{`} (subunit)
8468 to check subunit, use -gnatc
8472 As indicated by the above error messages, if you want to submit
8473 one of these files to the compiler to check for correct semantics
8474 without generating code, then use the @code{-gnatc} switch.
8476 The basic command for compiling a file containing an Ada unit is:
8479 $ gcc -c [switches] <file name>
8482 where @code{file name} is the name of the Ada file (usually
8483 having an extension @code{.ads} for a spec or @code{.adb} for a body).
8485 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
8486 The result of a successful compilation is an object file, which has the
8487 same name as the source file but an extension of @code{.o} and an Ada
8488 Library Information (ALI) file, which also has the same name as the
8489 source file, but with @code{.ali} as the extension. GNAT creates these
8490 two output files in the current directory, but you may specify a source
8491 file in any directory using an absolute or relative path specification
8492 containing the directory information.
8494 TESTING: the @code{--foobar@emph{NN}} switch
8498 @code{gcc} is actually a driver program that looks at the extensions of
8499 the file arguments and loads the appropriate compiler. For example, the
8500 GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8501 These programs are in directories known to the driver program (in some
8502 configurations via environment variables you set), but need not be in
8503 your path. The @code{gcc} driver also calls the assembler and any other
8504 utilities needed to complete the generation of the required object
8507 It is possible to supply several file names on the same @code{gcc}
8508 command. This causes @code{gcc} to call the appropriate compiler for
8509 each file. For example, the following command lists two separate
8510 files to be compiled:
8513 $ gcc -c x.adb y.adb
8516 calls @code{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8518 The compiler generates two object files @code{x.o} and @code{y.o}
8519 and the two ALI files @code{x.ali} and @code{y.ali}.
8521 Any switches apply to all the files listed, see @ref{ea,,Compiler Switches} for a
8522 list of available @code{gcc} switches.
8524 @node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8525 @anchor{gnat_ugn/building_executable_programs_with_gnat id10}@anchor{eb}@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-and-the-run-time-library-rtl}@anchor{89}
8526 @subsection Search Paths and the Run-Time Library (RTL)
8529 With the GNAT source-based library system, the compiler must be able to
8530 find source files for units that are needed by the unit being compiled.
8531 Search paths are used to guide this process.
8533 The compiler compiles one source file whose name must be given
8534 explicitly on the command line. In other words, no searching is done
8535 for this file. To find all other source files that are needed (the most
8536 common being the specs of units), the compiler examines the following
8537 directories, in the following order:
8543 The directory containing the source file of the main unit being compiled
8544 (the file name on the command line).
8547 Each directory named by an @code{-I} switch given on the @code{gcc}
8548 command line, in the order given.
8550 @geindex ADA_PRJ_INCLUDE_FILE
8553 Each of the directories listed in the text file whose name is given
8555 @geindex ADA_PRJ_INCLUDE_FILE
8556 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8557 @code{ADA_PRJ_INCLUDE_FILE} environment variable.
8558 @geindex ADA_PRJ_INCLUDE_FILE
8559 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8560 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8561 driver when project files are used. It should not normally be set
8564 @geindex ADA_INCLUDE_PATH
8567 Each of the directories listed in the value of the
8568 @geindex ADA_INCLUDE_PATH
8569 @geindex environment variable; ADA_INCLUDE_PATH
8570 @code{ADA_INCLUDE_PATH} environment variable.
8571 Construct this value
8574 @geindex environment variable; PATH
8575 @code{PATH} environment variable: a list of directory
8576 names separated by colons (semicolons when working with the NT version).
8579 The content of the @code{ada_source_path} file which is part of the GNAT
8580 installation tree and is used to store standard libraries such as the
8581 GNAT Run Time Library (RTL) source files.
8582 @ref{87,,Installing a library}
8585 Specifying the switch @code{-I-}
8586 inhibits the use of the directory
8587 containing the source file named in the command line. You can still
8588 have this directory on your search path, but in this case it must be
8589 explicitly requested with a @code{-I} switch.
8591 Specifying the switch @code{-nostdinc}
8592 inhibits the search of the default location for the GNAT Run Time
8593 Library (RTL) source files.
8595 The compiler outputs its object files and ALI files in the current
8597 Caution: The object file can be redirected with the @code{-o} switch;
8598 however, @code{gcc} and @code{gnat1} have not been coordinated on this
8599 so the @code{ALI} file will not go to the right place. Therefore, you should
8600 avoid using the @code{-o} switch.
8604 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8605 children make up the GNAT RTL, together with the simple @code{System.IO}
8606 package used in the @code{"Hello World"} example. The sources for these units
8607 are needed by the compiler and are kept together in one directory. Not
8608 all of the bodies are needed, but all of the sources are kept together
8609 anyway. In a normal installation, you need not specify these directory
8610 names when compiling or binding. Either the environment variables or
8611 the built-in defaults cause these files to be found.
8613 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8614 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8615 consisting of child units of @code{GNAT}. This is a collection of generally
8616 useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8617 for further details.
8619 Besides simplifying access to the RTL, a major use of search paths is
8620 in compiling sources from multiple directories. This can make
8621 development environments much more flexible.
8623 @node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8624 @anchor{gnat_ugn/building_executable_programs_with_gnat id11}@anchor{ec}@anchor{gnat_ugn/building_executable_programs_with_gnat order-of-compilation-issues}@anchor{ed}
8625 @subsection Order of Compilation Issues
8628 If, in our earlier example, there was a spec for the @code{hello}
8629 procedure, it would be contained in the file @code{hello.ads}; yet this
8630 file would not have to be explicitly compiled. This is the result of the
8631 model we chose to implement library management. Some of the consequences
8632 of this model are as follows:
8638 There is no point in compiling specs (except for package
8639 specs with no bodies) because these are compiled as needed by clients. If
8640 you attempt a useless compilation, you will receive an error message.
8641 It is also useless to compile subunits because they are compiled as needed
8645 There are no order of compilation requirements: performing a
8646 compilation never obsoletes anything. The only way you can obsolete
8647 something and require recompilations is to modify one of the
8648 source files on which it depends.
8651 There is no library as such, apart from the ALI files
8652 (@ref{42,,The Ada Library Information Files}, for information on the format
8653 of these files). For now we find it convenient to create separate ALI files,
8654 but eventually the information therein may be incorporated into the object
8658 When you compile a unit, the source files for the specs of all units
8659 that it @emph{with}s, all its subunits, and the bodies of any generics it
8660 instantiates must be available (reachable by the search-paths mechanism
8661 described above), or you will receive a fatal error message.
8664 @node Examples,,Order of Compilation Issues,Compiling with gcc
8665 @anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{ee}@anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{ef}
8666 @subsection Examples
8669 The following are some typical Ada compilation command line examples:
8675 Compile body in file @code{xyz.adb} with all default options.
8678 $ gcc -c -O2 -gnata xyz-def.adb
8681 Compile the child unit package in file @code{xyz-def.adb} with extensive
8682 optimizations, and pragma @code{Assert}/@cite{Debug} statements
8686 $ gcc -c -gnatc abc-def.adb
8689 Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8692 @node Compiler Switches,Linker Switches,Compiling with gcc,Building Executable Programs with GNAT
8693 @anchor{gnat_ugn/building_executable_programs_with_gnat compiler-switches}@anchor{f0}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gcc}@anchor{ea}
8694 @section Compiler Switches
8697 The @code{gcc} command accepts switches that control the
8698 compilation process. These switches are fully described in this section:
8699 first an alphabetical listing of all switches with a brief description,
8700 and then functionally grouped sets of switches with more detailed
8703 More switches exist for GCC than those documented here, especially
8704 for specific targets. However, their use is not recommended as
8705 they may change code generation in ways that are incompatible with
8706 the Ada run-time library, or can cause inconsistencies between
8710 * Alphabetical List of All Switches::
8711 * Output and Error Message Control::
8712 * Warning Message Control::
8713 * Debugging and Assertion Control::
8714 * Validity Checking::
8717 * Using gcc for Syntax Checking::
8718 * Using gcc for Semantic Checking::
8719 * Compiling Different Versions of Ada::
8720 * Character Set Control::
8721 * File Naming Control::
8722 * Subprogram Inlining Control::
8723 * Auxiliary Output Control::
8724 * Debugging Control::
8725 * Exception Handling Control::
8726 * Units to Sources Mapping Files::
8727 * Code Generation Control::
8731 @node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8732 @anchor{gnat_ugn/building_executable_programs_with_gnat id13}@anchor{f1}@anchor{gnat_ugn/building_executable_programs_with_gnat alphabetical-list-of-all-switches}@anchor{f2}
8733 @subsection Alphabetical List of All Switches
8741 @item @code{-b @emph{target}}
8743 Compile your program to run on @code{target}, which is the name of a
8744 system configuration. You must have a GNAT cross-compiler built if
8745 @code{target} is not the same as your host system.
8753 @item @code{-B@emph{dir}}
8755 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8756 from @code{dir} instead of the default location. Only use this switch
8757 when multiple versions of the GNAT compiler are available.
8758 See the "Options for Directory Search" section in the
8759 @cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8760 You would normally use the @code{-b} or @code{-V} switch instead.
8770 Compile. Always use this switch when compiling Ada programs.
8772 Note: for some other languages when using @code{gcc}, notably in
8773 the case of C and C++, it is possible to use
8774 use @code{gcc} without a @code{-c} switch to
8775 compile and link in one step. In the case of GNAT, you
8776 cannot use this approach, because the binder must be run
8777 and @code{gcc} cannot be used to run the GNAT binder.
8780 @geindex -fcallgraph-info (gcc)
8785 @item @code{-fcallgraph-info[=su,da]}
8787 Makes the compiler output callgraph information for the program, on a
8788 per-file basis. The information is generated in the VCG format. It can
8789 be decorated with additional, per-node and/or per-edge information, if a
8790 list of comma-separated markers is additionally specified. When the
8791 @code{su} marker is specified, the callgraph is decorated with stack usage
8792 information; it is equivalent to @code{-fstack-usage}. When the @code{da}
8793 marker is specified, the callgraph is decorated with information about
8794 dynamically allocated objects.
8797 @geindex -fdump-scos (gcc)
8802 @item @code{-fdump-scos}
8804 Generates SCO (Source Coverage Obligation) information in the ALI file.
8805 This information is used by advanced coverage tools. See unit @code{SCOs}
8806 in the compiler sources for details in files @code{scos.ads} and
8810 @geindex -fdump-xref (gcc)
8815 @item @code{-fdump-xref}
8817 Generates cross reference information in GLI files for C and C++ sources.
8818 The GLI files have the same syntax as the ALI files for Ada, and can be used
8819 for source navigation in IDEs and on the command line using e.g. gnatxref
8820 and the @code{--ext=gli} switch.
8823 @geindex -flto (gcc)
8828 @item @code{-flto[=@emph{n}]}
8830 Enables Link Time Optimization. This switch must be used in conjunction
8831 with the traditional @code{-Ox} switches and instructs the compiler to
8832 defer most optimizations until the link stage. The advantage of this
8833 approach is that the compiler can do a whole-program analysis and choose
8834 the best interprocedural optimization strategy based on a complete view
8835 of the program, instead of a fragmentary view with the usual approach.
8836 This can also speed up the compilation of big programs and reduce the
8837 size of the executable, compared with a traditional per-unit compilation
8838 with inlining across modules enabled by the @code{-gnatn} switch.
8839 The drawback of this approach is that it may require more memory and that
8840 the debugging information generated by -g with it might be hardly usable.
8841 The switch, as well as the accompanying @code{-Ox} switches, must be
8842 specified both for the compilation and the link phases.
8843 If the @code{n} parameter is specified, the optimization and final code
8844 generation at link time are executed using @code{n} parallel jobs by
8845 means of an installed @code{make} program.
8848 @geindex -fno-inline (gcc)
8853 @item @code{-fno-inline}
8855 Suppresses all inlining, unless requested with pragma @code{Inline_Always}. The
8856 effect is enforced regardless of other optimization or inlining switches.
8857 Note that inlining can also be suppressed on a finer-grained basis with
8858 pragma @code{No_Inline}.
8861 @geindex -fno-inline-functions (gcc)
8866 @item @code{-fno-inline-functions}
8868 Suppresses automatic inlining of subprograms, which is enabled
8869 if @code{-O3} is used.
8872 @geindex -fno-inline-small-functions (gcc)
8877 @item @code{-fno-inline-small-functions}
8879 Suppresses automatic inlining of small subprograms, which is enabled
8880 if @code{-O2} is used.
8883 @geindex -fno-inline-functions-called-once (gcc)
8888 @item @code{-fno-inline-functions-called-once}
8890 Suppresses inlining of subprograms local to the unit and called once
8891 from within it, which is enabled if @code{-O1} is used.
8894 @geindex -fno-ivopts (gcc)
8899 @item @code{-fno-ivopts}
8901 Suppresses high-level loop induction variable optimizations, which are
8902 enabled if @code{-O1} is used. These optimizations are generally
8903 profitable but, for some specific cases of loops with numerous uses
8904 of the iteration variable that follow a common pattern, they may end
8905 up destroying the regularity that could be exploited at a lower level
8906 and thus producing inferior code.
8909 @geindex -fno-strict-aliasing (gcc)
8914 @item @code{-fno-strict-aliasing}
8916 Causes the compiler to avoid assumptions regarding non-aliasing
8917 of objects of different types. See
8918 @ref{f3,,Optimization and Strict Aliasing} for details.
8921 @geindex -fno-strict-overflow (gcc)
8926 @item @code{-fno-strict-overflow}
8928 Causes the compiler to avoid assumptions regarding the rules of signed
8929 integer overflow. These rules specify that signed integer overflow will
8930 result in a Constraint_Error exception at run time and are enforced in
8931 default mode by the compiler, so this switch should not be necessary in
8932 normal operating mode. It might be useful in conjunction with @code{-gnato0}
8933 for very peculiar cases of low-level programming.
8936 @geindex -fstack-check (gcc)
8941 @item @code{-fstack-check}
8943 Activates stack checking.
8944 See @ref{f4,,Stack Overflow Checking} for details.
8947 @geindex -fstack-usage (gcc)
8952 @item @code{-fstack-usage}
8954 Makes the compiler output stack usage information for the program, on a
8955 per-subprogram basis. See @ref{f5,,Static Stack Usage Analysis} for details.
8965 Generate debugging information. This information is stored in the object
8966 file and copied from there to the final executable file by the linker,
8967 where it can be read by the debugger. You must use the
8968 @code{-g} switch if you plan on using the debugger.
8971 @geindex -gnat05 (gcc)
8976 @item @code{-gnat05}
8978 Allow full Ada 2005 features.
8981 @geindex -gnat12 (gcc)
8986 @item @code{-gnat12}
8988 Allow full Ada 2012 features.
8991 @geindex -gnat83 (gcc)
8993 @geindex -gnat2005 (gcc)
8998 @item @code{-gnat2005}
9000 Allow full Ada 2005 features (same as @code{-gnat05})
9003 @geindex -gnat2012 (gcc)
9008 @item @code{-gnat2012}
9010 Allow full Ada 2012 features (same as @code{-gnat12})
9012 @item @code{-gnat83}
9014 Enforce Ada 83 restrictions.
9017 @geindex -gnat95 (gcc)
9022 @item @code{-gnat95}
9024 Enforce Ada 95 restrictions.
9026 Note: for compatibility with some Ada 95 compilers which support only
9027 the @code{overriding} keyword of Ada 2005, the @code{-gnatd.D} switch can
9028 be used along with @code{-gnat95} to achieve a similar effect with GNAT.
9030 @code{-gnatd.D} instructs GNAT to consider @code{overriding} as a keyword
9031 and handle its associated semantic checks, even in Ada 95 mode.
9034 @geindex -gnata (gcc)
9041 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
9042 activated. Note that these pragmas can also be controlled using the
9043 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
9044 It also activates pragmas @code{Check}, @code{Precondition}, and
9045 @code{Postcondition}. Note that these pragmas can also be controlled
9046 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
9047 also activates all assertions defined in the RM as aspects: preconditions,
9048 postconditions, type invariants and (sub)type predicates. In all Ada modes,
9049 corresponding pragmas for type invariants and (sub)type predicates are
9050 also activated. The default is that all these assertions are disabled,
9051 and have no effect, other than being checked for syntactic validity, and
9052 in the case of subtype predicates, constructions such as membership tests
9053 still test predicates even if assertions are turned off.
9056 @geindex -gnatA (gcc)
9063 Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
9067 @geindex -gnatb (gcc)
9074 Generate brief messages to @code{stderr} even if verbose mode set.
9077 @geindex -gnatB (gcc)
9084 Assume no invalid (bad) values except for 'Valid attribute use
9085 (@ref{f6,,Validity Checking}).
9088 @geindex -gnatc (gcc)
9095 Check syntax and semantics only (no code generation attempted). When the
9096 compiler is invoked by @code{gnatmake}, if the switch @code{-gnatc} is
9097 only given to the compiler (after @code{-cargs} or in package Compiler of
9098 the project file, @code{gnatmake} will fail because it will not find the
9099 object file after compilation. If @code{gnatmake} is called with
9100 @code{-gnatc} as a builder switch (before @code{-cargs} or in package
9101 Builder of the project file) then @code{gnatmake} will not fail because
9102 it will not look for the object files after compilation, and it will not try
9106 @geindex -gnatC (gcc)
9113 Generate CodePeer intermediate format (no code generation attempted).
9114 This switch will generate an intermediate representation suitable for
9115 use by CodePeer (@code{.scil} files). This switch is not compatible with
9116 code generation (it will, among other things, disable some switches such
9117 as -gnatn, and enable others such as -gnata).
9120 @geindex -gnatd (gcc)
9127 Specify debug options for the compiler. The string of characters after
9128 the @code{-gnatd} specify the specific debug options. The possible
9129 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
9130 compiler source file @code{debug.adb} for details of the implemented
9131 debug options. Certain debug options are relevant to applications
9132 programmers, and these are documented at appropriate points in this
9136 @geindex -gnatD[nn] (gcc)
9143 Create expanded source files for source level debugging. This switch
9144 also suppresses generation of cross-reference information
9145 (see @code{-gnatx}). Note that this switch is not allowed if a previous
9146 -gnatR switch has been given, since these two switches are not compatible.
9149 @geindex -gnateA (gcc)
9154 @item @code{-gnateA}
9156 Check that the actual parameters of a subprogram call are not aliases of one
9157 another. To qualify as aliasing, the actuals must denote objects of a composite
9158 type, their memory locations must be identical or overlapping, and at least one
9159 of the corresponding formal parameters must be of mode OUT or IN OUT.
9162 type Rec_Typ is record
9163 Data : Integer := 0;
9166 function Self (Val : Rec_Typ) return Rec_Typ is
9171 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
9174 end Detect_Aliasing;
9178 Detect_Aliasing (Obj, Obj);
9179 Detect_Aliasing (Obj, Self (Obj));
9182 In the example above, the first call to @code{Detect_Aliasing} fails with a
9183 @code{Program_Error} at runtime because the actuals for @code{Val_1} and
9184 @code{Val_2} denote the same object. The second call executes without raising
9185 an exception because @code{Self(Obj)} produces an anonymous object which does
9186 not share the memory location of @code{Obj}.
9189 @geindex -gnatec (gcc)
9194 @item @code{-gnatec=@emph{path}}
9196 Specify a configuration pragma file
9197 (the equal sign is optional)
9198 (@ref{79,,The Configuration Pragmas Files}).
9201 @geindex -gnateC (gcc)
9206 @item @code{-gnateC}
9208 Generate CodePeer messages in a compiler-like format. This switch is only
9209 effective if @code{-gnatcC} is also specified and requires an installation
9213 @geindex -gnated (gcc)
9218 @item @code{-gnated}
9220 Disable atomic synchronization
9223 @geindex -gnateD (gcc)
9228 @item @code{-gnateDsymbol[=@emph{value}]}
9230 Defines a symbol, associated with @code{value}, for preprocessing.
9231 (@ref{18,,Integrated Preprocessing}).
9234 @geindex -gnateE (gcc)
9239 @item @code{-gnateE}
9241 Generate extra information in exception messages. In particular, display
9242 extra column information and the value and range associated with index and
9243 range check failures, and extra column information for access checks.
9244 In cases where the compiler is able to determine at compile time that
9245 a check will fail, it gives a warning, and the extra information is not
9246 produced at run time.
9249 @geindex -gnatef (gcc)
9254 @item @code{-gnatef}
9256 Display full source path name in brief error messages.
9259 @geindex -gnateF (gcc)
9264 @item @code{-gnateF}
9266 Check for overflow on all floating-point operations, including those
9267 for unconstrained predefined types. See description of pragma
9268 @code{Check_Float_Overflow} in GNAT RM.
9271 @geindex -gnateg (gcc)
9278 The @code{-gnatc} switch must always be specified before this switch, e.g.
9279 @code{-gnatceg}. Generate a C header from the Ada input file. See
9280 @ref{ca,,Generating C Headers for Ada Specifications} for more
9284 @geindex -gnateG (gcc)
9289 @item @code{-gnateG}
9291 Save result of preprocessing in a text file.
9294 @geindex -gnatei (gcc)
9299 @item @code{-gnatei@emph{nnn}}
9301 Set maximum number of instantiations during compilation of a single unit to
9302 @code{nnn}. This may be useful in increasing the default maximum of 8000 for
9303 the rare case when a single unit legitimately exceeds this limit.
9306 @geindex -gnateI (gcc)
9311 @item @code{-gnateI@emph{nnn}}
9313 Indicates that the source is a multi-unit source and that the index of the
9314 unit to compile is @code{nnn}. @code{nnn} needs to be a positive number and need
9315 to be a valid index in the multi-unit source.
9318 @geindex -gnatel (gcc)
9323 @item @code{-gnatel}
9325 This switch can be used with the static elaboration model to issue info
9327 where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
9328 are generated. This is useful in diagnosing elaboration circularities
9329 caused by these implicit pragmas when using the static elaboration
9330 model. See See the section in this guide on elaboration checking for
9331 further details. These messages are not generated by default, and are
9332 intended only for temporary use when debugging circularity problems.
9335 @geindex -gnatel (gcc)
9340 @item @code{-gnateL}
9342 This switch turns off the info messages about implicit elaboration pragmas.
9345 @geindex -gnatem (gcc)
9350 @item @code{-gnatem=@emph{path}}
9352 Specify a mapping file
9353 (the equal sign is optional)
9354 (@ref{f7,,Units to Sources Mapping Files}).
9357 @geindex -gnatep (gcc)
9362 @item @code{-gnatep=@emph{file}}
9364 Specify a preprocessing data file
9365 (the equal sign is optional)
9366 (@ref{18,,Integrated Preprocessing}).
9369 @geindex -gnateP (gcc)
9374 @item @code{-gnateP}
9376 Turn categorization dependency errors into warnings.
9377 Ada requires that units that WITH one another have compatible categories, for
9378 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9379 these errors become warnings (which can be ignored, or suppressed in the usual
9380 manner). This can be useful in some specialized circumstances such as the
9381 temporary use of special test software.
9384 @geindex -gnateS (gcc)
9389 @item @code{-gnateS}
9391 Synonym of @code{-fdump-scos}, kept for backwards compatibility.
9394 @geindex -gnatet=file (gcc)
9399 @item @code{-gnatet=@emph{path}}
9401 Generate target dependent information. The format of the output file is
9402 described in the section about switch @code{-gnateT}.
9405 @geindex -gnateT (gcc)
9410 @item @code{-gnateT=@emph{path}}
9412 Read target dependent information, such as endianness or sizes and alignments
9413 of base type. If this switch is passed, the default target dependent
9414 information of the compiler is replaced by the one read from the input file.
9415 This is used by tools other than the compiler, e.g. to do
9416 semantic analysis of programs that will run on some other target than
9417 the machine on which the tool is run.
9419 The following target dependent values should be defined,
9420 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
9421 positive integer value, and fields marked with a question mark are
9422 boolean fields, where a value of 0 is False, and a value of 1 is True:
9425 Bits_BE : Nat; -- Bits stored big-endian?
9426 Bits_Per_Unit : Pos; -- Bits in a storage unit
9427 Bits_Per_Word : Pos; -- Bits in a word
9428 Bytes_BE : Nat; -- Bytes stored big-endian?
9429 Char_Size : Pos; -- Standard.Character'Size
9430 Double_Float_Alignment : Nat; -- Alignment of double float
9431 Double_Scalar_Alignment : Nat; -- Alignment of double length scalar
9432 Double_Size : Pos; -- Standard.Long_Float'Size
9433 Float_Size : Pos; -- Standard.Float'Size
9434 Float_Words_BE : Nat; -- Float words stored big-endian?
9435 Int_Size : Pos; -- Standard.Integer'Size
9436 Long_Double_Size : Pos; -- Standard.Long_Long_Float'Size
9437 Long_Long_Size : Pos; -- Standard.Long_Long_Integer'Size
9438 Long_Size : Pos; -- Standard.Long_Integer'Size
9439 Maximum_Alignment : Pos; -- Maximum permitted alignment
9440 Max_Unaligned_Field : Pos; -- Maximum size for unaligned bit field
9441 Pointer_Size : Pos; -- System.Address'Size
9442 Short_Enums : Nat; -- Short foreign convention enums?
9443 Short_Size : Pos; -- Standard.Short_Integer'Size
9444 Strict_Alignment : Nat; -- Strict alignment?
9445 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9446 Wchar_T_Size : Pos; -- Interfaces.C.wchar_t'Size
9447 Words_BE : Nat; -- Words stored big-endian?
9450 The format of the input file is as follows. First come the values of
9451 the variables defined above, with one line per value:
9457 where @code{name} is the name of the parameter, spelled out in full,
9458 and cased as in the above list, and @code{value} is an unsigned decimal
9459 integer. Two or more blanks separates the name from the value.
9461 All the variables must be present, in alphabetical order (i.e. the
9462 same order as the list above).
9464 Then there is a blank line to separate the two parts of the file. Then
9465 come the lines showing the floating-point types to be registered, with
9466 one line per registered mode:
9469 name digs float_rep size alignment
9472 where @code{name} is the string name of the type (which can have
9473 single spaces embedded in the name (e.g. long double), @code{digs} is
9474 the number of digits for the floating-point type, @code{float_rep} is
9475 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
9476 AAMP), @code{size} is the size in bits, @code{alignment} is the
9477 alignment in bits. The name is followed by at least two blanks, fields
9478 are separated by at least one blank, and a LF character immediately
9479 follows the alignment field.
9481 Here is an example of a target parameterization file:
9489 Double_Float_Alignment 0
9490 Double_Scalar_Alignment 0
9495 Long_Double_Size 128
9498 Maximum_Alignment 16
9499 Max_Unaligned_Field 64
9503 System_Allocator_Alignment 16
9509 long double 18 I 80 128
9514 @geindex -gnateu (gcc)
9519 @item @code{-gnateu}
9521 Ignore unrecognized validity, warning, and style switches that
9522 appear after this switch is given. This may be useful when
9523 compiling sources developed on a later version of the compiler
9524 with an earlier version. Of course the earlier version must
9525 support this switch.
9528 @geindex -gnateV (gcc)
9533 @item @code{-gnateV}
9535 Check that all actual parameters of a subprogram call are valid according to
9536 the rules of validity checking (@ref{f6,,Validity Checking}).
9539 @geindex -gnateY (gcc)
9544 @item @code{-gnateY}
9546 Ignore all STYLE_CHECKS pragmas. Full legality checks
9547 are still carried out, but the pragmas have no effect
9548 on what style checks are active. This allows all style
9549 checking options to be controlled from the command line.
9552 @geindex -gnatE (gcc)
9559 Full dynamic elaboration checks.
9562 @geindex -gnatf (gcc)
9569 Full errors. Multiple errors per line, all undefined references, do not
9570 attempt to suppress cascaded errors.
9573 @geindex -gnatF (gcc)
9580 Externals names are folded to all uppercase.
9583 @geindex -gnatg (gcc)
9590 Internal GNAT implementation mode. This should not be used for
9591 applications programs, it is intended only for use by the compiler
9592 and its run-time library. For documentation, see the GNAT sources.
9593 Note that @code{-gnatg} implies
9594 @code{-gnatw.ge} and
9596 so that all standard warnings and all standard style options are turned on.
9597 All warnings and style messages are treated as errors.
9600 @geindex -gnatG[nn] (gcc)
9605 @item @code{-gnatG=nn}
9607 List generated expanded code in source form.
9610 @geindex -gnath (gcc)
9617 Output usage information. The output is written to @code{stdout}.
9620 @geindex -gnati (gcc)
9625 @item @code{-gnati@emph{c}}
9627 Identifier character set (@code{c} = 1/2/3/4/8/9/p/f/n/w).
9628 For details of the possible selections for @code{c},
9629 see @ref{48,,Character Set Control}.
9632 @geindex -gnatI (gcc)
9639 Ignore representation clauses. When this switch is used,
9640 representation clauses are treated as comments. This is useful
9641 when initially porting code where you want to ignore rep clause
9642 problems, and also for compiling foreign code (particularly
9643 for use with ASIS). The representation clauses that are ignored
9644 are: enumeration_representation_clause, record_representation_clause,
9645 and attribute_definition_clause for the following attributes:
9646 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9647 Object_Size, Scalar_Storage_Order, Size, Small, Stream_Size,
9648 and Value_Size. Pragma Default_Scalar_Storage_Order is also ignored.
9649 Note that this option should be used only for compiling -- the
9650 code is likely to malfunction at run time.
9652 Note that when @code{-gnatct} is used to generate trees for input
9653 into ASIS tools, these representation clauses are removed
9654 from the tree and ignored. This means that the tool will not see them.
9657 @geindex -gnatjnn (gcc)
9662 @item @code{-gnatj@emph{nn}}
9664 Reformat error messages to fit on @code{nn} character lines
9667 @geindex -gnatk (gcc)
9672 @item @code{-gnatk=@emph{n}}
9674 Limit file names to @code{n} (1-999) characters (@code{k} = krunch).
9677 @geindex -gnatl (gcc)
9684 Output full source listing with embedded error messages.
9687 @geindex -gnatL (gcc)
9694 Used in conjunction with -gnatG or -gnatD to intersperse original
9695 source lines (as comment lines with line numbers) in the expanded
9699 @geindex -gnatm (gcc)
9704 @item @code{-gnatm=@emph{n}}
9706 Limit number of detected error or warning messages to @code{n}
9707 where @code{n} is in the range 1..999999. The default setting if
9708 no switch is given is 9999. If the number of warnings reaches this
9709 limit, then a message is output and further warnings are suppressed,
9710 but the compilation is continued. If the number of error messages
9711 reaches this limit, then a message is output and the compilation
9712 is abandoned. The equal sign here is optional. A value of zero
9713 means that no limit applies.
9716 @geindex -gnatn (gcc)
9721 @item @code{-gnatn[12]}
9723 Activate inlining across modules for subprograms for which pragma @code{Inline}
9724 is specified. This inlining is performed by the GCC back-end. An optional
9725 digit sets the inlining level: 1 for moderate inlining across modules
9726 or 2 for full inlining across modules. If no inlining level is specified,
9727 the compiler will pick it based on the optimization level.
9730 @geindex -gnatN (gcc)
9737 Activate front end inlining for subprograms for which
9738 pragma @code{Inline} is specified. This inlining is performed
9739 by the front end and will be visible in the
9740 @code{-gnatG} output.
9742 When using a gcc-based back end (in practice this means using any version
9743 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
9744 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
9745 Historically front end inlining was more extensive than the gcc back end
9746 inlining, but that is no longer the case.
9749 @geindex -gnato0 (gcc)
9754 @item @code{-gnato0}
9756 Suppresses overflow checking. This causes the behavior of the compiler to
9757 match the default for older versions where overflow checking was suppressed
9758 by default. This is equivalent to having
9759 @code{pragma Suppress (Overflow_Check)} in a configuration pragma file.
9762 @geindex -gnato?? (gcc)
9767 @item @code{-gnato??}
9769 Set default mode for handling generation of code to avoid intermediate
9770 arithmetic overflow. Here @code{??} is two digits, a
9771 single digit, or nothing. Each digit is one of the digits @code{1}
9775 @multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
9790 All intermediate overflows checked against base type (@code{STRICT})
9798 Minimize intermediate overflows (@code{MINIMIZED})
9806 Eliminate intermediate overflows (@code{ELIMINATED})
9811 If only one digit appears, then it applies to all
9812 cases; if two digits are given, then the first applies outside
9813 assertions, pre/postconditions, and type invariants, and the second
9814 applies within assertions, pre/postconditions, and type invariants.
9816 If no digits follow the @code{-gnato}, then it is equivalent to
9818 causing all intermediate overflows to be handled in strict
9821 This switch also causes arithmetic overflow checking to be performed
9822 (as though @code{pragma Unsuppress (Overflow_Check)} had been specified).
9824 The default if no option @code{-gnato} is given is that overflow handling
9825 is in @code{STRICT} mode (computations done using the base type), and that
9826 overflow checking is enabled.
9828 Note that division by zero is a separate check that is not
9829 controlled by this switch (divide-by-zero checking is on by default).
9831 See also @ref{f8,,Specifying the Desired Mode}.
9834 @geindex -gnatp (gcc)
9841 Suppress all checks. See @ref{f9,,Run-Time Checks} for details. This switch
9842 has no effect if cancelled by a subsequent @code{-gnat-p} switch.
9845 @geindex -gnat-p (gcc)
9850 @item @code{-gnat-p}
9852 Cancel effect of previous @code{-gnatp} switch.
9855 @geindex -gnatP (gcc)
9862 Enable polling. This is required on some systems (notably Windows NT) to
9863 obtain asynchronous abort and asynchronous transfer of control capability.
9864 See @code{Pragma_Polling} in the @cite{GNAT_Reference_Manual} for full
9868 @geindex -gnatq (gcc)
9875 Don't quit. Try semantics, even if parse errors.
9878 @geindex -gnatQ (gcc)
9885 Don't quit. Generate @code{ALI} and tree files even if illegalities.
9886 Note that code generation is still suppressed in the presence of any
9887 errors, so even with @code{-gnatQ} no object file is generated.
9890 @geindex -gnatr (gcc)
9897 Treat pragma Restrictions as Restriction_Warnings.
9900 @geindex -gnatR (gcc)
9905 @item @code{-gnatR[0/1/2/3][e][m][s]}
9907 Output representation information for declared types, objects and
9908 subprograms. Note that this switch is not allowed if a previous
9909 @code{-gnatD} switch has been given, since these two switches
9913 @geindex -gnats (gcc)
9923 @geindex -gnatS (gcc)
9930 Print package Standard.
9933 @geindex -gnatt (gcc)
9940 Generate tree output file.
9943 @geindex -gnatT (gcc)
9948 @item @code{-gnatT@emph{nnn}}
9950 All compiler tables start at @code{nnn} times usual starting size.
9953 @geindex -gnatu (gcc)
9960 List units for this compilation.
9963 @geindex -gnatU (gcc)
9970 Tag all error messages with the unique string 'error:'
9973 @geindex -gnatv (gcc)
9980 Verbose mode. Full error output with source lines to @code{stdout}.
9983 @geindex -gnatV (gcc)
9990 Control level of validity checking (@ref{f6,,Validity Checking}).
9993 @geindex -gnatw (gcc)
9998 @item @code{-gnatw@emph{xxx}}
10001 @code{xxx} is a string of option letters that denotes
10002 the exact warnings that
10003 are enabled or disabled (@ref{fa,,Warning Message Control}).
10006 @geindex -gnatW (gcc)
10011 @item @code{-gnatW@emph{e}}
10013 Wide character encoding method
10014 (@code{e}=n/h/u/s/e/8).
10017 @geindex -gnatx (gcc)
10022 @item @code{-gnatx}
10024 Suppress generation of cross-reference information.
10027 @geindex -gnatX (gcc)
10032 @item @code{-gnatX}
10034 Enable GNAT implementation extensions and latest Ada version.
10037 @geindex -gnaty (gcc)
10042 @item @code{-gnaty}
10044 Enable built-in style checks (@ref{fb,,Style Checking}).
10047 @geindex -gnatz (gcc)
10052 @item @code{-gnatz@emph{m}}
10054 Distribution stub generation and compilation
10055 (@code{m}=r/c for receiver/caller stubs).
10063 @item @code{-I@emph{dir}}
10067 Direct GNAT to search the @code{dir} directory for source files needed by
10068 the current compilation
10069 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
10081 Except for the source file named in the command line, do not look for source
10082 files in the directory containing the source file named in the command line
10083 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
10091 @item @code{-o @emph{file}}
10093 This switch is used in @code{gcc} to redirect the generated object file
10094 and its associated ALI file. Beware of this switch with GNAT, because it may
10095 cause the object file and ALI file to have different names which in turn
10096 may confuse the binder and the linker.
10099 @geindex -nostdinc (gcc)
10104 @item @code{-nostdinc}
10106 Inhibit the search of the default location for the GNAT Run Time
10107 Library (RTL) source files.
10110 @geindex -nostdlib (gcc)
10115 @item @code{-nostdlib}
10117 Inhibit the search of the default location for the GNAT Run Time
10118 Library (RTL) ALI files.
10126 @item @code{-O[@emph{n}]}
10128 @code{n} controls the optimization level:
10131 @multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
10146 No optimization, the default setting if no @code{-O} appears
10154 Normal optimization, the default if you specify @code{-O} without an
10155 operand. A good compromise between code quality and compilation
10164 Extensive optimization, may improve execution time, possibly at
10165 the cost of substantially increased compilation time.
10173 Same as @code{-O2}, and also includes inline expansion for small
10174 subprograms in the same unit.
10182 Optimize space usage
10187 See also @ref{fc,,Optimization Levels}.
10190 @geindex -pass-exit-codes (gcc)
10195 @item @code{-pass-exit-codes}
10197 Catch exit codes from the compiler and use the most meaningful as
10201 @geindex --RTS (gcc)
10206 @item @code{--RTS=@emph{rts-path}}
10208 Specifies the default location of the runtime library. Same meaning as the
10209 equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
10219 Used in place of @code{-c} to
10220 cause the assembler source file to be
10221 generated, using @code{.s} as the extension,
10222 instead of the object file.
10223 This may be useful if you need to examine the generated assembly code.
10226 @geindex -fverbose-asm (gcc)
10231 @item @code{-fverbose-asm}
10233 Used in conjunction with @code{-S}
10234 to cause the generated assembly code file to be annotated with variable
10235 names, making it significantly easier to follow.
10245 Show commands generated by the @code{gcc} driver. Normally used only for
10246 debugging purposes or if you need to be sure what version of the
10247 compiler you are executing.
10255 @item @code{-V @emph{ver}}
10257 Execute @code{ver} version of the compiler. This is the @code{gcc}
10258 version, not the GNAT version.
10268 Turn off warnings generated by the back end of the compiler. Use of
10269 this switch also causes the default for front end warnings to be set
10270 to suppress (as though @code{-gnatws} had appeared at the start of
10274 @geindex Combining GNAT switches
10276 You may combine a sequence of GNAT switches into a single switch. For
10277 example, the combined switch
10286 is equivalent to specifying the following sequence of switches:
10291 -gnato -gnatf -gnati3
10295 The following restrictions apply to the combination of switches
10302 The switch @code{-gnatc} if combined with other switches must come
10303 first in the string.
10306 The switch @code{-gnats} if combined with other switches must come
10307 first in the string.
10311 @code{-gnatzc} and @code{-gnatzr} may not be combined with any other
10312 switches, and only one of them may appear in the command line.
10315 The switch @code{-gnat-p} may not be combined with any other switch.
10318 Once a 'y' appears in the string (that is a use of the @code{-gnaty}
10319 switch), then all further characters in the switch are interpreted
10320 as style modifiers (see description of @code{-gnaty}).
10323 Once a 'd' appears in the string (that is a use of the @code{-gnatd}
10324 switch), then all further characters in the switch are interpreted
10325 as debug flags (see description of @code{-gnatd}).
10328 Once a 'w' appears in the string (that is a use of the @code{-gnatw}
10329 switch), then all further characters in the switch are interpreted
10330 as warning mode modifiers (see description of @code{-gnatw}).
10333 Once a 'V' appears in the string (that is a use of the @code{-gnatV}
10334 switch), then all further characters in the switch are interpreted
10335 as validity checking options (@ref{f6,,Validity Checking}).
10338 Option 'em', 'ec', 'ep', 'l=' and 'R' must be the last options in
10339 a combined list of options.
10342 @node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10343 @anchor{gnat_ugn/building_executable_programs_with_gnat id14}@anchor{fd}@anchor{gnat_ugn/building_executable_programs_with_gnat output-and-error-message-control}@anchor{fe}
10344 @subsection Output and Error Message Control
10349 The standard default format for error messages is called 'brief format'.
10350 Brief format messages are written to @code{stderr} (the standard error
10351 file) and have the following form:
10354 e.adb:3:04: Incorrect spelling of keyword "function"
10355 e.adb:4:20: ";" should be "is"
10358 The first integer after the file name is the line number in the file,
10359 and the second integer is the column number within the line.
10360 @code{GPS} can parse the error messages
10361 and point to the referenced character.
10362 The following switches provide control over the error message
10365 @geindex -gnatv (gcc)
10370 @item @code{-gnatv}
10372 The @code{v} stands for verbose.
10373 The effect of this setting is to write long-format error
10374 messages to @code{stdout} (the standard output file.
10375 The same program compiled with the
10376 @code{-gnatv} switch would generate:
10379 3. funcion X (Q : Integer)
10381 >>> Incorrect spelling of keyword "function"
10384 >>> ";" should be "is"
10387 The vertical bar indicates the location of the error, and the @code{>>>}
10388 prefix can be used to search for error messages. When this switch is
10389 used the only source lines output are those with errors.
10392 @geindex -gnatl (gcc)
10397 @item @code{-gnatl}
10399 The @code{l} stands for list.
10400 This switch causes a full listing of
10401 the file to be generated. In the case where a body is
10402 compiled, the corresponding spec is also listed, along
10403 with any subunits. Typical output from compiling a package
10404 body @code{p.adb} might look like:
10409 1. package body p is
10411 3. procedure a is separate;
10422 2. pragma Elaborate_Body
10443 When you specify the @code{-gnatv} or @code{-gnatl} switches and
10444 standard output is redirected, a brief summary is written to
10445 @code{stderr} (standard error) giving the number of error messages and
10446 warning messages generated.
10449 @geindex -gnatl=fname (gcc)
10454 @item @code{-gnatl=@emph{fname}}
10456 This has the same effect as @code{-gnatl} except that the output is
10457 written to a file instead of to standard output. If the given name
10458 @code{fname} does not start with a period, then it is the full name
10459 of the file to be written. If @code{fname} is an extension, it is
10460 appended to the name of the file being compiled. For example, if
10461 file @code{xyz.adb} is compiled with @code{-gnatl=.lst},
10462 then the output is written to file xyz.adb.lst.
10465 @geindex -gnatU (gcc)
10470 @item @code{-gnatU}
10472 This switch forces all error messages to be preceded by the unique
10473 string 'error:'. This means that error messages take a few more
10474 characters in space, but allows easy searching for and identification
10478 @geindex -gnatb (gcc)
10483 @item @code{-gnatb}
10485 The @code{b} stands for brief.
10486 This switch causes GNAT to generate the
10487 brief format error messages to @code{stderr} (the standard error
10488 file) as well as the verbose
10489 format message or full listing (which as usual is written to
10490 @code{stdout} (the standard output file).
10493 @geindex -gnatm (gcc)
10498 @item @code{-gnatm=@emph{n}}
10500 The @code{m} stands for maximum.
10501 @code{n} is a decimal integer in the
10502 range of 1 to 999999 and limits the number of error or warning
10503 messages to be generated. For example, using
10504 @code{-gnatm2} might yield
10507 e.adb:3:04: Incorrect spelling of keyword "function"
10508 e.adb:5:35: missing ".."
10509 fatal error: maximum number of errors detected
10510 compilation abandoned
10513 The default setting if
10514 no switch is given is 9999. If the number of warnings reaches this
10515 limit, then a message is output and further warnings are suppressed,
10516 but the compilation is continued. If the number of error messages
10517 reaches this limit, then a message is output and the compilation
10518 is abandoned. A value of zero means that no limit applies.
10520 Note that the equal sign is optional, so the switches
10521 @code{-gnatm2} and @code{-gnatm=2} are equivalent.
10524 @geindex -gnatf (gcc)
10529 @item @code{-gnatf}
10531 @geindex Error messages
10532 @geindex suppressing
10534 The @code{f} stands for full.
10535 Normally, the compiler suppresses error messages that are likely to be
10536 redundant. This switch causes all error
10537 messages to be generated. In particular, in the case of
10538 references to undefined variables. If a given variable is referenced
10539 several times, the normal format of messages is
10542 e.adb:7:07: "V" is undefined (more references follow)
10545 where the parenthetical comment warns that there are additional
10546 references to the variable @code{V}. Compiling the same program with the
10547 @code{-gnatf} switch yields
10550 e.adb:7:07: "V" is undefined
10551 e.adb:8:07: "V" is undefined
10552 e.adb:8:12: "V" is undefined
10553 e.adb:8:16: "V" is undefined
10554 e.adb:9:07: "V" is undefined
10555 e.adb:9:12: "V" is undefined
10558 The @code{-gnatf} switch also generates additional information for
10559 some error messages. Some examples are:
10565 Details on possibly non-portable unchecked conversion
10568 List possible interpretations for ambiguous calls
10571 Additional details on incorrect parameters
10575 @geindex -gnatjnn (gcc)
10580 @item @code{-gnatjnn}
10582 In normal operation mode (or if @code{-gnatj0} is used), then error messages
10583 with continuation lines are treated as though the continuation lines were
10584 separate messages (and so a warning with two continuation lines counts as
10585 three warnings, and is listed as three separate messages).
10587 If the @code{-gnatjnn} switch is used with a positive value for nn, then
10588 messages are output in a different manner. A message and all its continuation
10589 lines are treated as a unit, and count as only one warning or message in the
10590 statistics totals. Furthermore, the message is reformatted so that no line
10591 is longer than nn characters.
10594 @geindex -gnatq (gcc)
10599 @item @code{-gnatq}
10601 The @code{q} stands for quit (really 'don't quit').
10602 In normal operation mode, the compiler first parses the program and
10603 determines if there are any syntax errors. If there are, appropriate
10604 error messages are generated and compilation is immediately terminated.
10606 GNAT to continue with semantic analysis even if syntax errors have been
10607 found. This may enable the detection of more errors in a single run. On
10608 the other hand, the semantic analyzer is more likely to encounter some
10609 internal fatal error when given a syntactically invalid tree.
10612 @geindex -gnatQ (gcc)
10617 @item @code{-gnatQ}
10619 In normal operation mode, the @code{ALI} file is not generated if any
10620 illegalities are detected in the program. The use of @code{-gnatQ} forces
10621 generation of the @code{ALI} file. This file is marked as being in
10622 error, so it cannot be used for binding purposes, but it does contain
10623 reasonably complete cross-reference information, and thus may be useful
10624 for use by tools (e.g., semantic browsing tools or integrated development
10625 environments) that are driven from the @code{ALI} file. This switch
10626 implies @code{-gnatq}, since the semantic phase must be run to get a
10627 meaningful ALI file.
10629 In addition, if @code{-gnatt} is also specified, then the tree file is
10630 generated even if there are illegalities. It may be useful in this case
10631 to also specify @code{-gnatq} to ensure that full semantic processing
10632 occurs. The resulting tree file can be processed by ASIS, for the purpose
10633 of providing partial information about illegal units, but if the error
10634 causes the tree to be badly malformed, then ASIS may crash during the
10637 When @code{-gnatQ} is used and the generated @code{ALI} file is marked as
10638 being in error, @code{gnatmake} will attempt to recompile the source when it
10639 finds such an @code{ALI} file, including with switch @code{-gnatc}.
10641 Note that @code{-gnatQ} has no effect if @code{-gnats} is specified,
10642 since ALI files are never generated if @code{-gnats} is set.
10645 @node Warning Message Control,Debugging and Assertion Control,Output and Error Message Control,Compiler Switches
10646 @anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{fa}@anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{ff}
10647 @subsection Warning Message Control
10650 @geindex Warning messages
10652 In addition to error messages, which correspond to illegalities as defined
10653 in the Ada Reference Manual, the compiler detects two kinds of warning
10656 First, the compiler considers some constructs suspicious and generates a
10657 warning message to alert you to a possible error. Second, if the
10658 compiler detects a situation that is sure to raise an exception at
10659 run time, it generates a warning message. The following shows an example
10660 of warning messages:
10663 e.adb:4:24: warning: creation of object may raise Storage_Error
10664 e.adb:10:17: warning: static value out of range
10665 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10668 GNAT considers a large number of situations as appropriate
10669 for the generation of warning messages. As always, warnings are not
10670 definite indications of errors. For example, if you do an out-of-range
10671 assignment with the deliberate intention of raising a
10672 @code{Constraint_Error} exception, then the warning that may be
10673 issued does not indicate an error. Some of the situations for which GNAT
10674 issues warnings (at least some of the time) are given in the following
10675 list. This list is not complete, and new warnings are often added to
10676 subsequent versions of GNAT. The list is intended to give a general idea
10677 of the kinds of warnings that are generated.
10683 Possible infinitely recursive calls
10686 Out-of-range values being assigned
10689 Possible order of elaboration problems
10692 Size not a multiple of alignment for a record type
10695 Assertions (pragma Assert) that are sure to fail
10701 Address clauses with possibly unaligned values, or where an attempt is
10702 made to overlay a smaller variable with a larger one.
10705 Fixed-point type declarations with a null range
10708 Direct_IO or Sequential_IO instantiated with a type that has access values
10711 Variables that are never assigned a value
10714 Variables that are referenced before being initialized
10717 Task entries with no corresponding @code{accept} statement
10720 Duplicate accepts for the same task entry in a @code{select}
10723 Objects that take too much storage
10726 Unchecked conversion between types of differing sizes
10729 Missing @code{return} statement along some execution path in a function
10732 Incorrect (unrecognized) pragmas
10735 Incorrect external names
10738 Allocation from empty storage pool
10741 Potentially blocking operation in protected type
10744 Suspicious parenthesization of expressions
10747 Mismatching bounds in an aggregate
10750 Attempt to return local value by reference
10753 Premature instantiation of a generic body
10756 Attempt to pack aliased components
10759 Out of bounds array subscripts
10762 Wrong length on string assignment
10765 Violations of style rules if style checking is enabled
10768 Unused @emph{with} clauses
10771 @code{Bit_Order} usage that does not have any effect
10774 @code{Standard.Duration} used to resolve universal fixed expression
10777 Dereference of possibly null value
10780 Declaration that is likely to cause storage error
10783 Internal GNAT unit @emph{with}ed by application unit
10786 Values known to be out of range at compile time
10789 Unreferenced or unmodified variables. Note that a special
10790 exemption applies to variables which contain any of the substrings
10791 @code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
10792 are considered likely to be intentionally used in a situation where
10793 otherwise a warning would be given, so warnings of this kind are
10794 always suppressed for such variables.
10797 Address overlays that could clobber memory
10800 Unexpected initialization when address clause present
10803 Bad alignment for address clause
10806 Useless type conversions
10809 Redundant assignment statements and other redundant constructs
10812 Useless exception handlers
10815 Accidental hiding of name by child unit
10818 Access before elaboration detected at compile time
10821 A range in a @code{for} loop that is known to be null or might be null
10824 The following section lists compiler switches that are available
10825 to control the handling of warning messages. It is also possible
10826 to exercise much finer control over what warnings are issued and
10827 suppressed using the GNAT pragma Warnings (see the description
10828 of the pragma in the @cite{GNAT_Reference_manual}).
10830 @geindex -gnatwa (gcc)
10835 @item @code{-gnatwa}
10837 @emph{Activate most optional warnings.}
10839 This switch activates most optional warning messages. See the remaining list
10840 in this section for details on optional warning messages that can be
10841 individually controlled. The warnings that are not turned on by this
10848 @code{-gnatwd} (implicit dereferencing)
10851 @code{-gnatw.d} (tag warnings with -gnatw switch)
10854 @code{-gnatwh} (hiding)
10857 @code{-gnatw.h} (holes in record layouts)
10860 @code{-gnatw.j} (late primitives of tagged types)
10863 @code{-gnatw.k} (redefinition of names in standard)
10866 @code{-gnatwl} (elaboration warnings)
10869 @code{-gnatw.l} (inherited aspects)
10872 @code{-gnatw.n} (atomic synchronization)
10875 @code{-gnatwo} (address clause overlay)
10878 @code{-gnatw.o} (values set by out parameters ignored)
10881 @code{-gnatw.q} (questionable layout of record types)
10884 @code{-gnatw.s} (overridden size clause)
10887 @code{-gnatwt} (tracking of deleted conditional code)
10890 @code{-gnatw.u} (unordered enumeration)
10893 @code{-gnatw.w} (use of Warnings Off)
10896 @code{-gnatw.y} (reasons for package needing body)
10899 All other optional warnings are turned on.
10902 @geindex -gnatwA (gcc)
10907 @item @code{-gnatwA}
10909 @emph{Suppress all optional errors.}
10911 This switch suppresses all optional warning messages, see remaining list
10912 in this section for details on optional warning messages that can be
10913 individually controlled. Note that unlike switch @code{-gnatws}, the
10914 use of switch @code{-gnatwA} does not suppress warnings that are
10915 normally given unconditionally and cannot be individually controlled
10916 (for example, the warning about a missing exit path in a function).
10917 Also, again unlike switch @code{-gnatws}, warnings suppressed by
10918 the use of switch @code{-gnatwA} can be individually turned back
10919 on. For example the use of switch @code{-gnatwA} followed by
10920 switch @code{-gnatwd} will suppress all optional warnings except
10921 the warnings for implicit dereferencing.
10924 @geindex -gnatw.a (gcc)
10929 @item @code{-gnatw.a}
10931 @emph{Activate warnings on failing assertions.}
10933 @geindex Assert failures
10935 This switch activates warnings for assertions where the compiler can tell at
10936 compile time that the assertion will fail. Note that this warning is given
10937 even if assertions are disabled. The default is that such warnings are
10941 @geindex -gnatw.A (gcc)
10946 @item @code{-gnatw.A}
10948 @emph{Suppress warnings on failing assertions.}
10950 @geindex Assert failures
10952 This switch suppresses warnings for assertions where the compiler can tell at
10953 compile time that the assertion will fail.
10956 @geindex -gnatwb (gcc)
10961 @item @code{-gnatwb}
10963 @emph{Activate warnings on bad fixed values.}
10965 @geindex Bad fixed values
10967 @geindex Fixed-point Small value
10969 @geindex Small value
10971 This switch activates warnings for static fixed-point expressions whose
10972 value is not an exact multiple of Small. Such values are implementation
10973 dependent, since an implementation is free to choose either of the multiples
10974 that surround the value. GNAT always chooses the closer one, but this is not
10975 required behavior, and it is better to specify a value that is an exact
10976 multiple, ensuring predictable execution. The default is that such warnings
10980 @geindex -gnatwB (gcc)
10985 @item @code{-gnatwB}
10987 @emph{Suppress warnings on bad fixed values.}
10989 This switch suppresses warnings for static fixed-point expressions whose
10990 value is not an exact multiple of Small.
10993 @geindex -gnatw.b (gcc)
10998 @item @code{-gnatw.b}
11000 @emph{Activate warnings on biased representation.}
11002 @geindex Biased representation
11004 This switch activates warnings when a size clause, value size clause, component
11005 clause, or component size clause forces the use of biased representation for an
11006 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
11007 to represent 10/11). The default is that such warnings are generated.
11010 @geindex -gnatwB (gcc)
11015 @item @code{-gnatw.B}
11017 @emph{Suppress warnings on biased representation.}
11019 This switch suppresses warnings for representation clauses that force the use
11020 of biased representation.
11023 @geindex -gnatwc (gcc)
11028 @item @code{-gnatwc}
11030 @emph{Activate warnings on conditionals.}
11032 @geindex Conditionals
11035 This switch activates warnings for conditional expressions used in
11036 tests that are known to be True or False at compile time. The default
11037 is that such warnings are not generated.
11038 Note that this warning does
11039 not get issued for the use of boolean variables or constants whose
11040 values are known at compile time, since this is a standard technique
11041 for conditional compilation in Ada, and this would generate too many
11042 false positive warnings.
11044 This warning option also activates a special test for comparisons using
11045 the operators '>=' and' <='.
11046 If the compiler can tell that only the equality condition is possible,
11047 then it will warn that the '>' or '<' part of the test
11048 is useless and that the operator could be replaced by '='.
11049 An example would be comparing a @code{Natural} variable <= 0.
11051 This warning option also generates warnings if
11052 one or both tests is optimized away in a membership test for integer
11053 values if the result can be determined at compile time. Range tests on
11054 enumeration types are not included, since it is common for such tests
11055 to include an end point.
11057 This warning can also be turned on using @code{-gnatwa}.
11060 @geindex -gnatwC (gcc)
11065 @item @code{-gnatwC}
11067 @emph{Suppress warnings on conditionals.}
11069 This switch suppresses warnings for conditional expressions used in
11070 tests that are known to be True or False at compile time.
11073 @geindex -gnatw.c (gcc)
11078 @item @code{-gnatw.c}
11080 @emph{Activate warnings on missing component clauses.}
11082 @geindex Component clause
11085 This switch activates warnings for record components where a record
11086 representation clause is present and has component clauses for the
11087 majority, but not all, of the components. A warning is given for each
11088 component for which no component clause is present.
11091 @geindex -gnatwC (gcc)
11096 @item @code{-gnatw.C}
11098 @emph{Suppress warnings on missing component clauses.}
11100 This switch suppresses warnings for record components that are
11101 missing a component clause in the situation described above.
11104 @geindex -gnatwd (gcc)
11109 @item @code{-gnatwd}
11111 @emph{Activate warnings on implicit dereferencing.}
11113 If this switch is set, then the use of a prefix of an access type
11114 in an indexed component, slice, or selected component without an
11115 explicit @code{.all} will generate a warning. With this warning
11116 enabled, access checks occur only at points where an explicit
11117 @code{.all} appears in the source code (assuming no warnings are
11118 generated as a result of this switch). The default is that such
11119 warnings are not generated.
11122 @geindex -gnatwD (gcc)
11127 @item @code{-gnatwD}
11129 @emph{Suppress warnings on implicit dereferencing.}
11131 @geindex Implicit dereferencing
11133 @geindex Dereferencing
11136 This switch suppresses warnings for implicit dereferences in
11137 indexed components, slices, and selected components.
11140 @geindex -gnatw.d (gcc)
11145 @item @code{-gnatw.d}
11147 @emph{Activate tagging of warning and info messages.}
11149 If this switch is set, then warning messages are tagged, with one of the
11159 Used to tag warnings controlled by the switch @code{-gnatwx} where x
11164 Used to tag warnings controlled by the switch @code{-gnatw.x} where x
11169 Used to tag elaboration information (info) messages generated when the
11170 static model of elaboration is used and the @code{-gnatel} switch is set.
11173 @emph{[restriction warning]}
11174 Used to tag warning messages for restriction violations, activated by use
11175 of the pragma @code{Restriction_Warnings}.
11178 @emph{[warning-as-error]}
11179 Used to tag warning messages that have been converted to error messages by
11180 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
11181 the string "error: " rather than "warning: ".
11184 @emph{[enabled by default]}
11185 Used to tag all other warnings that are always given by default, unless
11186 warnings are completely suppressed using pragma @emph{Warnings(Off)} or
11187 the switch @code{-gnatws}.
11192 @geindex -gnatw.d (gcc)
11197 @item @code{-gnatw.D}
11199 @emph{Deactivate tagging of warning and info messages messages.}
11201 If this switch is set, then warning messages return to the default
11202 mode in which warnings and info messages are not tagged as described above for
11206 @geindex -gnatwe (gcc)
11209 @geindex treat as error
11214 @item @code{-gnatwe}
11216 @emph{Treat warnings and style checks as errors.}
11218 This switch causes warning messages and style check messages to be
11220 The warning string still appears, but the warning messages are counted
11221 as errors, and prevent the generation of an object file. Note that this
11222 is the only -gnatw switch that affects the handling of style check messages.
11223 Note also that this switch has no effect on info (information) messages, which
11224 are not treated as errors if this switch is present.
11227 @geindex -gnatw.e (gcc)
11232 @item @code{-gnatw.e}
11234 @emph{Activate every optional warning.}
11237 @geindex activate every optional warning
11239 This switch activates all optional warnings, including those which
11240 are not activated by @code{-gnatwa}. The use of this switch is not
11241 recommended for normal use. If you turn this switch on, it is almost
11242 certain that you will get large numbers of useless warnings. The
11243 warnings that are excluded from @code{-gnatwa} are typically highly
11244 specialized warnings that are suitable for use only in code that has
11245 been specifically designed according to specialized coding rules.
11248 @geindex -gnatwE (gcc)
11251 @geindex treat as error
11256 @item @code{-gnatwE}
11258 @emph{Treat all run-time exception warnings as errors.}
11260 This switch causes warning messages regarding errors that will be raised
11261 during run-time execution to be treated as errors.
11264 @geindex -gnatwf (gcc)
11269 @item @code{-gnatwf}
11271 @emph{Activate warnings on unreferenced formals.}
11274 @geindex unreferenced
11276 This switch causes a warning to be generated if a formal parameter
11277 is not referenced in the body of the subprogram. This warning can
11278 also be turned on using @code{-gnatwu}. The
11279 default is that these warnings are not generated.
11282 @geindex -gnatwF (gcc)
11287 @item @code{-gnatwF}
11289 @emph{Suppress warnings on unreferenced formals.}
11291 This switch suppresses warnings for unreferenced formal
11292 parameters. Note that the
11293 combination @code{-gnatwu} followed by @code{-gnatwF} has the
11294 effect of warning on unreferenced entities other than subprogram
11298 @geindex -gnatwg (gcc)
11303 @item @code{-gnatwg}
11305 @emph{Activate warnings on unrecognized pragmas.}
11308 @geindex unrecognized
11310 This switch causes a warning to be generated if an unrecognized
11311 pragma is encountered. Apart from issuing this warning, the
11312 pragma is ignored and has no effect. The default
11313 is that such warnings are issued (satisfying the Ada Reference
11314 Manual requirement that such warnings appear).
11317 @geindex -gnatwG (gcc)
11322 @item @code{-gnatwG}
11324 @emph{Suppress warnings on unrecognized pragmas.}
11326 This switch suppresses warnings for unrecognized pragmas.
11329 @geindex -gnatw.g (gcc)
11334 @item @code{-gnatw.g}
11336 @emph{Warnings used for GNAT sources.}
11338 This switch sets the warning categories that are used by the standard
11339 GNAT style. Currently this is equivalent to
11340 @code{-gnatwAao.q.s.CI.V.X.Z}
11341 but more warnings may be added in the future without advanced notice.
11344 @geindex -gnatwh (gcc)
11349 @item @code{-gnatwh}
11351 @emph{Activate warnings on hiding.}
11353 @geindex Hiding of Declarations
11355 This switch activates warnings on hiding declarations that are considered
11356 potentially confusing. Not all cases of hiding cause warnings; for example an
11357 overriding declaration hides an implicit declaration, which is just normal
11358 code. The default is that warnings on hiding are not generated.
11361 @geindex -gnatwH (gcc)
11366 @item @code{-gnatwH}
11368 @emph{Suppress warnings on hiding.}
11370 This switch suppresses warnings on hiding declarations.
11373 @geindex -gnatw.h (gcc)
11378 @item @code{-gnatw.h}
11380 @emph{Activate warnings on holes/gaps in records.}
11382 @geindex Record Representation (gaps)
11384 This switch activates warnings on component clauses in record
11385 representation clauses that leave holes (gaps) in the record layout.
11386 If this warning option is active, then record representation clauses
11387 should specify a contiguous layout, adding unused fill fields if needed.
11390 @geindex -gnatw.H (gcc)
11395 @item @code{-gnatw.H}
11397 @emph{Suppress warnings on holes/gaps in records.}
11399 This switch suppresses warnings on component clauses in record
11400 representation clauses that leave holes (haps) in the record layout.
11403 @geindex -gnatwi (gcc)
11408 @item @code{-gnatwi}
11410 @emph{Activate warnings on implementation units.}
11412 This switch activates warnings for a @emph{with} of an internal GNAT
11413 implementation unit, defined as any unit from the @code{Ada},
11414 @code{Interfaces}, @code{GNAT},
11416 hierarchies that is not
11417 documented in either the Ada Reference Manual or the GNAT
11418 Programmer's Reference Manual. Such units are intended only
11419 for internal implementation purposes and should not be @emph{with}ed
11420 by user programs. The default is that such warnings are generated
11423 @geindex -gnatwI (gcc)
11428 @item @code{-gnatwI}
11430 @emph{Disable warnings on implementation units.}
11432 This switch disables warnings for a @emph{with} of an internal GNAT
11433 implementation unit.
11436 @geindex -gnatw.i (gcc)
11441 @item @code{-gnatw.i}
11443 @emph{Activate warnings on overlapping actuals.}
11445 This switch enables a warning on statically detectable overlapping actuals in
11446 a subprogram call, when one of the actuals is an in-out parameter, and the
11447 types of the actuals are not by-copy types. This warning is off by default.
11450 @geindex -gnatw.I (gcc)
11455 @item @code{-gnatw.I}
11457 @emph{Disable warnings on overlapping actuals.}
11459 This switch disables warnings on overlapping actuals in a call..
11462 @geindex -gnatwj (gcc)
11467 @item @code{-gnatwj}
11469 @emph{Activate warnings on obsolescent features (Annex J).}
11472 @geindex obsolescent
11474 @geindex Obsolescent features
11476 If this warning option is activated, then warnings are generated for
11477 calls to subprograms marked with @code{pragma Obsolescent} and
11478 for use of features in Annex J of the Ada Reference Manual. In the
11479 case of Annex J, not all features are flagged. In particular use
11480 of the renamed packages (like @code{Text_IO}) and use of package
11481 @code{ASCII} are not flagged, since these are very common and
11482 would generate many annoying positive warnings. The default is that
11483 such warnings are not generated.
11485 In addition to the above cases, warnings are also generated for
11486 GNAT features that have been provided in past versions but which
11487 have been superseded (typically by features in the new Ada standard).
11488 For example, @code{pragma Ravenscar} will be flagged since its
11489 function is replaced by @code{pragma Profile(Ravenscar)}, and
11490 @code{pragma Interface_Name} will be flagged since its function
11491 is replaced by @code{pragma Import}.
11493 Note that this warning option functions differently from the
11494 restriction @code{No_Obsolescent_Features} in two respects.
11495 First, the restriction applies only to annex J features.
11496 Second, the restriction does flag uses of package @code{ASCII}.
11499 @geindex -gnatwJ (gcc)
11504 @item @code{-gnatwJ}
11506 @emph{Suppress warnings on obsolescent features (Annex J).}
11508 This switch disables warnings on use of obsolescent features.
11511 @geindex -gnatw.j (gcc)
11516 @item @code{-gnatw.j}
11518 @emph{Activate warnings on late declarations of tagged type primitives.}
11520 This switch activates warnings on visible primitives added to a
11521 tagged type after deriving a private extension from it.
11524 @geindex -gnatw.J (gcc)
11529 @item @code{-gnatw.J}
11531 @emph{Suppress warnings on late declarations of tagged type primitives.}
11533 This switch suppresses warnings on visible primitives added to a
11534 tagged type after deriving a private extension from it.
11537 @geindex -gnatwk (gcc)
11542 @item @code{-gnatwk}
11544 @emph{Activate warnings on variables that could be constants.}
11546 This switch activates warnings for variables that are initialized but
11547 never modified, and then could be declared constants. The default is that
11548 such warnings are not given.
11551 @geindex -gnatwK (gcc)
11556 @item @code{-gnatwK}
11558 @emph{Suppress warnings on variables that could be constants.}
11560 This switch disables warnings on variables that could be declared constants.
11563 @geindex -gnatw.k (gcc)
11568 @item @code{-gnatw.k}
11570 @emph{Activate warnings on redefinition of names in standard.}
11572 This switch activates warnings for declarations that declare a name that
11573 is defined in package Standard. Such declarations can be confusing,
11574 especially since the names in package Standard continue to be directly
11575 visible, meaning that use visibiliy on such redeclared names does not
11576 work as expected. Names of discriminants and components in records are
11577 not included in this check.
11580 @geindex -gnatwK (gcc)
11585 @item @code{-gnatw.K}
11587 @emph{Suppress warnings on redefinition of names in standard.}
11589 This switch activates warnings for declarations that declare a name that
11590 is defined in package Standard.
11593 @geindex -gnatwl (gcc)
11598 @item @code{-gnatwl}
11600 @emph{Activate warnings for elaboration pragmas.}
11602 @geindex Elaboration
11605 This switch activates warnings for possible elaboration problems,
11606 including suspicious use
11607 of @code{Elaborate} pragmas, when using the static elaboration model, and
11608 possible situations that may raise @code{Program_Error} when using the
11609 dynamic elaboration model.
11610 See the section in this guide on elaboration checking for further details.
11611 The default is that such warnings
11615 @geindex -gnatwL (gcc)
11620 @item @code{-gnatwL}
11622 @emph{Suppress warnings for elaboration pragmas.}
11624 This switch suppresses warnings for possible elaboration problems.
11627 @geindex -gnatw.l (gcc)
11632 @item @code{-gnatw.l}
11634 @emph{List inherited aspects.}
11636 This switch causes the compiler to list inherited invariants,
11637 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
11638 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
11641 @geindex -gnatw.L (gcc)
11646 @item @code{-gnatw.L}
11648 @emph{Suppress listing of inherited aspects.}
11650 This switch suppresses listing of inherited aspects.
11653 @geindex -gnatwm (gcc)
11658 @item @code{-gnatwm}
11660 @emph{Activate warnings on modified but unreferenced variables.}
11662 This switch activates warnings for variables that are assigned (using
11663 an initialization value or with one or more assignment statements) but
11664 whose value is never read. The warning is suppressed for volatile
11665 variables and also for variables that are renamings of other variables
11666 or for which an address clause is given.
11667 The default is that these warnings are not given.
11670 @geindex -gnatwM (gcc)
11675 @item @code{-gnatwM}
11677 @emph{Disable warnings on modified but unreferenced variables.}
11679 This switch disables warnings for variables that are assigned or
11680 initialized, but never read.
11683 @geindex -gnatw.m (gcc)
11688 @item @code{-gnatw.m}
11690 @emph{Activate warnings on suspicious modulus values.}
11692 This switch activates warnings for modulus values that seem suspicious.
11693 The cases caught are where the size is the same as the modulus (e.g.
11694 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11695 with no size clause. The guess in both cases is that 2**x was intended
11696 rather than x. In addition expressions of the form 2*x for small x
11697 generate a warning (the almost certainly accurate guess being that
11698 2**x was intended). The default is that these warnings are given.
11701 @geindex -gnatw.M (gcc)
11706 @item @code{-gnatw.M}
11708 @emph{Disable warnings on suspicious modulus values.}
11710 This switch disables warnings for suspicious modulus values.
11713 @geindex -gnatwn (gcc)
11718 @item @code{-gnatwn}
11720 @emph{Set normal warnings mode.}
11722 This switch sets normal warning mode, in which enabled warnings are
11723 issued and treated as warnings rather than errors. This is the default
11724 mode. the switch @code{-gnatwn} can be used to cancel the effect of
11725 an explicit @code{-gnatws} or
11726 @code{-gnatwe}. It also cancels the effect of the
11727 implicit @code{-gnatwe} that is activated by the
11728 use of @code{-gnatg}.
11731 @geindex -gnatw.n (gcc)
11733 @geindex Atomic Synchronization
11739 @item @code{-gnatw.n}
11741 @emph{Activate warnings on atomic synchronization.}
11743 This switch actives warnings when an access to an atomic variable
11744 requires the generation of atomic synchronization code. These
11745 warnings are off by default.
11748 @geindex -gnatw.N (gcc)
11753 @item @code{-gnatw.N}
11755 @emph{Suppress warnings on atomic synchronization.}
11757 @geindex Atomic Synchronization
11760 This switch suppresses warnings when an access to an atomic variable
11761 requires the generation of atomic synchronization code.
11764 @geindex -gnatwo (gcc)
11766 @geindex Address Clauses
11772 @item @code{-gnatwo}
11774 @emph{Activate warnings on address clause overlays.}
11776 This switch activates warnings for possibly unintended initialization
11777 effects of defining address clauses that cause one variable to overlap
11778 another. The default is that such warnings are generated.
11781 @geindex -gnatwO (gcc)
11786 @item @code{-gnatwO}
11788 @emph{Suppress warnings on address clause overlays.}
11790 This switch suppresses warnings on possibly unintended initialization
11791 effects of defining address clauses that cause one variable to overlap
11795 @geindex -gnatw.o (gcc)
11800 @item @code{-gnatw.o}
11802 @emph{Activate warnings on modified but unreferenced out parameters.}
11804 This switch activates warnings for variables that are modified by using
11805 them as actuals for a call to a procedure with an out mode formal, where
11806 the resulting assigned value is never read. It is applicable in the case
11807 where there is more than one out mode formal. If there is only one out
11808 mode formal, the warning is issued by default (controlled by -gnatwu).
11809 The warning is suppressed for volatile
11810 variables and also for variables that are renamings of other variables
11811 or for which an address clause is given.
11812 The default is that these warnings are not given.
11815 @geindex -gnatw.O (gcc)
11820 @item @code{-gnatw.O}
11822 @emph{Disable warnings on modified but unreferenced out parameters.}
11824 This switch suppresses warnings for variables that are modified by using
11825 them as actuals for a call to a procedure with an out mode formal, where
11826 the resulting assigned value is never read.
11829 @geindex -gnatwp (gcc)
11837 @item @code{-gnatwp}
11839 @emph{Activate warnings on ineffective pragma Inlines.}
11841 This switch activates warnings for failure of front end inlining
11842 (activated by @code{-gnatN}) to inline a particular call. There are
11843 many reasons for not being able to inline a call, including most
11844 commonly that the call is too complex to inline. The default is
11845 that such warnings are not given.
11846 Warnings on ineffective inlining by the gcc back-end can be activated
11847 separately, using the gcc switch -Winline.
11850 @geindex -gnatwP (gcc)
11855 @item @code{-gnatwP}
11857 @emph{Suppress warnings on ineffective pragma Inlines.}
11859 This switch suppresses warnings on ineffective pragma Inlines. If the
11860 inlining mechanism cannot inline a call, it will simply ignore the
11864 @geindex -gnatw.p (gcc)
11866 @geindex Parameter order
11872 @item @code{-gnatw.p}
11874 @emph{Activate warnings on parameter ordering.}
11876 This switch activates warnings for cases of suspicious parameter
11877 ordering when the list of arguments are all simple identifiers that
11878 match the names of the formals, but are in a different order. The
11879 warning is suppressed if any use of named parameter notation is used,
11880 so this is the appropriate way to suppress a false positive (and
11881 serves to emphasize that the "misordering" is deliberate). The
11882 default is that such warnings are not given.
11885 @geindex -gnatw.P (gcc)
11890 @item @code{-gnatw.P}
11892 @emph{Suppress warnings on parameter ordering.}
11894 This switch suppresses warnings on cases of suspicious parameter
11898 @geindex -gnatwq (gcc)
11900 @geindex Parentheses
11906 @item @code{-gnatwq}
11908 @emph{Activate warnings on questionable missing parentheses.}
11910 This switch activates warnings for cases where parentheses are not used and
11911 the result is potential ambiguity from a readers point of view. For example
11912 (not a > b) when a and b are modular means ((not a) > b) and very likely the
11913 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
11914 quite likely ((-x) mod 5) was intended. In such situations it seems best to
11915 follow the rule of always parenthesizing to make the association clear, and
11916 this warning switch warns if such parentheses are not present. The default
11917 is that these warnings are given.
11920 @geindex -gnatwQ (gcc)
11925 @item @code{-gnatwQ}
11927 @emph{Suppress warnings on questionable missing parentheses.}
11929 This switch suppresses warnings for cases where the association is not
11930 clear and the use of parentheses is preferred.
11933 @geindex -gnatw.q (gcc)
11941 @item @code{-gnatw.q}
11943 @emph{Activate warnings on questionable layout of record types.}
11945 This switch activates warnings for cases where the default layout of
11946 a record type, that is to say the layout of its components in textual
11947 order of the source code, would very likely cause inefficiencies in
11948 the code generated by the compiler, both in terms of space and speed
11949 during execution. One warning is issued for each problematic component
11950 without representation clause in the nonvariant part and then in each
11951 variant recursively, if any.
11953 The purpose of these warnings is neither to prescribe an optimal layout
11954 nor to force the use of representation clauses, but rather to get rid of
11955 the most blatant inefficiencies in the layout. Therefore, the default
11956 layout is matched against the following synthetic ordered layout and
11957 the deviations are flagged on a component-by-component basis:
11963 first all components or groups of components whose length is fixed
11964 and a multiple of the storage unit,
11967 then the remaining components whose length is fixed and not a multiple
11968 of the storage unit,
11971 then the remaining components whose length doesn't depend on discriminants
11972 (that is to say, with variable but uniform length for all objects),
11975 then all components whose length depends on discriminants,
11978 finally the variant part (if any),
11981 for the nonvariant part and for each variant recursively, if any.
11983 The exact wording of the warning depends on whether the compiler is allowed
11984 to reorder the components in the record type or precluded from doing it by
11985 means of pragma @code{No_Component_Reordering}.
11987 The default is that these warnings are not given.
11990 @geindex -gnatw.Q (gcc)
11995 @item @code{-gnatw.Q}
11997 @emph{Suppress warnings on questionable layout of record types.}
11999 This switch suppresses warnings for cases where the default layout of
12000 a record type would very likely cause inefficiencies.
12003 @geindex -gnatwr (gcc)
12008 @item @code{-gnatwr}
12010 @emph{Activate warnings on redundant constructs.}
12012 This switch activates warnings for redundant constructs. The following
12013 is the current list of constructs regarded as redundant:
12019 Assignment of an item to itself.
12022 Type conversion that converts an expression to its own type.
12025 Use of the attribute @code{Base} where @code{typ'Base} is the same
12029 Use of pragma @code{Pack} when all components are placed by a record
12030 representation clause.
12033 Exception handler containing only a reraise statement (raise with no
12034 operand) which has no effect.
12037 Use of the operator abs on an operand that is known at compile time
12041 Comparison of an object or (unary or binary) operation of boolean type to
12042 an explicit True value.
12045 The default is that warnings for redundant constructs are not given.
12048 @geindex -gnatwR (gcc)
12053 @item @code{-gnatwR}
12055 @emph{Suppress warnings on redundant constructs.}
12057 This switch suppresses warnings for redundant constructs.
12060 @geindex -gnatw.r (gcc)
12065 @item @code{-gnatw.r}
12067 @emph{Activate warnings for object renaming function.}
12069 This switch activates warnings for an object renaming that renames a
12070 function call, which is equivalent to a constant declaration (as
12071 opposed to renaming the function itself). The default is that these
12072 warnings are given.
12075 @geindex -gnatwT (gcc)
12080 @item @code{-gnatw.R}
12082 @emph{Suppress warnings for object renaming function.}
12084 This switch suppresses warnings for object renaming function.
12087 @geindex -gnatws (gcc)
12092 @item @code{-gnatws}
12094 @emph{Suppress all warnings.}
12096 This switch completely suppresses the
12097 output of all warning messages from the GNAT front end, including
12098 both warnings that can be controlled by switches described in this
12099 section, and those that are normally given unconditionally. The
12100 effect of this suppress action can only be cancelled by a subsequent
12101 use of the switch @code{-gnatwn}.
12103 Note that switch @code{-gnatws} does not suppress
12104 warnings from the @code{gcc} back end.
12105 To suppress these back end warnings as well, use the switch @code{-w}
12106 in addition to @code{-gnatws}. Also this switch has no effect on the
12107 handling of style check messages.
12110 @geindex -gnatw.s (gcc)
12112 @geindex Record Representation (component sizes)
12117 @item @code{-gnatw.s}
12119 @emph{Activate warnings on overridden size clauses.}
12121 This switch activates warnings on component clauses in record
12122 representation clauses where the length given overrides that
12123 specified by an explicit size clause for the component type. A
12124 warning is similarly given in the array case if a specified
12125 component size overrides an explicit size clause for the array
12129 @geindex -gnatw.S (gcc)
12134 @item @code{-gnatw.S}
12136 @emph{Suppress warnings on overridden size clauses.}
12138 This switch suppresses warnings on component clauses in record
12139 representation clauses that override size clauses, and similar
12140 warnings when an array component size overrides a size clause.
12143 @geindex -gnatwt (gcc)
12145 @geindex Deactivated code
12148 @geindex Deleted code
12154 @item @code{-gnatwt}
12156 @emph{Activate warnings for tracking of deleted conditional code.}
12158 This switch activates warnings for tracking of code in conditionals (IF and
12159 CASE statements) that is detected to be dead code which cannot be executed, and
12160 which is removed by the front end. This warning is off by default. This may be
12161 useful for detecting deactivated code in certified applications.
12164 @geindex -gnatwT (gcc)
12169 @item @code{-gnatwT}
12171 @emph{Suppress warnings for tracking of deleted conditional code.}
12173 This switch suppresses warnings for tracking of deleted conditional code.
12176 @geindex -gnatw.t (gcc)
12181 @item @code{-gnatw.t}
12183 @emph{Activate warnings on suspicious contracts.}
12185 This switch activates warnings on suspicious contracts. This includes
12186 warnings on suspicious postconditions (whether a pragma @code{Postcondition} or a
12187 @code{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
12188 @code{Contract_Cases}). A function postcondition or contract case is suspicious
12189 when no postcondition or contract case for this function mentions the result
12190 of the function. A procedure postcondition or contract case is suspicious
12191 when it only refers to the pre-state of the procedure, because in that case
12192 it should rather be expressed as a precondition. This switch also controls
12193 warnings on suspicious cases of expressions typically found in contracts like
12194 quantified expressions and uses of Update attribute. The default is that such
12195 warnings are generated.
12198 @geindex -gnatw.T (gcc)
12203 @item @code{-gnatw.T}
12205 @emph{Suppress warnings on suspicious contracts.}
12207 This switch suppresses warnings on suspicious contracts.
12210 @geindex -gnatwu (gcc)
12215 @item @code{-gnatwu}
12217 @emph{Activate warnings on unused entities.}
12219 This switch activates warnings to be generated for entities that
12220 are declared but not referenced, and for units that are @emph{with}ed
12222 referenced. In the case of packages, a warning is also generated if
12223 no entities in the package are referenced. This means that if a with'ed
12224 package is referenced but the only references are in @code{use}
12225 clauses or @code{renames}
12226 declarations, a warning is still generated. A warning is also generated
12227 for a generic package that is @emph{with}ed but never instantiated.
12228 In the case where a package or subprogram body is compiled, and there
12229 is a @emph{with} on the corresponding spec
12230 that is only referenced in the body,
12231 a warning is also generated, noting that the
12232 @emph{with} can be moved to the body. The default is that
12233 such warnings are not generated.
12234 This switch also activates warnings on unreferenced formals
12235 (it includes the effect of @code{-gnatwf}).
12238 @geindex -gnatwU (gcc)
12243 @item @code{-gnatwU}
12245 @emph{Suppress warnings on unused entities.}
12247 This switch suppresses warnings for unused entities and packages.
12248 It also turns off warnings on unreferenced formals (and thus includes
12249 the effect of @code{-gnatwF}).
12252 @geindex -gnatw.u (gcc)
12257 @item @code{-gnatw.u}
12259 @emph{Activate warnings on unordered enumeration types.}
12261 This switch causes enumeration types to be considered as conceptually
12262 unordered, unless an explicit pragma @code{Ordered} is given for the type.
12263 The effect is to generate warnings in clients that use explicit comparisons
12264 or subranges, since these constructs both treat objects of the type as
12265 ordered. (A @emph{client} is defined as a unit that is other than the unit in
12266 which the type is declared, or its body or subunits.) Please refer to
12267 the description of pragma @code{Ordered} in the
12268 @cite{GNAT Reference Manual} for further details.
12269 The default is that such warnings are not generated.
12272 @geindex -gnatw.U (gcc)
12277 @item @code{-gnatw.U}
12279 @emph{Deactivate warnings on unordered enumeration types.}
12281 This switch causes all enumeration types to be considered as ordered, so
12282 that no warnings are given for comparisons or subranges for any type.
12285 @geindex -gnatwv (gcc)
12287 @geindex Unassigned variable warnings
12292 @item @code{-gnatwv}
12294 @emph{Activate warnings on unassigned variables.}
12296 This switch activates warnings for access to variables which
12297 may not be properly initialized. The default is that
12298 such warnings are generated.
12301 @geindex -gnatwV (gcc)
12306 @item @code{-gnatwV}
12308 @emph{Suppress warnings on unassigned variables.}
12310 This switch suppresses warnings for access to variables which
12311 may not be properly initialized.
12312 For variables of a composite type, the warning can also be suppressed in
12313 Ada 2005 by using a default initialization with a box. For example, if
12314 Table is an array of records whose components are only partially uninitialized,
12315 then the following code:
12318 Tab : Table := (others => <>);
12321 will suppress warnings on subsequent statements that access components
12325 @geindex -gnatw.v (gcc)
12327 @geindex bit order warnings
12332 @item @code{-gnatw.v}
12334 @emph{Activate info messages for non-default bit order.}
12336 This switch activates messages (labeled "info", they are not warnings,
12337 just informational messages) about the effects of non-default bit-order
12338 on records to which a component clause is applied. The effect of specifying
12339 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
12340 these messages, which are given by default, are useful in understanding the
12341 exact consequences of using this feature.
12344 @geindex -gnatw.V (gcc)
12349 @item @code{-gnatw.V}
12351 @emph{Suppress info messages for non-default bit order.}
12353 This switch suppresses information messages for the effects of specifying
12354 non-default bit order on record components with component clauses.
12357 @geindex -gnatww (gcc)
12359 @geindex String indexing warnings
12364 @item @code{-gnatww}
12366 @emph{Activate warnings on wrong low bound assumption.}
12368 This switch activates warnings for indexing an unconstrained string parameter
12369 with a literal or S'Length. This is a case where the code is assuming that the
12370 low bound is one, which is in general not true (for example when a slice is
12371 passed). The default is that such warnings are generated.
12374 @geindex -gnatwW (gcc)
12379 @item @code{-gnatwW}
12381 @emph{Suppress warnings on wrong low bound assumption.}
12383 This switch suppresses warnings for indexing an unconstrained string parameter
12384 with a literal or S'Length. Note that this warning can also be suppressed
12385 in a particular case by adding an assertion that the lower bound is 1,
12386 as shown in the following example:
12389 procedure K (S : String) is
12390 pragma Assert (S'First = 1);
12395 @geindex -gnatw.w (gcc)
12397 @geindex Warnings Off control
12402 @item @code{-gnatw.w}
12404 @emph{Activate warnings on Warnings Off pragmas.}
12406 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
12407 where either the pragma is entirely useless (because it suppresses no
12408 warnings), or it could be replaced by @code{pragma Unreferenced} or
12409 @code{pragma Unmodified}.
12410 Also activates warnings for the case of
12411 Warnings (Off, String), where either there is no matching
12412 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12413 The default is that these warnings are not given.
12416 @geindex -gnatw.W (gcc)
12421 @item @code{-gnatw.W}
12423 @emph{Suppress warnings on unnecessary Warnings Off pragmas.}
12425 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
12428 @geindex -gnatwx (gcc)
12430 @geindex Export/Import pragma warnings
12435 @item @code{-gnatwx}
12437 @emph{Activate warnings on Export/Import pragmas.}
12439 This switch activates warnings on Export/Import pragmas when
12440 the compiler detects a possible conflict between the Ada and
12441 foreign language calling sequences. For example, the use of
12442 default parameters in a convention C procedure is dubious
12443 because the C compiler cannot supply the proper default, so
12444 a warning is issued. The default is that such warnings are
12448 @geindex -gnatwX (gcc)
12453 @item @code{-gnatwX}
12455 @emph{Suppress warnings on Export/Import pragmas.}
12457 This switch suppresses warnings on Export/Import pragmas.
12458 The sense of this is that you are telling the compiler that
12459 you know what you are doing in writing the pragma, and it
12460 should not complain at you.
12463 @geindex -gnatwm (gcc)
12468 @item @code{-gnatw.x}
12470 @emph{Activate warnings for No_Exception_Propagation mode.}
12472 This switch activates warnings for exception usage when pragma Restrictions
12473 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
12474 explicit exception raises which are not covered by a local handler, and for
12475 exception handlers which do not cover a local raise. The default is that these
12476 warnings are not given.
12478 @item @code{-gnatw.X}
12480 @emph{Disable warnings for No_Exception_Propagation mode.}
12482 This switch disables warnings for exception usage when pragma Restrictions
12483 (No_Exception_Propagation) is in effect.
12486 @geindex -gnatwy (gcc)
12488 @geindex Ada compatibility issues warnings
12493 @item @code{-gnatwy}
12495 @emph{Activate warnings for Ada compatibility issues.}
12497 For the most part, newer versions of Ada are upwards compatible
12498 with older versions. For example, Ada 2005 programs will almost
12499 always work when compiled as Ada 2012.
12500 However there are some exceptions (for example the fact that
12501 @code{some} is now a reserved word in Ada 2012). This
12502 switch activates several warnings to help in identifying
12503 and correcting such incompatibilities. The default is that
12504 these warnings are generated. Note that at one point Ada 2005
12505 was called Ada 0Y, hence the choice of character.
12508 @geindex -gnatwY (gcc)
12510 @geindex Ada compatibility issues warnings
12515 @item @code{-gnatwY}
12517 @emph{Disable warnings for Ada compatibility issues.}
12519 This switch suppresses the warnings intended to help in identifying
12520 incompatibilities between Ada language versions.
12523 @geindex -gnatw.y (gcc)
12525 @geindex Package spec needing body
12530 @item @code{-gnatw.y}
12532 @emph{Activate information messages for why package spec needs body.}
12534 There are a number of cases in which a package spec needs a body.
12535 For example, the use of pragma Elaborate_Body, or the declaration
12536 of a procedure specification requiring a completion. This switch
12537 causes information messages to be output showing why a package
12538 specification requires a body. This can be useful in the case of
12539 a large package specification which is unexpectedly requiring a
12540 body. The default is that such information messages are not output.
12543 @geindex -gnatw.Y (gcc)
12545 @geindex No information messages for why package spec needs body
12550 @item @code{-gnatw.Y}
12552 @emph{Disable information messages for why package spec needs body.}
12554 This switch suppresses the output of information messages showing why
12555 a package specification needs a body.
12558 @geindex -gnatwz (gcc)
12560 @geindex Unchecked_Conversion warnings
12565 @item @code{-gnatwz}
12567 @emph{Activate warnings on unchecked conversions.}
12569 This switch activates warnings for unchecked conversions
12570 where the types are known at compile time to have different
12571 sizes. The default is that such warnings are generated. Warnings are also
12572 generated for subprogram pointers with different conventions.
12575 @geindex -gnatwZ (gcc)
12580 @item @code{-gnatwZ}
12582 @emph{Suppress warnings on unchecked conversions.}
12584 This switch suppresses warnings for unchecked conversions
12585 where the types are known at compile time to have different
12586 sizes or conventions.
12589 @geindex -gnatw.z (gcc)
12591 @geindex Size/Alignment warnings
12596 @item @code{-gnatw.z}
12598 @emph{Activate warnings for size not a multiple of alignment.}
12600 This switch activates warnings for cases of record types with
12601 specified @code{Size} and @code{Alignment} attributes where the
12602 size is not a multiple of the alignment, resulting in an object
12603 size that is greater than the specified size. The default
12604 is that such warnings are generated.
12607 @geindex -gnatw.Z (gcc)
12609 @geindex Size/Alignment warnings
12614 @item @code{-gnatw.Z}
12616 @emph{Suppress warnings for size not a multiple of alignment.}
12618 This switch suppresses warnings for cases of record types with
12619 specified @code{Size} and @code{Alignment} attributes where the
12620 size is not a multiple of the alignment, resulting in an object
12621 size that is greater than the specified size.
12622 The warning can also be
12623 suppressed by giving an explicit @code{Object_Size} value.
12626 @geindex -Wunused (gcc)
12631 @item @code{-Wunused}
12633 The warnings controlled by the @code{-gnatw} switch are generated by
12634 the front end of the compiler. The GCC back end can provide
12635 additional warnings and they are controlled by the @code{-W} switch.
12636 For example, @code{-Wunused} activates back end
12637 warnings for entities that are declared but not referenced.
12640 @geindex -Wuninitialized (gcc)
12645 @item @code{-Wuninitialized}
12647 Similarly, @code{-Wuninitialized} activates
12648 the back end warning for uninitialized variables. This switch must be
12649 used in conjunction with an optimization level greater than zero.
12652 @geindex -Wstack-usage (gcc)
12657 @item @code{-Wstack-usage=@emph{len}}
12659 Warn if the stack usage of a subprogram might be larger than @code{len} bytes.
12660 See @ref{f5,,Static Stack Usage Analysis} for details.
12663 @geindex -Wall (gcc)
12670 This switch enables most warnings from the GCC back end.
12671 The code generator detects a number of warning situations that are missed
12672 by the GNAT front end, and this switch can be used to activate them.
12673 The use of this switch also sets the default front end warning mode to
12674 @code{-gnatwa}, that is, most front end warnings activated as well.
12684 Conversely, this switch suppresses warnings from the GCC back end.
12685 The use of this switch also sets the default front end warning mode to
12686 @code{-gnatws}, that is, front end warnings suppressed as well.
12689 @geindex -Werror (gcc)
12694 @item @code{-Werror}
12696 This switch causes warnings from the GCC back end to be treated as
12697 errors. The warning string still appears, but the warning messages are
12698 counted as errors, and prevent the generation of an object file.
12701 A string of warning parameters can be used in the same parameter. For example:
12707 will turn on all optional warnings except for unrecognized pragma warnings,
12708 and also specify that warnings should be treated as errors.
12710 When no switch @code{-gnatw} is used, this is equivalent to:
12830 @node Debugging and Assertion Control,Validity Checking,Warning Message Control,Compiler Switches
12831 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-and-assertion-control}@anchor{100}@anchor{gnat_ugn/building_executable_programs_with_gnat id16}@anchor{101}
12832 @subsection Debugging and Assertion Control
12835 @geindex -gnata (gcc)
12840 @item @code{-gnata}
12846 @geindex Assertions
12848 @geindex Precondition
12850 @geindex Postcondition
12852 @geindex Type invariants
12854 @geindex Subtype predicates
12856 The @code{-gnata} option is equivalent to the following @code{Assertion_Policy} pragma:
12859 pragma Assertion_Policy (Check);
12862 Which is a shorthand for:
12865 pragma Assertion_Policy
12867 Static_Predicate => Check,
12868 Dynamic_Predicate => Check,
12870 Pre'Class => Check,
12872 Post'Class => Check,
12873 Type_Invariant => Check,
12874 Type_Invariant'Class => Check);
12877 The pragmas @code{Assert} and @code{Debug} normally have no effect and
12878 are ignored. This switch, where @code{a} stands for 'assert', causes
12879 pragmas @code{Assert} and @code{Debug} to be activated. This switch also
12880 causes preconditions, postconditions, subtype predicates, and
12881 type invariants to be activated.
12883 The pragmas have the form:
12886 pragma Assert (<Boolean-expression> [, <static-string-expression>])
12887 pragma Debug (<procedure call>)
12888 pragma Type_Invariant (<type-local-name>, <Boolean-expression>)
12889 pragma Predicate (<type-local-name>, <Boolean-expression>)
12890 pragma Precondition (<Boolean-expression>, <string-expression>)
12891 pragma Postcondition (<Boolean-expression>, <string-expression>)
12894 The aspects have the form:
12897 with [Pre|Post|Type_Invariant|Dynamic_Predicate|Static_Predicate]
12898 => <Boolean-expression>;
12901 The @code{Assert} pragma causes @code{Boolean-expression} to be tested.
12902 If the result is @code{True}, the pragma has no effect (other than
12903 possible side effects from evaluating the expression). If the result is
12904 @code{False}, the exception @code{Assert_Failure} declared in the package
12905 @code{System.Assertions} is raised (passing @code{static-string-expression}, if
12906 present, as the message associated with the exception). If no string
12907 expression is given, the default is a string containing the file name and
12908 line number of the pragma.
12910 The @code{Debug} pragma causes @code{procedure} to be called. Note that
12911 @code{pragma Debug} may appear within a declaration sequence, allowing
12912 debugging procedures to be called between declarations.
12914 For the aspect specification, the @code{Boolean-expression} is evaluated.
12915 If the result is @code{True}, the aspect has no effect. If the result
12916 is @code{False}, the exception @code{Assert_Failure} is raised.
12919 @node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
12920 @anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{102}
12921 @subsection Validity Checking
12924 @geindex Validity Checking
12926 The Ada Reference Manual defines the concept of invalid values (see
12927 RM 13.9.1). The primary source of invalid values is uninitialized
12928 variables. A scalar variable that is left uninitialized may contain
12929 an invalid value; the concept of invalid does not apply to access or
12932 It is an error to read an invalid value, but the RM does not require
12933 run-time checks to detect such errors, except for some minimal
12934 checking to prevent erroneous execution (i.e. unpredictable
12935 behavior). This corresponds to the @code{-gnatVd} switch below,
12936 which is the default. For example, by default, if the expression of a
12937 case statement is invalid, it will raise Constraint_Error rather than
12938 causing a wild jump, and if an array index on the left-hand side of an
12939 assignment is invalid, it will raise Constraint_Error rather than
12940 overwriting an arbitrary memory location.
12942 The @code{-gnatVa} may be used to enable additional validity checks,
12943 which are not required by the RM. These checks are often very
12944 expensive (which is why the RM does not require them). These checks
12945 are useful in tracking down uninitialized variables, but they are
12946 not usually recommended for production builds, and in particular
12947 we do not recommend using these extra validity checking options in
12948 combination with optimization, since this can confuse the optimizer.
12949 If performance is a consideration, leading to the need to optimize,
12950 then the validity checking options should not be used.
12952 The other @code{-gnatV@emph{x}} switches below allow finer-grained
12953 control; you can enable whichever validity checks you desire. However,
12954 for most debugging purposes, @code{-gnatVa} is sufficient, and the
12955 default @code{-gnatVd} (i.e. standard Ada behavior) is usually
12956 sufficient for non-debugging use.
12958 The @code{-gnatB} switch tells the compiler to assume that all
12959 values are valid (that is, within their declared subtype range)
12960 except in the context of a use of the Valid attribute. This means
12961 the compiler can generate more efficient code, since the range
12962 of values is better known at compile time. However, an uninitialized
12963 variable can cause wild jumps and memory corruption in this mode.
12965 The @code{-gnatV@emph{x}} switch allows control over the validity
12966 checking mode as described below.
12967 The @code{x} argument is a string of letters that
12968 indicate validity checks that are performed or not performed in addition
12969 to the default checks required by Ada as described above.
12971 @geindex -gnatVa (gcc)
12976 @item @code{-gnatVa}
12978 @emph{All validity checks.}
12980 All validity checks are turned on.
12981 That is, @code{-gnatVa} is
12982 equivalent to @code{gnatVcdfimorst}.
12985 @geindex -gnatVc (gcc)
12990 @item @code{-gnatVc}
12992 @emph{Validity checks for copies.}
12994 The right hand side of assignments, and the initializing values of
12995 object declarations are validity checked.
12998 @geindex -gnatVd (gcc)
13003 @item @code{-gnatVd}
13005 @emph{Default (RM) validity checks.}
13007 Some validity checks are done by default following normal Ada semantics
13008 (RM 13.9.1 (9-11)).
13009 A check is done in case statements that the expression is within the range
13010 of the subtype. If it is not, Constraint_Error is raised.
13011 For assignments to array components, a check is done that the expression used
13012 as index is within the range. If it is not, Constraint_Error is raised.
13013 Both these validity checks may be turned off using switch @code{-gnatVD}.
13014 They are turned on by default. If @code{-gnatVD} is specified, a subsequent
13015 switch @code{-gnatVd} will leave the checks turned on.
13016 Switch @code{-gnatVD} should be used only if you are sure that all such
13017 expressions have valid values. If you use this switch and invalid values
13018 are present, then the program is erroneous, and wild jumps or memory
13019 overwriting may occur.
13022 @geindex -gnatVe (gcc)
13027 @item @code{-gnatVe}
13029 @emph{Validity checks for elementary components.}
13031 In the absence of this switch, assignments to record or array components are
13032 not validity checked, even if validity checks for assignments generally
13033 (@code{-gnatVc}) are turned on. In Ada, assignment of composite values do not
13034 require valid data, but assignment of individual components does. So for
13035 example, there is a difference between copying the elements of an array with a
13036 slice assignment, compared to assigning element by element in a loop. This
13037 switch allows you to turn off validity checking for components, even when they
13038 are assigned component by component.
13041 @geindex -gnatVf (gcc)
13046 @item @code{-gnatVf}
13048 @emph{Validity checks for floating-point values.}
13050 In the absence of this switch, validity checking occurs only for discrete
13051 values. If @code{-gnatVf} is specified, then validity checking also applies
13052 for floating-point values, and NaNs and infinities are considered invalid,
13053 as well as out of range values for constrained types. Note that this means
13054 that standard IEEE infinity mode is not allowed. The exact contexts
13055 in which floating-point values are checked depends on the setting of other
13056 options. For example, @code{-gnatVif} or @code{-gnatVfi}
13057 (the order does not matter) specifies that floating-point parameters of mode
13058 @code{in} should be validity checked.
13061 @geindex -gnatVi (gcc)
13066 @item @code{-gnatVi}
13068 @emph{Validity checks for `@w{`}in`@w{`} mode parameters.}
13070 Arguments for parameters of mode @code{in} are validity checked in function
13071 and procedure calls at the point of call.
13074 @geindex -gnatVm (gcc)
13079 @item @code{-gnatVm}
13081 @emph{Validity checks for `@w{`}in out`@w{`} mode parameters.}
13083 Arguments for parameters of mode @code{in out} are validity checked in
13084 procedure calls at the point of call. The @code{'m'} here stands for
13085 modify, since this concerns parameters that can be modified by the call.
13086 Note that there is no specific option to test @code{out} parameters,
13087 but any reference within the subprogram will be tested in the usual
13088 manner, and if an invalid value is copied back, any reference to it
13089 will be subject to validity checking.
13092 @geindex -gnatVn (gcc)
13097 @item @code{-gnatVn}
13099 @emph{No validity checks.}
13101 This switch turns off all validity checking, including the default checking
13102 for case statements and left hand side subscripts. Note that the use of
13103 the switch @code{-gnatp} suppresses all run-time checks, including
13104 validity checks, and thus implies @code{-gnatVn}. When this switch
13105 is used, it cancels any other @code{-gnatV} previously issued.
13108 @geindex -gnatVo (gcc)
13113 @item @code{-gnatVo}
13115 @emph{Validity checks for operator and attribute operands.}
13117 Arguments for predefined operators and attributes are validity checked.
13118 This includes all operators in package @code{Standard},
13119 the shift operators defined as intrinsic in package @code{Interfaces}
13120 and operands for attributes such as @code{Pos}. Checks are also made
13121 on individual component values for composite comparisons, and on the
13122 expressions in type conversions and qualified expressions. Checks are
13123 also made on explicit ranges using @code{..} (e.g., slices, loops etc).
13126 @geindex -gnatVp (gcc)
13131 @item @code{-gnatVp}
13133 @emph{Validity checks for parameters.}
13135 This controls the treatment of parameters within a subprogram (as opposed
13136 to @code{-gnatVi} and @code{-gnatVm} which control validity testing
13137 of parameters on a call. If either of these call options is used, then
13138 normally an assumption is made within a subprogram that the input arguments
13139 have been validity checking at the point of call, and do not need checking
13140 again within a subprogram). If @code{-gnatVp} is set, then this assumption
13141 is not made, and parameters are not assumed to be valid, so their validity
13142 will be checked (or rechecked) within the subprogram.
13145 @geindex -gnatVr (gcc)
13150 @item @code{-gnatVr}
13152 @emph{Validity checks for function returns.}
13154 The expression in @code{return} statements in functions is validity
13158 @geindex -gnatVs (gcc)
13163 @item @code{-gnatVs}
13165 @emph{Validity checks for subscripts.}
13167 All subscripts expressions are checked for validity, whether they appear
13168 on the right side or left side (in default mode only left side subscripts
13169 are validity checked).
13172 @geindex -gnatVt (gcc)
13177 @item @code{-gnatVt}
13179 @emph{Validity checks for tests.}
13181 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
13182 statements are checked, as well as guard expressions in entry calls.
13185 The @code{-gnatV} switch may be followed by a string of letters
13186 to turn on a series of validity checking options.
13187 For example, @code{-gnatVcr}
13188 specifies that in addition to the default validity checking, copies and
13189 function return expressions are to be validity checked.
13190 In order to make it easier to specify the desired combination of effects,
13191 the upper case letters @code{CDFIMORST} may
13192 be used to turn off the corresponding lower case option.
13193 Thus @code{-gnatVaM} turns on all validity checking options except for
13194 checking of @code{in out} parameters.
13196 The specification of additional validity checking generates extra code (and
13197 in the case of @code{-gnatVa} the code expansion can be substantial).
13198 However, these additional checks can be very useful in detecting
13199 uninitialized variables, incorrect use of unchecked conversion, and other
13200 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
13201 is useful in conjunction with the extra validity checking, since this
13202 ensures that wherever possible uninitialized variables have invalid values.
13204 See also the pragma @code{Validity_Checks} which allows modification of
13205 the validity checking mode at the program source level, and also allows for
13206 temporary disabling of validity checks.
13208 @node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
13209 @anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{103}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{fb}
13210 @subsection Style Checking
13213 @geindex Style checking
13215 @geindex -gnaty (gcc)
13217 The @code{-gnatyx} switch causes the compiler to
13218 enforce specified style rules. A limited set of style rules has been used
13219 in writing the GNAT sources themselves. This switch allows user programs
13220 to activate all or some of these checks. If the source program fails a
13221 specified style check, an appropriate message is given, preceded by
13222 the character sequence '(style)'. This message does not prevent
13223 successful compilation (unless the @code{-gnatwe} switch is used).
13225 Note that this is by no means intended to be a general facility for
13226 checking arbitrary coding standards. It is simply an embedding of the
13227 style rules we have chosen for the GNAT sources. If you are starting
13228 a project which does not have established style standards, you may
13229 find it useful to adopt the entire set of GNAT coding standards, or
13230 some subset of them.
13233 The string @code{x} is a sequence of letters or digits
13234 indicating the particular style
13235 checks to be performed. The following checks are defined:
13237 @geindex -gnaty[0-9] (gcc)
13242 @item @code{-gnaty0}
13244 @emph{Specify indentation level.}
13246 If a digit from 1-9 appears
13247 in the string after @code{-gnaty}
13248 then proper indentation is checked, with the digit indicating the
13249 indentation level required. A value of zero turns off this style check.
13250 The general style of required indentation is as specified by
13251 the examples in the Ada Reference Manual. Full line comments must be
13252 aligned with the @code{--} starting on a column that is a multiple of
13253 the alignment level, or they may be aligned the same way as the following
13254 non-blank line (this is useful when full line comments appear in the middle
13255 of a statement, or they may be aligned with the source line on the previous
13259 @geindex -gnatya (gcc)
13264 @item @code{-gnatya}
13266 @emph{Check attribute casing.}
13268 Attribute names, including the case of keywords such as @code{digits}
13269 used as attributes names, must be written in mixed case, that is, the
13270 initial letter and any letter following an underscore must be uppercase.
13271 All other letters must be lowercase.
13274 @geindex -gnatyA (gcc)
13279 @item @code{-gnatyA}
13281 @emph{Use of array index numbers in array attributes.}
13283 When using the array attributes First, Last, Range,
13284 or Length, the index number must be omitted for one-dimensional arrays
13285 and is required for multi-dimensional arrays.
13288 @geindex -gnatyb (gcc)
13293 @item @code{-gnatyb}
13295 @emph{Blanks not allowed at statement end.}
13297 Trailing blanks are not allowed at the end of statements. The purpose of this
13298 rule, together with h (no horizontal tabs), is to enforce a canonical format
13299 for the use of blanks to separate source tokens.
13302 @geindex -gnatyB (gcc)
13307 @item @code{-gnatyB}
13309 @emph{Check Boolean operators.}
13311 The use of AND/OR operators is not permitted except in the cases of modular
13312 operands, array operands, and simple stand-alone boolean variables or
13313 boolean constants. In all other cases @code{and then}/@cite{or else} are
13317 @geindex -gnatyc (gcc)
13322 @item @code{-gnatyc}
13324 @emph{Check comments, double space.}
13326 Comments must meet the following set of rules:
13332 The @code{--} that starts the column must either start in column one,
13333 or else at least one blank must precede this sequence.
13336 Comments that follow other tokens on a line must have at least one blank
13337 following the @code{--} at the start of the comment.
13340 Full line comments must have at least two blanks following the
13341 @code{--} that starts the comment, with the following exceptions.
13344 A line consisting only of the @code{--} characters, possibly preceded
13345 by blanks is permitted.
13348 A comment starting with @code{--x} where @code{x} is a special character
13350 This allows proper processing of the output from specialized tools
13351 such as @code{gnatprep} (where @code{--!} is used) and in earlier versions of the SPARK
13353 language (where @code{--#} is used). For the purposes of this rule, a
13354 special character is defined as being in one of the ASCII ranges
13355 @code{16#21#...16#2F#} or @code{16#3A#...16#3F#}.
13356 Note that this usage is not permitted
13357 in GNAT implementation units (i.e., when @code{-gnatg} is used).
13360 A line consisting entirely of minus signs, possibly preceded by blanks, is
13361 permitted. This allows the construction of box comments where lines of minus
13362 signs are used to form the top and bottom of the box.
13365 A comment that starts and ends with @code{--} is permitted as long as at
13366 least one blank follows the initial @code{--}. Together with the preceding
13367 rule, this allows the construction of box comments, as shown in the following
13371 ---------------------------
13372 -- This is a box comment --
13373 -- with two text lines. --
13374 ---------------------------
13379 @geindex -gnatyC (gcc)
13384 @item @code{-gnatyC}
13386 @emph{Check comments, single space.}
13388 This is identical to @code{c} except that only one space
13389 is required following the @code{--} of a comment instead of two.
13392 @geindex -gnatyd (gcc)
13397 @item @code{-gnatyd}
13399 @emph{Check no DOS line terminators present.}
13401 All lines must be terminated by a single ASCII.LF
13402 character (in particular the DOS line terminator sequence CR/LF is not
13406 @geindex -gnatye (gcc)
13411 @item @code{-gnatye}
13413 @emph{Check end/exit labels.}
13415 Optional labels on @code{end} statements ending subprograms and on
13416 @code{exit} statements exiting named loops, are required to be present.
13419 @geindex -gnatyf (gcc)
13424 @item @code{-gnatyf}
13426 @emph{No form feeds or vertical tabs.}
13428 Neither form feeds nor vertical tab characters are permitted
13429 in the source text.
13432 @geindex -gnatyg (gcc)
13437 @item @code{-gnatyg}
13439 @emph{GNAT style mode.}
13441 The set of style check switches is set to match that used by the GNAT sources.
13442 This may be useful when developing code that is eventually intended to be
13443 incorporated into GNAT. Currently this is equivalent to @code{-gnatwydISux})
13444 but additional style switches may be added to this set in the future without
13448 @geindex -gnatyh (gcc)
13453 @item @code{-gnatyh}
13455 @emph{No horizontal tabs.}
13457 Horizontal tab characters are not permitted in the source text.
13458 Together with the b (no blanks at end of line) check, this
13459 enforces a canonical form for the use of blanks to separate
13463 @geindex -gnatyi (gcc)
13468 @item @code{-gnatyi}
13470 @emph{Check if-then layout.}
13472 The keyword @code{then} must appear either on the same
13473 line as corresponding @code{if}, or on a line on its own, lined
13474 up under the @code{if}.
13477 @geindex -gnatyI (gcc)
13482 @item @code{-gnatyI}
13484 @emph{check mode IN keywords.}
13486 Mode @code{in} (the default mode) is not
13487 allowed to be given explicitly. @code{in out} is fine,
13488 but not @code{in} on its own.
13491 @geindex -gnatyk (gcc)
13496 @item @code{-gnatyk}
13498 @emph{Check keyword casing.}
13500 All keywords must be in lower case (with the exception of keywords
13501 such as @code{digits} used as attribute names to which this check
13505 @geindex -gnatyl (gcc)
13510 @item @code{-gnatyl}
13512 @emph{Check layout.}
13514 Layout of statement and declaration constructs must follow the
13515 recommendations in the Ada Reference Manual, as indicated by the
13516 form of the syntax rules. For example an @code{else} keyword must
13517 be lined up with the corresponding @code{if} keyword.
13519 There are two respects in which the style rule enforced by this check
13520 option are more liberal than those in the Ada Reference Manual. First
13521 in the case of record declarations, it is permissible to put the
13522 @code{record} keyword on the same line as the @code{type} keyword, and
13523 then the @code{end} in @code{end record} must line up under @code{type}.
13524 This is also permitted when the type declaration is split on two lines.
13525 For example, any of the following three layouts is acceptable:
13546 Second, in the case of a block statement, a permitted alternative
13547 is to put the block label on the same line as the @code{declare} or
13548 @code{begin} keyword, and then line the @code{end} keyword up under
13549 the block label. For example both the following are permitted:
13566 The same alternative format is allowed for loops. For example, both of
13567 the following are permitted:
13570 Clear : while J < 10 loop
13581 @geindex -gnatyLnnn (gcc)
13586 @item @code{-gnatyL}
13588 @emph{Set maximum nesting level.}
13590 The maximum level of nesting of constructs (including subprograms, loops,
13591 blocks, packages, and conditionals) may not exceed the given value
13592 @emph{nnn}. A value of zero disconnects this style check.
13595 @geindex -gnatym (gcc)
13600 @item @code{-gnatym}
13602 @emph{Check maximum line length.}
13604 The length of source lines must not exceed 79 characters, including
13605 any trailing blanks. The value of 79 allows convenient display on an
13606 80 character wide device or window, allowing for possible special
13607 treatment of 80 character lines. Note that this count is of
13608 characters in the source text. This means that a tab character counts
13609 as one character in this count and a wide character sequence counts as
13610 a single character (however many bytes are needed in the encoding).
13613 @geindex -gnatyMnnn (gcc)
13618 @item @code{-gnatyM}
13620 @emph{Set maximum line length.}
13622 The length of lines must not exceed the
13623 given value @emph{nnn}. The maximum value that can be specified is 32767.
13624 If neither style option for setting the line length is used, then the
13625 default is 255. This also controls the maximum length of lexical elements,
13626 where the only restriction is that they must fit on a single line.
13629 @geindex -gnatyn (gcc)
13634 @item @code{-gnatyn}
13636 @emph{Check casing of entities in Standard.}
13638 Any identifier from Standard must be cased
13639 to match the presentation in the Ada Reference Manual (for example,
13640 @code{Integer} and @code{ASCII.NUL}).
13643 @geindex -gnatyN (gcc)
13648 @item @code{-gnatyN}
13650 @emph{Turn off all style checks.}
13652 All style check options are turned off.
13655 @geindex -gnatyo (gcc)
13660 @item @code{-gnatyo}
13662 @emph{Check order of subprogram bodies.}
13664 All subprogram bodies in a given scope
13665 (e.g., a package body) must be in alphabetical order. The ordering
13666 rule uses normal Ada rules for comparing strings, ignoring casing
13667 of letters, except that if there is a trailing numeric suffix, then
13668 the value of this suffix is used in the ordering (e.g., Junk2 comes
13672 @geindex -gnatyO (gcc)
13677 @item @code{-gnatyO}
13679 @emph{Check that overriding subprograms are explicitly marked as such.}
13681 This applies to all subprograms of a derived type that override a primitive
13682 operation of the type, for both tagged and untagged types. In particular,
13683 the declaration of a primitive operation of a type extension that overrides
13684 an inherited operation must carry an overriding indicator. Another case is
13685 the declaration of a function that overrides a predefined operator (such
13686 as an equality operator).
13689 @geindex -gnatyp (gcc)
13694 @item @code{-gnatyp}
13696 @emph{Check pragma casing.}
13698 Pragma names must be written in mixed case, that is, the
13699 initial letter and any letter following an underscore must be uppercase.
13700 All other letters must be lowercase. An exception is that SPARK_Mode is
13701 allowed as an alternative for Spark_Mode.
13704 @geindex -gnatyr (gcc)
13709 @item @code{-gnatyr}
13711 @emph{Check references.}
13713 All identifier references must be cased in the same way as the
13714 corresponding declaration. No specific casing style is imposed on
13715 identifiers. The only requirement is for consistency of references
13719 @geindex -gnatys (gcc)
13724 @item @code{-gnatys}
13726 @emph{Check separate specs.}
13728 Separate declarations ('specs') are required for subprograms (a
13729 body is not allowed to serve as its own declaration). The only
13730 exception is that parameterless library level procedures are
13731 not required to have a separate declaration. This exception covers
13732 the most frequent form of main program procedures.
13735 @geindex -gnatyS (gcc)
13740 @item @code{-gnatyS}
13742 @emph{Check no statements after then/else.}
13744 No statements are allowed
13745 on the same line as a @code{then} or @code{else} keyword following the
13746 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
13747 affected, and a special exception allows a pragma to appear after @code{else}.
13750 @geindex -gnatyt (gcc)
13755 @item @code{-gnatyt}
13757 @emph{Check token spacing.}
13759 The following token spacing rules are enforced:
13765 The keywords @code{abs} and @code{not} must be followed by a space.
13768 The token @code{=>} must be surrounded by spaces.
13771 The token @code{<>} must be preceded by a space or a left parenthesis.
13774 Binary operators other than @code{**} must be surrounded by spaces.
13775 There is no restriction on the layout of the @code{**} binary operator.
13778 Colon must be surrounded by spaces.
13781 Colon-equal (assignment, initialization) must be surrounded by spaces.
13784 Comma must be the first non-blank character on the line, or be
13785 immediately preceded by a non-blank character, and must be followed
13789 If the token preceding a left parenthesis ends with a letter or digit, then
13790 a space must separate the two tokens.
13793 If the token following a right parenthesis starts with a letter or digit, then
13794 a space must separate the two tokens.
13797 A right parenthesis must either be the first non-blank character on
13798 a line, or it must be preceded by a non-blank character.
13801 A semicolon must not be preceded by a space, and must not be followed by
13802 a non-blank character.
13805 A unary plus or minus may not be followed by a space.
13808 A vertical bar must be surrounded by spaces.
13811 Exactly one blank (and no other white space) must appear between
13812 a @code{not} token and a following @code{in} token.
13815 @geindex -gnatyu (gcc)
13820 @item @code{-gnatyu}
13822 @emph{Check unnecessary blank lines.}
13824 Unnecessary blank lines are not allowed. A blank line is considered
13825 unnecessary if it appears at the end of the file, or if more than
13826 one blank line occurs in sequence.
13829 @geindex -gnatyx (gcc)
13834 @item @code{-gnatyx}
13836 @emph{Check extra parentheses.}
13838 Unnecessary extra level of parentheses (C-style) are not allowed
13839 around conditions in @code{if} statements, @code{while} statements and
13840 @code{exit} statements.
13843 @geindex -gnatyy (gcc)
13848 @item @code{-gnatyy}
13850 @emph{Set all standard style check options.}
13852 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
13853 options enabled with the exception of @code{-gnatyB}, @code{-gnatyd},
13854 @code{-gnatyI}, @code{-gnatyLnnn}, @code{-gnatyo}, @code{-gnatyO},
13855 @code{-gnatyS}, @code{-gnatyu}, and @code{-gnatyx}.
13858 @geindex -gnaty- (gcc)
13863 @item @code{-gnaty-}
13865 @emph{Remove style check options.}
13867 This causes any subsequent options in the string to act as canceling the
13868 corresponding style check option. To cancel maximum nesting level control,
13869 use the @code{L} parameter without any integer value after that, because any
13870 digit following @emph{-} in the parameter string of the @code{-gnaty}
13871 option will be treated as canceling the indentation check. The same is true
13872 for the @code{M} parameter. @code{y} and @code{N} parameters are not
13873 allowed after @emph{-}.
13876 @geindex -gnaty+ (gcc)
13881 @item @code{-gnaty+}
13883 @emph{Enable style check options.}
13885 This causes any subsequent options in the string to enable the corresponding
13886 style check option. That is, it cancels the effect of a previous -,
13890 @c end of switch description (leave this comment to ease automatic parsing for
13894 In the above rules, appearing in column one is always permitted, that is,
13895 counts as meeting either a requirement for a required preceding space,
13896 or as meeting a requirement for no preceding space.
13898 Appearing at the end of a line is also always permitted, that is, counts
13899 as meeting either a requirement for a following space, or as meeting
13900 a requirement for no following space.
13902 If any of these style rules is violated, a message is generated giving
13903 details on the violation. The initial characters of such messages are
13904 always '@cite{(style)}'. Note that these messages are treated as warning
13905 messages, so they normally do not prevent the generation of an object
13906 file. The @code{-gnatwe} switch can be used to treat warning messages,
13907 including style messages, as fatal errors.
13909 The switch @code{-gnaty} on its own (that is not
13910 followed by any letters or digits) is equivalent
13911 to the use of @code{-gnatyy} as described above, that is all
13912 built-in standard style check options are enabled.
13914 The switch @code{-gnatyN} clears any previously set style checks.
13916 @node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
13917 @anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{f9}@anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{104}
13918 @subsection Run-Time Checks
13921 @geindex Division by zero
13923 @geindex Access before elaboration
13926 @geindex division by zero
13929 @geindex access before elaboration
13932 @geindex stack overflow checking
13934 By default, the following checks are suppressed: stack overflow
13935 checks, and checks for access before elaboration on subprogram
13936 calls. All other checks, including overflow checks, range checks and
13937 array bounds checks, are turned on by default. The following @code{gcc}
13938 switches refine this default behavior.
13940 @geindex -gnatp (gcc)
13945 @item @code{-gnatp}
13947 @geindex Suppressing checks
13950 @geindex suppressing
13952 This switch causes the unit to be compiled
13953 as though @code{pragma Suppress (All_checks)}
13954 had been present in the source. Validity checks are also eliminated (in
13955 other words @code{-gnatp} also implies @code{-gnatVn}.
13956 Use this switch to improve the performance
13957 of the code at the expense of safety in the presence of invalid data or
13960 Note that when checks are suppressed, the compiler is allowed, but not
13961 required, to omit the checking code. If the run-time cost of the
13962 checking code is zero or near-zero, the compiler will generate it even
13963 if checks are suppressed. In particular, if the compiler can prove
13964 that a certain check will necessarily fail, it will generate code to
13965 do an unconditional 'raise', even if checks are suppressed. The
13966 compiler warns in this case. Another case in which checks may not be
13967 eliminated is when they are embedded in certain run time routines such
13968 as math library routines.
13970 Of course, run-time checks are omitted whenever the compiler can prove
13971 that they will not fail, whether or not checks are suppressed.
13973 Note that if you suppress a check that would have failed, program
13974 execution is erroneous, which means the behavior is totally
13975 unpredictable. The program might crash, or print wrong answers, or
13976 do anything else. It might even do exactly what you wanted it to do
13977 (and then it might start failing mysteriously next week or next
13978 year). The compiler will generate code based on the assumption that
13979 the condition being checked is true, which can result in erroneous
13980 execution if that assumption is wrong.
13982 The checks subject to suppression include all the checks defined by the Ada
13983 standard, the additional implementation defined checks @code{Alignment_Check},
13984 @code{Duplicated_Tag_Check}, @code{Predicate_Check}, @code{Container_Checks}, @code{Tampering_Check},
13985 and @code{Validity_Check}, as well as any checks introduced using @code{pragma Check_Name}.
13986 Note that @code{Atomic_Synchronization} is not automatically suppressed by use of this option.
13988 If the code depends on certain checks being active, you can use
13989 pragma @code{Unsuppress} either as a configuration pragma or as
13990 a local pragma to make sure that a specified check is performed
13991 even if @code{gnatp} is specified.
13993 The @code{-gnatp} switch has no effect if a subsequent
13994 @code{-gnat-p} switch appears.
13997 @geindex -gnat-p (gcc)
13999 @geindex Suppressing checks
14002 @geindex suppressing
14009 @item @code{-gnat-p}
14011 This switch cancels the effect of a previous @code{gnatp} switch.
14014 @geindex -gnato?? (gcc)
14016 @geindex Overflow checks
14018 @geindex Overflow mode
14026 @item @code{-gnato??}
14028 This switch controls the mode used for computing intermediate
14029 arithmetic integer operations, and also enables overflow checking.
14030 For a full description of overflow mode and checking control, see
14031 the 'Overflow Check Handling in GNAT' appendix in this
14034 Overflow checks are always enabled by this switch. The argument
14035 controls the mode, using the codes
14040 @item @emph{1 = STRICT}
14042 In STRICT mode, intermediate operations are always done using the
14043 base type, and overflow checking ensures that the result is within
14044 the base type range.
14046 @item @emph{2 = MINIMIZED}
14048 In MINIMIZED mode, overflows in intermediate operations are avoided
14049 where possible by using a larger integer type for the computation
14050 (typically @code{Long_Long_Integer}). Overflow checking ensures that
14051 the result fits in this larger integer type.
14053 @item @emph{3 = ELIMINATED}
14055 In ELIMINATED mode, overflows in intermediate operations are avoided
14056 by using multi-precision arithmetic. In this case, overflow checking
14057 has no effect on intermediate operations (since overflow is impossible).
14060 If two digits are present after @code{-gnato} then the first digit
14061 sets the mode for expressions outside assertions, and the second digit
14062 sets the mode for expressions within assertions. Here assertions is used
14063 in the technical sense (which includes for example precondition and
14064 postcondition expressions).
14066 If one digit is present, the corresponding mode is applicable to both
14067 expressions within and outside assertion expressions.
14069 If no digits are present, the default is to enable overflow checks
14070 and set STRICT mode for both kinds of expressions. This is compatible
14071 with the use of @code{-gnato} in previous versions of GNAT.
14073 @geindex Machine_Overflows
14075 Note that the @code{-gnato??} switch does not affect the code generated
14076 for any floating-point operations; it applies only to integer semantics.
14077 For floating-point, GNAT has the @code{Machine_Overflows}
14078 attribute set to @code{False} and the normal mode of operation is to
14079 generate IEEE NaN and infinite values on overflow or invalid operations
14080 (such as dividing 0.0 by 0.0).
14082 The reason that we distinguish overflow checking from other kinds of
14083 range constraint checking is that a failure of an overflow check, unlike
14084 for example the failure of a range check, can result in an incorrect
14085 value, but cannot cause random memory destruction (like an out of range
14086 subscript), or a wild jump (from an out of range case value). Overflow
14087 checking is also quite expensive in time and space, since in general it
14088 requires the use of double length arithmetic.
14090 Note again that the default is @code{-gnato11} (equivalent to @code{-gnato1}),
14091 so overflow checking is performed in STRICT mode by default.
14094 @geindex -gnatE (gcc)
14096 @geindex Elaboration checks
14099 @geindex elaboration
14104 @item @code{-gnatE}
14106 Enables dynamic checks for access-before-elaboration
14107 on subprogram calls and generic instantiations.
14108 Note that @code{-gnatE} is not necessary for safety, because in the
14109 default mode, GNAT ensures statically that the checks would not fail.
14110 For full details of the effect and use of this switch,
14111 @ref{1c,,Compiling with gcc}.
14114 @geindex -fstack-check (gcc)
14116 @geindex Stack Overflow Checking
14119 @geindex stack overflow checking
14124 @item @code{-fstack-check}
14126 Activates stack overflow checking. For full details of the effect and use of
14127 this switch see @ref{f4,,Stack Overflow Checking}.
14130 @geindex Unsuppress
14132 The setting of these switches only controls the default setting of the
14133 checks. You may modify them using either @code{Suppress} (to remove
14134 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
14135 the program source.
14137 @node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
14138 @anchor{gnat_ugn/building_executable_programs_with_gnat id20}@anchor{105}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-syntax-checking}@anchor{106}
14139 @subsection Using @code{gcc} for Syntax Checking
14142 @geindex -gnats (gcc)
14147 @item @code{-gnats}
14149 The @code{s} stands for 'syntax'.
14151 Run GNAT in syntax checking only mode. For
14152 example, the command
14155 $ gcc -c -gnats x.adb
14158 compiles file @code{x.adb} in syntax-check-only mode. You can check a
14159 series of files in a single command
14160 , and can use wild cards to specify such a group of files.
14161 Note that you must specify the @code{-c} (compile
14162 only) flag in addition to the @code{-gnats} flag.
14164 You may use other switches in conjunction with @code{-gnats}. In
14165 particular, @code{-gnatl} and @code{-gnatv} are useful to control the
14166 format of any generated error messages.
14168 When the source file is empty or contains only empty lines and/or comments,
14169 the output is a warning:
14172 $ gcc -c -gnats -x ada toto.txt
14173 toto.txt:1:01: warning: empty file, contains no compilation units
14177 Otherwise, the output is simply the error messages, if any. No object file or
14178 ALI file is generated by a syntax-only compilation. Also, no units other
14179 than the one specified are accessed. For example, if a unit @code{X}
14180 @emph{with}s a unit @code{Y}, compiling unit @code{X} in syntax
14181 check only mode does not access the source file containing unit
14184 @geindex Multiple units
14185 @geindex syntax checking
14187 Normally, GNAT allows only a single unit in a source file. However, this
14188 restriction does not apply in syntax-check-only mode, and it is possible
14189 to check a file containing multiple compilation units concatenated
14190 together. This is primarily used by the @code{gnatchop} utility
14191 (@ref{36,,Renaming Files with gnatchop}).
14194 @node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
14195 @anchor{gnat_ugn/building_executable_programs_with_gnat id21}@anchor{107}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-semantic-checking}@anchor{108}
14196 @subsection Using @code{gcc} for Semantic Checking
14199 @geindex -gnatc (gcc)
14204 @item @code{-gnatc}
14206 The @code{c} stands for 'check'.
14207 Causes the compiler to operate in semantic check mode,
14208 with full checking for all illegalities specified in the
14209 Ada Reference Manual, but without generation of any object code
14210 (no object file is generated).
14212 Because dependent files must be accessed, you must follow the GNAT
14213 semantic restrictions on file structuring to operate in this mode:
14219 The needed source files must be accessible
14220 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
14223 Each file must contain only one compilation unit.
14226 The file name and unit name must match (@ref{52,,File Naming Rules}).
14229 The output consists of error messages as appropriate. No object file is
14230 generated. An @code{ALI} file is generated for use in the context of
14231 cross-reference tools, but this file is marked as not being suitable
14232 for binding (since no object file is generated).
14233 The checking corresponds exactly to the notion of
14234 legality in the Ada Reference Manual.
14236 Any unit can be compiled in semantics-checking-only mode, including
14237 units that would not normally be compiled (subunits,
14238 and specifications where a separate body is present).
14241 @node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
14242 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-different-versions-of-ada}@anchor{6}@anchor{gnat_ugn/building_executable_programs_with_gnat id22}@anchor{109}
14243 @subsection Compiling Different Versions of Ada
14246 The switches described in this section allow you to explicitly specify
14247 the version of the Ada language that your programs are written in.
14248 The default mode is Ada 2012,
14249 but you can also specify Ada 95, Ada 2005 mode, or
14250 indicate Ada 83 compatibility mode.
14252 @geindex Compatibility with Ada 83
14254 @geindex -gnat83 (gcc)
14257 @geindex Ada 83 tests
14259 @geindex Ada 83 mode
14264 @item @code{-gnat83} (Ada 83 Compatibility Mode)
14266 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
14267 specifies that the program is to be compiled in Ada 83 mode. With
14268 @code{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
14269 semantics where this can be done easily.
14270 It is not possible to guarantee this switch does a perfect
14271 job; some subtle tests, such as are
14272 found in earlier ACVC tests (and that have been removed from the ACATS suite
14273 for Ada 95), might not compile correctly.
14274 Nevertheless, this switch may be useful in some circumstances, for example
14275 where, due to contractual reasons, existing code needs to be maintained
14276 using only Ada 83 features.
14278 With few exceptions (most notably the need to use @code{<>} on
14280 @geindex Generic formal parameters
14281 generic formal parameters,
14282 the use of the new Ada 95 / Ada 2005
14283 reserved words, and the use of packages
14284 with optional bodies), it is not necessary to specify the
14285 @code{-gnat83} switch when compiling Ada 83 programs, because, with rare
14286 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
14287 a correct Ada 83 program is usually also a correct program
14288 in these later versions of the language standard. For further information
14289 please refer to the @emph{Compatibility and Porting Guide} chapter in the
14290 @cite{GNAT Reference Manual}.
14293 @geindex -gnat95 (gcc)
14295 @geindex Ada 95 mode
14300 @item @code{-gnat95} (Ada 95 mode)
14302 This switch directs the compiler to implement the Ada 95 version of the
14304 Since Ada 95 is almost completely upwards
14305 compatible with Ada 83, Ada 83 programs may generally be compiled using
14306 this switch (see the description of the @code{-gnat83} switch for further
14307 information about Ada 83 mode).
14308 If an Ada 2005 program is compiled in Ada 95 mode,
14309 uses of the new Ada 2005 features will cause error
14310 messages or warnings.
14312 This switch also can be used to cancel the effect of a previous
14313 @code{-gnat83}, @code{-gnat05/2005}, or @code{-gnat12/2012}
14314 switch earlier in the command line.
14317 @geindex -gnat05 (gcc)
14319 @geindex -gnat2005 (gcc)
14321 @geindex Ada 2005 mode
14326 @item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
14328 This switch directs the compiler to implement the Ada 2005 version of the
14329 language, as documented in the official Ada standards document.
14330 Since Ada 2005 is almost completely upwards
14331 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
14332 may generally be compiled using this switch (see the description of the
14333 @code{-gnat83} and @code{-gnat95} switches for further
14337 @geindex -gnat12 (gcc)
14339 @geindex -gnat2012 (gcc)
14341 @geindex Ada 2012 mode
14346 @item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
14348 This switch directs the compiler to implement the Ada 2012 version of the
14349 language (also the default).
14350 Since Ada 2012 is almost completely upwards
14351 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
14352 Ada 83 and Ada 95 programs
14353 may generally be compiled using this switch (see the description of the
14354 @code{-gnat83}, @code{-gnat95}, and @code{-gnat05/2005} switches
14355 for further information).
14358 @geindex -gnatX (gcc)
14360 @geindex Ada language extensions
14362 @geindex GNAT extensions
14367 @item @code{-gnatX} (Enable GNAT Extensions)
14369 This switch directs the compiler to implement the latest version of the
14370 language (currently Ada 2012) and also to enable certain GNAT implementation
14371 extensions that are not part of any Ada standard. For a full list of these
14372 extensions, see the GNAT reference manual.
14375 @node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14376 @anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{10a}@anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{48}
14377 @subsection Character Set Control
14380 @geindex -gnati (gcc)
14385 @item @code{-gnati@emph{c}}
14387 Normally GNAT recognizes the Latin-1 character set in source program
14388 identifiers, as described in the Ada Reference Manual.
14390 GNAT to recognize alternate character sets in identifiers. @code{c} is a
14391 single character indicating the character set, as follows:
14394 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14401 ISO 8859-1 (Latin-1) identifiers
14409 ISO 8859-2 (Latin-2) letters allowed in identifiers
14417 ISO 8859-3 (Latin-3) letters allowed in identifiers
14425 ISO 8859-4 (Latin-4) letters allowed in identifiers
14433 ISO 8859-5 (Cyrillic) letters allowed in identifiers
14441 ISO 8859-15 (Latin-9) letters allowed in identifiers
14449 IBM PC letters (code page 437) allowed in identifiers
14457 IBM PC letters (code page 850) allowed in identifiers
14465 Full upper-half codes allowed in identifiers
14473 No upper-half codes allowed in identifiers
14481 Wide-character codes (that is, codes greater than 255)
14482 allowed in identifiers
14487 See @ref{3e,,Foreign Language Representation} for full details on the
14488 implementation of these character sets.
14491 @geindex -gnatW (gcc)
14496 @item @code{-gnatW@emph{e}}
14498 Specify the method of encoding for wide characters.
14499 @code{e} is one of the following:
14502 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14509 Hex encoding (brackets coding also recognized)
14517 Upper half encoding (brackets encoding also recognized)
14525 Shift/JIS encoding (brackets encoding also recognized)
14533 EUC encoding (brackets encoding also recognized)
14541 UTF-8 encoding (brackets encoding also recognized)
14549 Brackets encoding only (default value)
14554 For full details on these encoding
14555 methods see @ref{4e,,Wide_Character Encodings}.
14556 Note that brackets coding is always accepted, even if one of the other
14557 options is specified, so for example @code{-gnatW8} specifies that both
14558 brackets and UTF-8 encodings will be recognized. The units that are
14559 with'ed directly or indirectly will be scanned using the specified
14560 representation scheme, and so if one of the non-brackets scheme is
14561 used, it must be used consistently throughout the program. However,
14562 since brackets encoding is always recognized, it may be conveniently
14563 used in standard libraries, allowing these libraries to be used with
14564 any of the available coding schemes.
14566 Note that brackets encoding only applies to program text. Within comments,
14567 brackets are considered to be normal graphic characters, and bracket sequences
14568 are never recognized as wide characters.
14570 If no @code{-gnatW?} parameter is present, then the default
14571 representation is normally Brackets encoding only. However, if the
14572 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14573 byte order mark or BOM for UTF-8), then these three characters are
14574 skipped and the default representation for the file is set to UTF-8.
14576 Note that the wide character representation that is specified (explicitly
14577 or by default) for the main program also acts as the default encoding used
14578 for Wide_Text_IO files if not specifically overridden by a WCEM form
14582 When no @code{-gnatW?} is specified, then characters (other than wide
14583 characters represented using brackets notation) are treated as 8-bit
14584 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14585 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14586 characters in the range 16#00#..16#1F# are not accepted in program text
14587 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14588 in program text, but allowed and ignored in comments. Note in particular
14589 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14590 as an end of line in this default mode. If your source program contains
14591 instances of the NEL character used as a line terminator,
14592 you must use UTF-8 encoding for the whole
14593 source program. In default mode, all lines must be ended by a standard
14594 end of line sequence (CR, CR/LF, or LF).
14596 Note that the convention of simply accepting all upper half characters in
14597 comments means that programs that use standard ASCII for program text, but
14598 UTF-8 encoding for comments are accepted in default mode, providing that the
14599 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14600 This is a common mode for many programs with foreign language comments.
14602 @node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14603 @anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{10b}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{10c}
14604 @subsection File Naming Control
14607 @geindex -gnatk (gcc)
14612 @item @code{-gnatk@emph{n}}
14614 Activates file name 'krunching'. @code{n}, a decimal integer in the range
14615 1-999, indicates the maximum allowable length of a file name (not
14616 including the @code{.ads} or @code{.adb} extension). The default is not
14617 to enable file name krunching.
14619 For the source file naming rules, @ref{52,,File Naming Rules}.
14622 @node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14623 @anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{10d}@anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{10e}
14624 @subsection Subprogram Inlining Control
14627 @geindex -gnatn (gcc)
14632 @item @code{-gnatn[12]}
14634 The @code{n} here is intended to suggest the first syllable of the word 'inline'.
14635 GNAT recognizes and processes @code{Inline} pragmas. However, for inlining to
14636 actually occur, optimization must be enabled and, by default, inlining of
14637 subprograms across modules is not performed. If you want to additionally
14638 enable inlining of subprograms specified by pragma @code{Inline} across modules,
14639 you must also specify this switch.
14641 In the absence of this switch, GNAT does not attempt inlining across modules
14642 and does not access the bodies of subprograms for which @code{pragma Inline} is
14643 specified if they are not in the current unit.
14645 You can optionally specify the inlining level: 1 for moderate inlining across
14646 modules, which is a good compromise between compilation times and performances
14647 at run time, or 2 for full inlining across modules, which may bring about
14648 longer compilation times. If no inlining level is specified, the compiler will
14649 pick it based on the optimization level: 1 for @code{-O1}, @code{-O2} or
14650 @code{-Os} and 2 for @code{-O3}.
14652 If you specify this switch the compiler will access these bodies,
14653 creating an extra source dependency for the resulting object file, and
14654 where possible, the call will be inlined.
14655 For further details on when inlining is possible
14656 see @ref{10f,,Inlining of Subprograms}.
14659 @geindex -gnatN (gcc)
14664 @item @code{-gnatN}
14666 This switch activates front-end inlining which also
14667 generates additional dependencies.
14669 When using a gcc-based back end (in practice this means using any version
14670 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
14671 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
14672 Historically front end inlining was more extensive than the gcc back end
14673 inlining, but that is no longer the case.
14676 @node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14677 @anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{110}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{111}
14678 @subsection Auxiliary Output Control
14681 @geindex -gnatt (gcc)
14683 @geindex Writing internal trees
14685 @geindex Internal trees
14686 @geindex writing to file
14691 @item @code{-gnatt}
14693 Causes GNAT to write the internal tree for a unit to a file (with the
14694 extension @code{.adt}.
14695 This not normally required, but is used by separate analysis tools.
14697 these tools do the necessary compilations automatically, so you should
14698 not have to specify this switch in normal operation.
14699 Note that the combination of switches @code{-gnatct}
14700 generates a tree in the form required by ASIS applications.
14703 @geindex -gnatu (gcc)
14708 @item @code{-gnatu}
14710 Print a list of units required by this compilation on @code{stdout}.
14711 The listing includes all units on which the unit being compiled depends
14712 either directly or indirectly.
14715 @geindex -pass-exit-codes (gcc)
14720 @item @code{-pass-exit-codes}
14722 If this switch is not used, the exit code returned by @code{gcc} when
14723 compiling multiple files indicates whether all source files have
14724 been successfully used to generate object files or not.
14726 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
14727 exit status and allows an integrated development environment to better
14728 react to a compilation failure. Those exit status are:
14731 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14738 There was an error in at least one source file.
14746 At least one source file did not generate an object file.
14754 The compiler died unexpectedly (internal error for example).
14762 An object file has been generated for every source file.
14768 @node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
14769 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{112}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{113}
14770 @subsection Debugging Control
14775 @geindex Debugging options
14778 @geindex -gnatd (gcc)
14783 @item @code{-gnatd@emph{x}}
14785 Activate internal debugging switches. @code{x} is a letter or digit, or
14786 string of letters or digits, which specifies the type of debugging
14787 outputs desired. Normally these are used only for internal development
14788 or system debugging purposes. You can find full documentation for these
14789 switches in the body of the @code{Debug} unit in the compiler source
14790 file @code{debug.adb}.
14793 @geindex -gnatG (gcc)
14798 @item @code{-gnatG[=@emph{nn}]}
14800 This switch causes the compiler to generate auxiliary output containing
14801 a pseudo-source listing of the generated expanded code. Like most Ada
14802 compilers, GNAT works by first transforming the high level Ada code into
14803 lower level constructs. For example, tasking operations are transformed
14804 into calls to the tasking run-time routines. A unique capability of GNAT
14805 is to list this expanded code in a form very close to normal Ada source.
14806 This is very useful in understanding the implications of various Ada
14807 usage on the efficiency of the generated code. There are many cases in
14808 Ada (e.g., the use of controlled types), where simple Ada statements can
14809 generate a lot of run-time code. By using @code{-gnatG} you can identify
14810 these cases, and consider whether it may be desirable to modify the coding
14811 approach to improve efficiency.
14813 The optional parameter @code{nn} if present after -gnatG specifies an
14814 alternative maximum line length that overrides the normal default of 72.
14815 This value is in the range 40-999999, values less than 40 being silently
14816 reset to 40. The equal sign is optional.
14818 The format of the output is very similar to standard Ada source, and is
14819 easily understood by an Ada programmer. The following special syntactic
14820 additions correspond to low level features used in the generated code that
14821 do not have any exact analogies in pure Ada source form. The following
14822 is a partial list of these special constructions. See the spec
14823 of package @code{Sprint} in file @code{sprint.ads} for a full list.
14825 @geindex -gnatL (gcc)
14827 If the switch @code{-gnatL} is used in conjunction with
14828 @code{-gnatG}, then the original source lines are interspersed
14829 in the expanded source (as comment lines with the original line number).
14834 @item @code{new @emph{xxx} [storage_pool = @emph{yyy}]}
14836 Shows the storage pool being used for an allocator.
14838 @item @code{at end @emph{procedure-name};}
14840 Shows the finalization (cleanup) procedure for a scope.
14842 @item @code{(if @emph{expr} then @emph{expr} else @emph{expr})}
14844 Conditional expression equivalent to the @code{x?y:z} construction in C.
14846 @item @code{@emph{target}^(@emph{source})}
14848 A conversion with floating-point truncation instead of rounding.
14850 @item @code{@emph{target}?(@emph{source})}
14852 A conversion that bypasses normal Ada semantic checking. In particular
14853 enumeration types and fixed-point types are treated simply as integers.
14855 @item @code{@emph{target}?^(@emph{source})}
14857 Combines the above two cases.
14860 @code{@emph{x} #/ @emph{y}}
14862 @code{@emph{x} #mod @emph{y}}
14864 @code{@emph{x} # @emph{y}}
14869 @item @code{@emph{x} #rem @emph{y}}
14871 A division or multiplication of fixed-point values which are treated as
14872 integers without any kind of scaling.
14874 @item @code{free @emph{expr} [storage_pool = @emph{xxx}]}
14876 Shows the storage pool associated with a @code{free} statement.
14878 @item @code{[subtype or type declaration]}
14880 Used to list an equivalent declaration for an internally generated
14881 type that is referenced elsewhere in the listing.
14883 @item @code{freeze @emph{type-name} [@emph{actions}]}
14885 Shows the point at which @code{type-name} is frozen, with possible
14886 associated actions to be performed at the freeze point.
14888 @item @code{reference @emph{itype}}
14890 Reference (and hence definition) to internal type @code{itype}.
14892 @item @code{@emph{function-name}! (@emph{arg}, @emph{arg}, @emph{arg})}
14894 Intrinsic function call.
14896 @item @code{@emph{label-name} : label}
14898 Declaration of label @code{labelname}.
14900 @item @code{#$ @emph{subprogram-name}}
14902 An implicit call to a run-time support routine
14903 (to meet the requirement of H.3.1(9) in a
14904 convenient manner).
14906 @item @code{@emph{expr} && @emph{expr} && @emph{expr} ... && @emph{expr}}
14908 A multiple concatenation (same effect as @code{expr} & @code{expr} &
14909 @code{expr}, but handled more efficiently).
14911 @item @code{[constraint_error]}
14913 Raise the @code{Constraint_Error} exception.
14915 @item @code{@emph{expression}'reference}
14917 A pointer to the result of evaluating @{expression@}.
14919 @item @code{@emph{target-type}!(@emph{source-expression})}
14921 An unchecked conversion of @code{source-expression} to @code{target-type}.
14923 @item @code{[@emph{numerator}/@emph{denominator}]}
14925 Used to represent internal real literals (that) have no exact
14926 representation in base 2-16 (for example, the result of compile time
14927 evaluation of the expression 1.0/27.0).
14931 @geindex -gnatD (gcc)
14936 @item @code{-gnatD[=nn]}
14938 When used in conjunction with @code{-gnatG}, this switch causes
14939 the expanded source, as described above for
14940 @code{-gnatG} to be written to files with names
14941 @code{xxx.dg}, where @code{xxx} is the normal file name,
14942 instead of to the standard output file. For
14943 example, if the source file name is @code{hello.adb}, then a file
14944 @code{hello.adb.dg} will be written. The debugging
14945 information generated by the @code{gcc} @code{-g} switch
14946 will refer to the generated @code{xxx.dg} file. This allows
14947 you to do source level debugging using the generated code which is
14948 sometimes useful for complex code, for example to find out exactly
14949 which part of a complex construction raised an exception. This switch
14950 also suppresses generation of cross-reference information (see
14951 @code{-gnatx}) since otherwise the cross-reference information
14952 would refer to the @code{.dg} file, which would cause
14953 confusion since this is not the original source file.
14955 Note that @code{-gnatD} actually implies @code{-gnatG}
14956 automatically, so it is not necessary to give both options.
14957 In other words @code{-gnatD} is equivalent to @code{-gnatDG}).
14959 @geindex -gnatL (gcc)
14961 If the switch @code{-gnatL} is used in conjunction with
14962 @code{-gnatDG}, then the original source lines are interspersed
14963 in the expanded source (as comment lines with the original line number).
14965 The optional parameter @code{nn} if present after -gnatD specifies an
14966 alternative maximum line length that overrides the normal default of 72.
14967 This value is in the range 40-999999, values less than 40 being silently
14968 reset to 40. The equal sign is optional.
14971 @geindex -gnatr (gcc)
14973 @geindex pragma Restrictions
14978 @item @code{-gnatr}
14980 This switch causes pragma Restrictions to be treated as Restriction_Warnings
14981 so that violation of restrictions causes warnings rather than illegalities.
14982 This is useful during the development process when new restrictions are added
14983 or investigated. The switch also causes pragma Profile to be treated as
14984 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
14985 restriction warnings rather than restrictions.
14988 @geindex -gnatR (gcc)
14993 @item @code{-gnatR[0|1|2|3][e][m][s]}
14995 This switch controls output from the compiler of a listing showing
14996 representation information for declared types, objects and subprograms.
14997 For @code{-gnatR0}, no information is output (equivalent to omitting
14998 the @code{-gnatR} switch). For @code{-gnatR1} (which is the default,
14999 so @code{-gnatR} with no parameter has the same effect), size and
15000 alignment information is listed for declared array and record types.
15001 For @code{-gnatR2}, size and alignment information is listed for all
15002 declared types and objects. The @code{Linker_Section} is also listed for any
15003 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
15004 latter case occurs for objects of a type for which a @code{Linker_Section}
15007 For @code{-gnatR3}, symbolic expressions for values that are computed
15008 at run time for records are included. These symbolic expressions have
15009 a mostly obvious format with #n being used to represent the value of the
15010 n'th discriminant. See source files @code{repinfo.ads/adb} in the
15011 GNAT sources for full details on the format of @code{-gnatR3} output.
15013 If the switch is followed by an @code{e} (e.g. @code{-gnatR2e}), then
15014 extended representation information for record sub-components of records
15017 If the switch is followed by an @code{m} (e.g. @code{-gnatRm}), then
15018 subprogram conventions and parameter passing mechanisms for all the
15019 subprograms are included.
15021 If the switch is followed by an @code{s} (e.g., @code{-gnatR3s}), then
15022 the output is to a file with the name @code{file.rep} where file is
15023 the name of the corresponding source file.
15025 Note that it is possible for record components to have zero size. In
15026 this case, the component clause uses an obvious extension of permitted
15027 Ada syntax, for example @code{at 0 range 0 .. -1}.
15030 @geindex -gnatS (gcc)
15035 @item @code{-gnatS}
15037 The use of the switch @code{-gnatS} for an
15038 Ada compilation will cause the compiler to output a
15039 representation of package Standard in a form very
15040 close to standard Ada. It is not quite possible to
15041 do this entirely in standard Ada (since new
15042 numeric base types cannot be created in standard
15043 Ada), but the output is easily
15044 readable to any Ada programmer, and is useful to
15045 determine the characteristics of target dependent
15046 types in package Standard.
15049 @geindex -gnatx (gcc)
15054 @item @code{-gnatx}
15056 Normally the compiler generates full cross-referencing information in
15057 the @code{ALI} file. This information is used by a number of tools,
15058 including @code{gnatfind} and @code{gnatxref}. The @code{-gnatx} switch
15059 suppresses this information. This saves some space and may slightly
15060 speed up compilation, but means that these tools cannot be used.
15063 @node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
15064 @anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{114}@anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{115}
15065 @subsection Exception Handling Control
15068 GNAT uses two methods for handling exceptions at run-time. The
15069 @code{setjmp/longjmp} method saves the context when entering
15070 a frame with an exception handler. Then when an exception is
15071 raised, the context can be restored immediately, without the
15072 need for tracing stack frames. This method provides very fast
15073 exception propagation, but introduces significant overhead for
15074 the use of exception handlers, even if no exception is raised.
15076 The other approach is called 'zero cost' exception handling.
15077 With this method, the compiler builds static tables to describe
15078 the exception ranges. No dynamic code is required when entering
15079 a frame containing an exception handler. When an exception is
15080 raised, the tables are used to control a back trace of the
15081 subprogram invocation stack to locate the required exception
15082 handler. This method has considerably poorer performance for
15083 the propagation of exceptions, but there is no overhead for
15084 exception handlers if no exception is raised. Note that in this
15085 mode and in the context of mixed Ada and C/C++ programming,
15086 to propagate an exception through a C/C++ code, the C/C++ code
15087 must be compiled with the @code{-funwind-tables} GCC's
15090 The following switches may be used to control which of the
15091 two exception handling methods is used.
15093 @geindex --RTS=sjlj (gnatmake)
15098 @item @code{--RTS=sjlj}
15100 This switch causes the setjmp/longjmp run-time (when available) to be used
15101 for exception handling. If the default
15102 mechanism for the target is zero cost exceptions, then
15103 this switch can be used to modify this default, and must be
15104 used for all units in the partition.
15105 This option is rarely used. One case in which it may be
15106 advantageous is if you have an application where exception
15107 raising is common and the overall performance of the
15108 application is improved by favoring exception propagation.
15111 @geindex --RTS=zcx (gnatmake)
15113 @geindex Zero Cost Exceptions
15118 @item @code{--RTS=zcx}
15120 This switch causes the zero cost approach to be used
15121 for exception handling. If this is the default mechanism for the
15122 target (see below), then this switch is unneeded. If the default
15123 mechanism for the target is setjmp/longjmp exceptions, then
15124 this switch can be used to modify this default, and must be
15125 used for all units in the partition.
15126 This option can only be used if the zero cost approach
15127 is available for the target in use, otherwise it will generate an error.
15130 The same option @code{--RTS} must be used both for @code{gcc}
15131 and @code{gnatbind}. Passing this option to @code{gnatmake}
15132 (@ref{dc,,Switches for gnatmake}) will ensure the required consistency
15133 through the compilation and binding steps.
15135 @node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
15136 @anchor{gnat_ugn/building_executable_programs_with_gnat id29}@anchor{116}@anchor{gnat_ugn/building_executable_programs_with_gnat units-to-sources-mapping-files}@anchor{f7}
15137 @subsection Units to Sources Mapping Files
15140 @geindex -gnatem (gcc)
15145 @item @code{-gnatem=@emph{path}}
15147 A mapping file is a way to communicate to the compiler two mappings:
15148 from unit names to file names (without any directory information) and from
15149 file names to path names (with full directory information). These mappings
15150 are used by the compiler to short-circuit the path search.
15152 The use of mapping files is not required for correct operation of the
15153 compiler, but mapping files can improve efficiency, particularly when
15154 sources are read over a slow network connection. In normal operation,
15155 you need not be concerned with the format or use of mapping files,
15156 and the @code{-gnatem} switch is not a switch that you would use
15157 explicitly. It is intended primarily for use by automatic tools such as
15158 @code{gnatmake} running under the project file facility. The
15159 description here of the format of mapping files is provided
15160 for completeness and for possible use by other tools.
15162 A mapping file is a sequence of sets of three lines. In each set, the
15163 first line is the unit name, in lower case, with @code{%s} appended
15164 for specs and @code{%b} appended for bodies; the second line is the
15165 file name; and the third line is the path name.
15172 /gnat/project1/sources/main.2.ada
15175 When the switch @code{-gnatem} is specified, the compiler will
15176 create in memory the two mappings from the specified file. If there is
15177 any problem (nonexistent file, truncated file or duplicate entries),
15178 no mapping will be created.
15180 Several @code{-gnatem} switches may be specified; however, only the
15181 last one on the command line will be taken into account.
15183 When using a project file, @code{gnatmake} creates a temporary
15184 mapping file and communicates it to the compiler using this switch.
15187 @node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
15188 @anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{117}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{118}
15189 @subsection Code Generation Control
15192 The GCC technology provides a wide range of target dependent
15193 @code{-m} switches for controlling
15194 details of code generation with respect to different versions of
15195 architectures. This includes variations in instruction sets (e.g.,
15196 different members of the power pc family), and different requirements
15197 for optimal arrangement of instructions (e.g., different members of
15198 the x86 family). The list of available @code{-m} switches may be
15199 found in the GCC documentation.
15201 Use of these @code{-m} switches may in some cases result in improved
15204 The GNAT technology is tested and qualified without any
15205 @code{-m} switches,
15206 so generally the most reliable approach is to avoid the use of these
15207 switches. However, we generally expect most of these switches to work
15208 successfully with GNAT, and many customers have reported successful
15209 use of these options.
15211 Our general advice is to avoid the use of @code{-m} switches unless
15212 special needs lead to requirements in this area. In particular,
15213 there is no point in using @code{-m} switches to improve performance
15214 unless you actually see a performance improvement.
15216 @node Linker Switches,Binding with gnatbind,Compiler Switches,Building Executable Programs with GNAT
15217 @anchor{gnat_ugn/building_executable_programs_with_gnat linker-switches}@anchor{119}@anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{11a}
15218 @section Linker Switches
15221 Linker switches can be specified after @code{-largs} builder switch.
15223 @geindex -fuse-ld=name
15228 @item @code{-fuse-ld=@emph{name}}
15230 Linker to be used. The default is @code{bfd} for @code{ld.bfd},
15231 the alternative being @code{gold} for @code{ld.gold}. The later is
15232 a more recent and faster linker, but only available on GNU/Linux
15236 @node Binding with gnatbind,Linking with gnatlink,Linker Switches,Building Executable Programs with GNAT
15237 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{1d}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{11b}
15238 @section Binding with @code{gnatbind}
15243 This chapter describes the GNAT binder, @code{gnatbind}, which is used
15244 to bind compiled GNAT objects.
15246 The @code{gnatbind} program performs four separate functions:
15252 Checks that a program is consistent, in accordance with the rules in
15253 Chapter 10 of the Ada Reference Manual. In particular, error
15254 messages are generated if a program uses inconsistent versions of a
15258 Checks that an acceptable order of elaboration exists for the program
15259 and issues an error message if it cannot find an order of elaboration
15260 that satisfies the rules in Chapter 10 of the Ada Language Manual.
15263 Generates a main program incorporating the given elaboration order.
15264 This program is a small Ada package (body and spec) that
15265 must be subsequently compiled
15266 using the GNAT compiler. The necessary compilation step is usually
15267 performed automatically by @code{gnatlink}. The two most important
15268 functions of this program
15269 are to call the elaboration routines of units in an appropriate order
15270 and to call the main program.
15273 Determines the set of object files required by the given main program.
15274 This information is output in the forms of comments in the generated program,
15275 to be read by the @code{gnatlink} utility used to link the Ada application.
15279 * Running gnatbind::
15280 * Switches for gnatbind::
15281 * Command-Line Access::
15282 * Search Paths for gnatbind::
15283 * Examples of gnatbind Usage::
15287 @node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
15288 @anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{11c}@anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{11d}
15289 @subsection Running @code{gnatbind}
15292 The form of the @code{gnatbind} command is
15295 $ gnatbind [ switches ] mainprog[.ali] [ switches ]
15298 where @code{mainprog.adb} is the Ada file containing the main program
15299 unit body. @code{gnatbind} constructs an Ada
15300 package in two files whose names are
15301 @code{b~mainprog.ads}, and @code{b~mainprog.adb}.
15302 For example, if given the
15303 parameter @code{hello.ali}, for a main program contained in file
15304 @code{hello.adb}, the binder output files would be @code{b~hello.ads}
15305 and @code{b~hello.adb}.
15307 When doing consistency checking, the binder takes into consideration
15308 any source files it can locate. For example, if the binder determines
15309 that the given main program requires the package @code{Pack}, whose
15311 file is @code{pack.ali} and whose corresponding source spec file is
15312 @code{pack.ads}, it attempts to locate the source file @code{pack.ads}
15313 (using the same search path conventions as previously described for the
15314 @code{gcc} command). If it can locate this source file, it checks that
15316 or source checksums of the source and its references to in @code{ALI} files
15317 match. In other words, any @code{ALI} files that mentions this spec must have
15318 resulted from compiling this version of the source file (or in the case
15319 where the source checksums match, a version close enough that the
15320 difference does not matter).
15322 @geindex Source files
15323 @geindex use by binder
15325 The effect of this consistency checking, which includes source files, is
15326 that the binder ensures that the program is consistent with the latest
15327 version of the source files that can be located at bind time. Editing a
15328 source file without compiling files that depend on the source file cause
15329 error messages to be generated by the binder.
15331 For example, suppose you have a main program @code{hello.adb} and a
15332 package @code{P}, from file @code{p.ads} and you perform the following
15339 Enter @code{gcc -c hello.adb} to compile the main program.
15342 Enter @code{gcc -c p.ads} to compile package @code{P}.
15345 Edit file @code{p.ads}.
15348 Enter @code{gnatbind hello}.
15351 At this point, the file @code{p.ali} contains an out-of-date time stamp
15352 because the file @code{p.ads} has been edited. The attempt at binding
15353 fails, and the binder generates the following error messages:
15356 error: "hello.adb" must be recompiled ("p.ads" has been modified)
15357 error: "p.ads" has been modified and must be recompiled
15360 Now both files must be recompiled as indicated, and then the bind can
15361 succeed, generating a main program. You need not normally be concerned
15362 with the contents of this file, but for reference purposes a sample
15363 binder output file is given in @ref{e,,Example of Binder Output File}.
15365 In most normal usage, the default mode of @code{gnatbind} which is to
15366 generate the main package in Ada, as described in the previous section.
15367 In particular, this means that any Ada programmer can read and understand
15368 the generated main program. It can also be debugged just like any other
15369 Ada code provided the @code{-g} switch is used for
15370 @code{gnatbind} and @code{gnatlink}.
15372 @node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
15373 @anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{11e}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{11f}
15374 @subsection Switches for @code{gnatbind}
15377 The following switches are available with @code{gnatbind}; details will
15378 be presented in subsequent sections.
15380 @geindex --version (gnatbind)
15385 @item @code{--version}
15387 Display Copyright and version, then exit disregarding all other options.
15390 @geindex --help (gnatbind)
15395 @item @code{--help}
15397 If @code{--version} was not used, display usage, then exit disregarding
15401 @geindex -a (gnatbind)
15408 Indicates that, if supported by the platform, the adainit procedure should
15409 be treated as an initialisation routine by the linker (a constructor). This
15410 is intended to be used by the Project Manager to automatically initialize
15411 shared Stand-Alone Libraries.
15414 @geindex -aO (gnatbind)
15421 Specify directory to be searched for ALI files.
15424 @geindex -aI (gnatbind)
15431 Specify directory to be searched for source file.
15434 @geindex -A (gnatbind)
15439 @item @code{-A[=@emph{filename}]}
15441 Output ALI list (to standard output or to the named file).
15444 @geindex -b (gnatbind)
15451 Generate brief messages to @code{stderr} even if verbose mode set.
15454 @geindex -c (gnatbind)
15461 Check only, no generation of binder output file.
15464 @geindex -dnn[k|m] (gnatbind)
15469 @item @code{-d@emph{nn}[k|m]}
15471 This switch can be used to change the default task stack size value
15472 to a specified size @code{nn}, which is expressed in bytes by default, or
15473 in kilobytes when suffixed with @code{k} or in megabytes when suffixed
15475 In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15476 in effect, to completing all task specs with
15479 pragma Storage_Size (nn);
15482 When they do not already have such a pragma.
15485 @geindex -D (gnatbind)
15490 @item @code{-D@emph{nn}[k|m]}
15492 This switch can be used to change the default secondary stack size value
15493 to a specified size @code{nn}, which is expressed in bytes by default, or
15494 in kilobytes when suffixed with @code{k} or in megabytes when suffixed
15497 The secondary stack is used to deal with functions that return a variable
15498 sized result, for example a function returning an unconstrained
15499 String. There are two ways in which this secondary stack is allocated.
15501 For most targets, the secondary stack grows on demand and is allocated
15502 as a chain of blocks in the heap. The -D option is not very
15503 relevant. It only give some control over the size of the allocated
15504 blocks (whose size is the minimum of the default secondary stack size value,
15505 and the actual size needed for the current allocation request).
15507 For certain targets, notably VxWorks 653 and bare board targets,
15508 the secondary stack is allocated by carving off a chunk of the primary task
15509 stack. By default this is a fixed percentage of the primary task stack as
15510 defined by System.Parameter.Sec_Stack_Percentage. This can be overridden per
15511 task using the Secondary_Stack_Size pragma/aspect. The -D option is used to
15512 define the size of the environment task's secondary stack.
15515 @geindex -e (gnatbind)
15522 Output complete list of elaboration-order dependencies.
15525 @geindex -Ea (gnatbind)
15532 Store tracebacks in exception occurrences when the target supports it.
15533 The "a" is for "address"; tracebacks will contain hexadecimal addresses,
15534 unless symbolic tracebacks are enabled.
15536 See also the packages @code{GNAT.Traceback} and
15537 @code{GNAT.Traceback.Symbolic} for more information.
15538 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
15542 @geindex -Es (gnatbind)
15549 Store tracebacks in exception occurrences when the target supports it.
15550 The "s" is for "symbolic"; symbolic tracebacks are enabled.
15553 @geindex -E (gnatbind)
15560 Currently the same as @code{-Ea}.
15563 @geindex -f (gnatbind)
15568 @item @code{-f@emph{elab-order}}
15570 Force elaboration order.
15573 @geindex -F (gnatbind)
15580 Force the checks of elaboration flags. @code{gnatbind} does not normally
15581 generate checks of elaboration flags for the main executable, except when
15582 a Stand-Alone Library is used. However, there are cases when this cannot be
15583 detected by gnatbind. An example is importing an interface of a Stand-Alone
15584 Library through a pragma Import and only specifying through a linker switch
15585 this Stand-Alone Library. This switch is used to guarantee that elaboration
15586 flag checks are generated.
15589 @geindex -h (gnatbind)
15596 Output usage (help) information.
15598 @geindex -H32 (gnatbind)
15602 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
15603 For further details see @ref{120,,Dynamic Allocation Control}.
15605 @geindex -H64 (gnatbind)
15607 @geindex __gnat_malloc
15611 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
15612 For further details see @ref{120,,Dynamic Allocation Control}.
15614 @geindex -I (gnatbind)
15618 Specify directory to be searched for source and ALI files.
15620 @geindex -I- (gnatbind)
15624 Do not look for sources in the current directory where @code{gnatbind} was
15625 invoked, and do not look for ALI files in the directory containing the
15626 ALI file named in the @code{gnatbind} command line.
15628 @geindex -l (gnatbind)
15632 Output chosen elaboration order.
15634 @geindex -L (gnatbind)
15636 @item @code{-L@emph{xxx}}
15638 Bind the units for library building. In this case the @code{adainit} and
15639 @code{adafinal} procedures (@ref{b4,,Binding with Non-Ada Main Programs})
15640 are renamed to @code{@emph{xxx}init} and
15641 @code{@emph{xxx}final}.
15643 (@ref{15,,GNAT and Libraries}, for more details.)
15645 @geindex -M (gnatbind)
15647 @item @code{-M@emph{xyz}}
15649 Rename generated main program from main to xyz. This option is
15650 supported on cross environments only.
15652 @geindex -m (gnatbind)
15654 @item @code{-m@emph{n}}
15656 Limit number of detected errors or warnings to @code{n}, where @code{n} is
15657 in the range 1..999999. The default value if no switch is
15658 given is 9999. If the number of warnings reaches this limit, then a
15659 message is output and further warnings are suppressed, the bind
15660 continues in this case. If the number of errors reaches this
15661 limit, then a message is output and the bind is abandoned.
15662 A value of zero means that no limit is enforced. The equal
15665 @geindex -n (gnatbind)
15671 @geindex -nostdinc (gnatbind)
15673 @item @code{-nostdinc}
15675 Do not look for sources in the system default directory.
15677 @geindex -nostdlib (gnatbind)
15679 @item @code{-nostdlib}
15681 Do not look for library files in the system default directory.
15683 @geindex --RTS (gnatbind)
15685 @item @code{--RTS=@emph{rts-path}}
15687 Specifies the default location of the runtime library. Same meaning as the
15688 equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
15690 @geindex -o (gnatbind)
15692 @item @code{-o @emph{file}}
15694 Name the output file @code{file} (default is @code{b~`xxx}.adb`).
15695 Note that if this option is used, then linking must be done manually,
15696 gnatlink cannot be used.
15698 @geindex -O (gnatbind)
15700 @item @code{-O[=@emph{filename}]}
15702 Output object list (to standard output or to the named file).
15704 @geindex -p (gnatbind)
15708 Pessimistic (worst-case) elaboration order.
15710 @geindex -P (gnatbind)
15714 Generate binder file suitable for CodePeer.
15716 @geindex -R (gnatbind)
15720 Output closure source list, which includes all non-run-time units that are
15721 included in the bind.
15723 @geindex -Ra (gnatbind)
15727 Like @code{-R} but the list includes run-time units.
15729 @geindex -s (gnatbind)
15733 Require all source files to be present.
15735 @geindex -S (gnatbind)
15737 @item @code{-S@emph{xxx}}
15739 Specifies the value to be used when detecting uninitialized scalar
15740 objects with pragma Initialize_Scalars.
15741 The @code{xxx} string specified with the switch is one of:
15747 @code{in} for an invalid value.
15749 If zero is invalid for the discrete type in question,
15750 then the scalar value is set to all zero bits.
15751 For signed discrete types, the largest possible negative value of
15752 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15753 For unsigned discrete types, the underlying scalar value is set to all
15754 one bits. For floating-point types, a NaN value is set
15755 (see body of package System.Scalar_Values for exact values).
15758 @code{lo} for low value.
15760 If zero is invalid for the discrete type in question,
15761 then the scalar value is set to all zero bits.
15762 For signed discrete types, the largest possible negative value of
15763 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15764 For unsigned discrete types, the underlying scalar value is set to all
15765 zero bits. For floating-point, a small value is set
15766 (see body of package System.Scalar_Values for exact values).
15769 @code{hi} for high value.
15771 If zero is invalid for the discrete type in question,
15772 then the scalar value is set to all one bits.
15773 For signed discrete types, the largest possible positive value of
15774 the underlying scalar is set (i.e. a zero bit followed by all one bits).
15775 For unsigned discrete types, the underlying scalar value is set to all
15776 one bits. For floating-point, a large value is set
15777 (see body of package System.Scalar_Values for exact values).
15780 @code{xx} for hex value (two hex digits).
15782 The underlying scalar is set to a value consisting of repeated bytes, whose
15783 value corresponds to the given value. For example if @code{BF} is given,
15784 then a 32-bit scalar value will be set to the bit patterm @code{16#BFBFBFBF#}.
15787 @geindex GNAT_INIT_SCALARS
15789 In addition, you can specify @code{-Sev} to indicate that the value is
15790 to be set at run time. In this case, the program will look for an environment
15791 variable of the form @code{GNAT_INIT_SCALARS=@emph{yy}}, where @code{yy} is one
15792 of @code{in/lo/hi/@emph{xx}} with the same meanings as above.
15793 If no environment variable is found, or if it does not have a valid value,
15794 then the default is @code{in} (invalid values).
15797 @geindex -static (gnatbind)
15802 @item @code{-static}
15804 Link against a static GNAT run time.
15806 @geindex -shared (gnatbind)
15808 @item @code{-shared}
15810 Link against a shared GNAT run time when available.
15812 @geindex -t (gnatbind)
15816 Tolerate time stamp and other consistency errors.
15818 @geindex -T (gnatbind)
15820 @item @code{-T@emph{n}}
15822 Set the time slice value to @code{n} milliseconds. If the system supports
15823 the specification of a specific time slice value, then the indicated value
15824 is used. If the system does not support specific time slice values, but
15825 does support some general notion of round-robin scheduling, then any
15826 nonzero value will activate round-robin scheduling.
15828 A value of zero is treated specially. It turns off time
15829 slicing, and in addition, indicates to the tasking run time that the
15830 semantics should match as closely as possible the Annex D
15831 requirements of the Ada RM, and in particular sets the default
15832 scheduling policy to @code{FIFO_Within_Priorities}.
15834 @geindex -u (gnatbind)
15836 @item @code{-u@emph{n}}
15838 Enable dynamic stack usage, with @code{n} results stored and displayed
15839 at program termination. A result is generated when a task
15840 terminates. Results that can't be stored are displayed on the fly, at
15841 task termination. This option is currently not supported on Itanium
15842 platforms. (See @ref{121,,Dynamic Stack Usage Analysis} for details.)
15844 @geindex -v (gnatbind)
15848 Verbose mode. Write error messages, header, summary output to
15851 @geindex -V (gnatbind)
15853 @item @code{-V@emph{key}=@emph{value}}
15855 Store the given association of @code{key} to @code{value} in the bind environment.
15856 Values stored this way can be retrieved at run time using
15857 @code{GNAT.Bind_Environment}.
15859 @geindex -w (gnatbind)
15861 @item @code{-w@emph{x}}
15863 Warning mode; @code{x} = s/e for suppress/treat as error.
15865 @geindex -Wx (gnatbind)
15867 @item @code{-Wx@emph{e}}
15869 Override default wide character encoding for standard Text_IO files.
15871 @geindex -x (gnatbind)
15875 Exclude source files (check object consistency only).
15877 @geindex -Xnnn (gnatbind)
15879 @item @code{-X@emph{nnn}}
15881 Set default exit status value, normally 0 for POSIX compliance.
15883 @geindex -y (gnatbind)
15887 Enable leap seconds support in @code{Ada.Calendar} and its children.
15889 @geindex -z (gnatbind)
15893 No main subprogram.
15896 You may obtain this listing of switches by running @code{gnatbind} with
15900 * Consistency-Checking Modes::
15901 * Binder Error Message Control::
15902 * Elaboration Control::
15904 * Dynamic Allocation Control::
15905 * Binding with Non-Ada Main Programs::
15906 * Binding Programs with No Main Subprogram::
15910 @node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
15911 @anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{122}@anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{123}
15912 @subsubsection Consistency-Checking Modes
15915 As described earlier, by default @code{gnatbind} checks
15916 that object files are consistent with one another and are consistent
15917 with any source files it can locate. The following switches control binder
15922 @geindex -s (gnatbind)
15930 Require source files to be present. In this mode, the binder must be
15931 able to locate all source files that are referenced, in order to check
15932 their consistency. In normal mode, if a source file cannot be located it
15933 is simply ignored. If you specify this switch, a missing source
15936 @geindex -Wx (gnatbind)
15938 @item @code{-Wx@emph{e}}
15940 Override default wide character encoding for standard Text_IO files.
15941 Normally the default wide character encoding method used for standard
15942 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
15943 the main source input (see description of switch
15944 @code{-gnatWx} for the compiler). The
15945 use of this switch for the binder (which has the same set of
15946 possible arguments) overrides this default as specified.
15948 @geindex -x (gnatbind)
15952 Exclude source files. In this mode, the binder only checks that ALI
15953 files are consistent with one another. Source files are not accessed.
15954 The binder runs faster in this mode, and there is still a guarantee that
15955 the resulting program is self-consistent.
15956 If a source file has been edited since it was last compiled, and you
15957 specify this switch, the binder will not detect that the object
15958 file is out of date with respect to the source file. Note that this is the
15959 mode that is automatically used by @code{gnatmake} because in this
15960 case the checking against sources has already been performed by
15961 @code{gnatmake} in the course of compilation (i.e., before binding).
15964 @node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
15965 @anchor{gnat_ugn/building_executable_programs_with_gnat id36}@anchor{124}@anchor{gnat_ugn/building_executable_programs_with_gnat binder-error-message-control}@anchor{125}
15966 @subsubsection Binder Error Message Control
15969 The following switches provide control over the generation of error
15970 messages from the binder:
15974 @geindex -v (gnatbind)
15982 Verbose mode. In the normal mode, brief error messages are generated to
15983 @code{stderr}. If this switch is present, a header is written
15984 to @code{stdout} and any error messages are directed to @code{stdout}.
15985 All that is written to @code{stderr} is a brief summary message.
15987 @geindex -b (gnatbind)
15991 Generate brief error messages to @code{stderr} even if verbose mode is
15992 specified. This is relevant only when used with the
15995 @geindex -m (gnatbind)
15997 @item @code{-m@emph{n}}
15999 Limits the number of error messages to @code{n}, a decimal integer in the
16000 range 1-999. The binder terminates immediately if this limit is reached.
16002 @geindex -M (gnatbind)
16004 @item @code{-M@emph{xxx}}
16006 Renames the generated main program from @code{main} to @code{xxx}.
16007 This is useful in the case of some cross-building environments, where
16008 the actual main program is separate from the one generated
16009 by @code{gnatbind}.
16011 @geindex -ws (gnatbind)
16017 Suppress all warning messages.
16019 @geindex -we (gnatbind)
16023 Treat any warning messages as fatal errors.
16025 @geindex -t (gnatbind)
16027 @geindex Time stamp checks
16030 @geindex Binder consistency checks
16032 @geindex Consistency checks
16037 The binder performs a number of consistency checks including:
16043 Check that time stamps of a given source unit are consistent
16046 Check that checksums of a given source unit are consistent
16049 Check that consistent versions of @code{GNAT} were used for compilation
16052 Check consistency of configuration pragmas as required
16055 Normally failure of such checks, in accordance with the consistency
16056 requirements of the Ada Reference Manual, causes error messages to be
16057 generated which abort the binder and prevent the output of a binder
16058 file and subsequent link to obtain an executable.
16060 The @code{-t} switch converts these error messages
16061 into warnings, so that
16062 binding and linking can continue to completion even in the presence of such
16063 errors. The result may be a failed link (due to missing symbols), or a
16064 non-functional executable which has undefined semantics.
16068 This means that @code{-t} should be used only in unusual situations,
16074 @node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
16075 @anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{126}@anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{127}
16076 @subsubsection Elaboration Control
16079 The following switches provide additional control over the elaboration
16080 order. For full details see @ref{f,,Elaboration Order Handling in GNAT}.
16082 @geindex -f (gnatbind)
16087 @item @code{-f@emph{elab-order}}
16089 Force elaboration order.
16091 @code{elab-order} should be the name of a "forced elaboration order file", that
16092 is, a text file containing library item names, one per line. A name of the
16093 form "some.unit%s" or "some.unit (spec)" denotes the spec of Some.Unit. A
16094 name of the form "some.unit%b" or "some.unit (body)" denotes the body of
16095 Some.Unit. Each pair of lines is taken to mean that there is an elaboration
16096 dependence of the second line on the first. For example, if the file
16106 then the spec of This will be elaborated before the body of This, and the
16107 body of This will be elaborated before the spec of That, and the spec of That
16108 will be elaborated before the body of That. The first and last of these three
16109 dependences are already required by Ada rules, so this file is really just
16110 forcing the body of This to be elaborated before the spec of That.
16112 The given order must be consistent with Ada rules, or else @code{gnatbind} will
16113 give elaboration cycle errors. For example, if you say x (body) should be
16114 elaborated before x (spec), there will be a cycle, because Ada rules require
16115 x (spec) to be elaborated before x (body); you can't have the spec and body
16116 both elaborated before each other.
16118 If you later add "with That;" to the body of This, there will be a cycle, in
16119 which case you should erase either "this (body)" or "that (spec)" from the
16120 above forced elaboration order file.
16122 Blank lines and Ada-style comments are ignored. Unit names that do not exist
16123 in the program are ignored. Units in the GNAT predefined library are also
16126 @geindex -p (gnatbind)
16130 Normally the binder attempts to choose an elaboration order that is
16131 likely to minimize the likelihood of an elaboration order error resulting
16132 in raising a @code{Program_Error} exception. This switch reverses the
16133 action of the binder, and requests that it deliberately choose an order
16134 that is likely to maximize the likelihood of an elaboration error.
16135 This is useful in ensuring portability and avoiding dependence on
16136 accidental fortuitous elaboration ordering.
16138 Normally it only makes sense to use the @code{-p}
16140 elaboration checking is used (@code{-gnatE} switch used for compilation).
16141 This is because in the default static elaboration mode, all necessary
16142 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
16143 These implicit pragmas are still respected by the binder in
16144 @code{-p} mode, so a
16145 safe elaboration order is assured.
16147 Note that @code{-p} is not intended for
16148 production use; it is more for debugging/experimental use.
16151 @node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
16152 @anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{128}@anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{129}
16153 @subsubsection Output Control
16156 The following switches allow additional control over the output
16157 generated by the binder.
16161 @geindex -c (gnatbind)
16169 Check only. Do not generate the binder output file. In this mode the
16170 binder performs all error checks but does not generate an output file.
16172 @geindex -e (gnatbind)
16176 Output complete list of elaboration-order dependencies, showing the
16177 reason for each dependency. This output can be rather extensive but may
16178 be useful in diagnosing problems with elaboration order. The output is
16179 written to @code{stdout}.
16181 @geindex -h (gnatbind)
16185 Output usage information. The output is written to @code{stdout}.
16187 @geindex -K (gnatbind)
16191 Output linker options to @code{stdout}. Includes library search paths,
16192 contents of pragmas Ident and Linker_Options, and libraries added
16193 by @code{gnatbind}.
16195 @geindex -l (gnatbind)
16199 Output chosen elaboration order. The output is written to @code{stdout}.
16201 @geindex -O (gnatbind)
16205 Output full names of all the object files that must be linked to provide
16206 the Ada component of the program. The output is written to @code{stdout}.
16207 This list includes the files explicitly supplied and referenced by the user
16208 as well as implicitly referenced run-time unit files. The latter are
16209 omitted if the corresponding units reside in shared libraries. The
16210 directory names for the run-time units depend on the system configuration.
16212 @geindex -o (gnatbind)
16214 @item @code{-o @emph{file}}
16216 Set name of output file to @code{file} instead of the normal
16217 @code{b~`mainprog}.adb` default. Note that @code{file} denote the Ada
16218 binder generated body filename.
16219 Note that if this option is used, then linking must be done manually.
16220 It is not possible to use gnatlink in this case, since it cannot locate
16223 @geindex -r (gnatbind)
16227 Generate list of @code{pragma Restrictions} that could be applied to
16228 the current unit. This is useful for code audit purposes, and also may
16229 be used to improve code generation in some cases.
16232 @node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
16233 @anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{120}@anchor{gnat_ugn/building_executable_programs_with_gnat id39}@anchor{12a}
16234 @subsubsection Dynamic Allocation Control
16237 The heap control switches -- @code{-H32} and @code{-H64} --
16238 determine whether dynamic allocation uses 32-bit or 64-bit memory.
16239 They only affect compiler-generated allocations via @code{__gnat_malloc};
16240 explicit calls to @code{malloc} and related functions from the C
16241 run-time library are unaffected.
16248 Allocate memory on 32-bit heap
16252 Allocate memory on 64-bit heap. This is the default
16253 unless explicitly overridden by a @code{'Size} clause on the access type.
16256 These switches are only effective on VMS platforms.
16258 @node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
16259 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-non-ada-main-programs}@anchor{b4}@anchor{gnat_ugn/building_executable_programs_with_gnat id40}@anchor{12b}
16260 @subsubsection Binding with Non-Ada Main Programs
16263 The description so far has assumed that the main
16264 program is in Ada, and that the task of the binder is to generate a
16265 corresponding function @code{main} that invokes this Ada main
16266 program. GNAT also supports the building of executable programs where
16267 the main program is not in Ada, but some of the called routines are
16268 written in Ada and compiled using GNAT (@ref{44,,Mixed Language Programming}).
16269 The following switch is used in this situation:
16273 @geindex -n (gnatbind)
16281 No main program. The main program is not in Ada.
16284 In this case, most of the functions of the binder are still required,
16285 but instead of generating a main program, the binder generates a file
16286 containing the following callable routines:
16295 @item @code{adainit}
16297 You must call this routine to initialize the Ada part of the program by
16298 calling the necessary elaboration routines. A call to @code{adainit} is
16299 required before the first call to an Ada subprogram.
16301 Note that it is assumed that the basic execution environment must be setup
16302 to be appropriate for Ada execution at the point where the first Ada
16303 subprogram is called. In particular, if the Ada code will do any
16304 floating-point operations, then the FPU must be setup in an appropriate
16305 manner. For the case of the x86, for example, full precision mode is
16306 required. The procedure GNAT.Float_Control.Reset may be used to ensure
16307 that the FPU is in the right state.
16315 @item @code{adafinal}
16317 You must call this routine to perform any library-level finalization
16318 required by the Ada subprograms. A call to @code{adafinal} is required
16319 after the last call to an Ada subprogram, and before the program
16324 @geindex -n (gnatbind)
16327 @geindex multiple input files
16329 If the @code{-n} switch
16330 is given, more than one ALI file may appear on
16331 the command line for @code{gnatbind}. The normal @code{closure}
16332 calculation is performed for each of the specified units. Calculating
16333 the closure means finding out the set of units involved by tracing
16334 @emph{with} references. The reason it is necessary to be able to
16335 specify more than one ALI file is that a given program may invoke two or
16336 more quite separate groups of Ada units.
16338 The binder takes the name of its output file from the last specified ALI
16339 file, unless overridden by the use of the @code{-o file}.
16341 @geindex -o (gnatbind)
16343 The output is an Ada unit in source form that can be compiled with GNAT.
16344 This compilation occurs automatically as part of the @code{gnatlink}
16347 Currently the GNAT run time requires a FPU using 80 bits mode
16348 precision. Under targets where this is not the default it is required to
16349 call GNAT.Float_Control.Reset before using floating point numbers (this
16350 include float computation, float input and output) in the Ada code. A
16351 side effect is that this could be the wrong mode for the foreign code
16352 where floating point computation could be broken after this call.
16354 @node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
16355 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-programs-with-no-main-subprogram}@anchor{12c}@anchor{gnat_ugn/building_executable_programs_with_gnat id41}@anchor{12d}
16356 @subsubsection Binding Programs with No Main Subprogram
16359 It is possible to have an Ada program which does not have a main
16360 subprogram. This program will call the elaboration routines of all the
16361 packages, then the finalization routines.
16363 The following switch is used to bind programs organized in this manner:
16367 @geindex -z (gnatbind)
16375 Normally the binder checks that the unit name given on the command line
16376 corresponds to a suitable main subprogram. When this switch is used,
16377 a list of ALI files can be given, and the execution of the program
16378 consists of elaboration of these units in an appropriate order. Note
16379 that the default wide character encoding method for standard Text_IO
16380 files is always set to Brackets if this switch is set (you can use
16382 @code{-Wx} to override this default).
16385 @node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
16386 @anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{12e}@anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{12f}
16387 @subsection Command-Line Access
16390 The package @code{Ada.Command_Line} provides access to the command-line
16391 arguments and program name. In order for this interface to operate
16392 correctly, the two variables
16403 are declared in one of the GNAT library routines. These variables must
16404 be set from the actual @code{argc} and @code{argv} values passed to the
16405 main program. With no @emph{n} present, @code{gnatbind}
16406 generates the C main program to automatically set these variables.
16407 If the @emph{n} switch is used, there is no automatic way to
16408 set these variables. If they are not set, the procedures in
16409 @code{Ada.Command_Line} will not be available, and any attempt to use
16410 them will raise @code{Constraint_Error}. If command line access is
16411 required, your main program must set @code{gnat_argc} and
16412 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
16415 @node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
16416 @anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-for-gnatbind}@anchor{8c}@anchor{gnat_ugn/building_executable_programs_with_gnat id43}@anchor{130}
16417 @subsection Search Paths for @code{gnatbind}
16420 The binder takes the name of an ALI file as its argument and needs to
16421 locate source files as well as other ALI files to verify object consistency.
16423 For source files, it follows exactly the same search rules as @code{gcc}
16424 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
16425 directories searched are:
16431 The directory containing the ALI file named in the command line, unless
16432 the switch @code{-I-} is specified.
16435 All directories specified by @code{-I}
16436 switches on the @code{gnatbind}
16437 command line, in the order given.
16439 @geindex ADA_PRJ_OBJECTS_FILE
16442 Each of the directories listed in the text file whose name is given
16444 @geindex ADA_PRJ_OBJECTS_FILE
16445 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16446 @code{ADA_PRJ_OBJECTS_FILE} environment variable.
16448 @geindex ADA_PRJ_OBJECTS_FILE
16449 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16450 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
16451 driver when project files are used. It should not normally be set
16454 @geindex ADA_OBJECTS_PATH
16457 Each of the directories listed in the value of the
16458 @geindex ADA_OBJECTS_PATH
16459 @geindex environment variable; ADA_OBJECTS_PATH
16460 @code{ADA_OBJECTS_PATH} environment variable.
16461 Construct this value
16464 @geindex environment variable; PATH
16465 @code{PATH} environment variable: a list of directory
16466 names separated by colons (semicolons when working with the NT version
16470 The content of the @code{ada_object_path} file which is part of the GNAT
16471 installation tree and is used to store standard libraries such as the
16472 GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is
16473 specified. See @ref{87,,Installing a library}
16476 @geindex -I (gnatbind)
16478 @geindex -aI (gnatbind)
16480 @geindex -aO (gnatbind)
16482 In the binder the switch @code{-I}
16483 is used to specify both source and
16484 library file paths. Use @code{-aI}
16485 instead if you want to specify
16486 source paths only, and @code{-aO}
16487 if you want to specify library paths
16488 only. This means that for the binder
16489 @code{-I@emph{dir}} is equivalent to
16490 @code{-aI@emph{dir}}
16491 @code{-aO`@emph{dir}}.
16492 The binder generates the bind file (a C language source file) in the
16493 current working directory.
16499 @geindex Interfaces
16503 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
16504 children make up the GNAT Run-Time Library, together with the package
16505 GNAT and its children, which contain a set of useful additional
16506 library functions provided by GNAT. The sources for these units are
16507 needed by the compiler and are kept together in one directory. The ALI
16508 files and object files generated by compiling the RTL are needed by the
16509 binder and the linker and are kept together in one directory, typically
16510 different from the directory containing the sources. In a normal
16511 installation, you need not specify these directory names when compiling
16512 or binding. Either the environment variables or the built-in defaults
16513 cause these files to be found.
16515 Besides simplifying access to the RTL, a major use of search paths is
16516 in compiling sources from multiple directories. This can make
16517 development environments much more flexible.
16519 @node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16520 @anchor{gnat_ugn/building_executable_programs_with_gnat id44}@anchor{131}@anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatbind-usage}@anchor{132}
16521 @subsection Examples of @code{gnatbind} Usage
16524 Here are some examples of @code{gnatbind} invovations:
16532 The main program @code{Hello} (source program in @code{hello.adb}) is
16533 bound using the standard switch settings. The generated main program is
16534 @code{b~hello.adb}. This is the normal, default use of the binder.
16537 gnatbind hello -o mainprog.adb
16540 The main program @code{Hello} (source program in @code{hello.adb}) is
16541 bound using the standard switch settings. The generated main program is
16542 @code{mainprog.adb} with the associated spec in
16543 @code{mainprog.ads}. Note that you must specify the body here not the
16544 spec. Note that if this option is used, then linking must be done manually,
16545 since gnatlink will not be able to find the generated file.
16548 @node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16549 @anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{133}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{1e}
16550 @section Linking with @code{gnatlink}
16555 This chapter discusses @code{gnatlink}, a tool that links
16556 an Ada program and builds an executable file. This utility
16557 invokes the system linker (via the @code{gcc} command)
16558 with a correct list of object files and library references.
16559 @code{gnatlink} automatically determines the list of files and
16560 references for the Ada part of a program. It uses the binder file
16561 generated by the @code{gnatbind} to determine this list.
16564 * Running gnatlink::
16565 * Switches for gnatlink::
16569 @node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16570 @anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{134}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{135}
16571 @subsection Running @code{gnatlink}
16574 The form of the @code{gnatlink} command is
16577 $ gnatlink [ switches ] mainprog [.ali]
16578 [ non-Ada objects ] [ linker options ]
16581 The arguments of @code{gnatlink} (switches, main @code{ALI} file,
16583 or linker options) may be in any order, provided that no non-Ada object may
16584 be mistaken for a main @code{ALI} file.
16585 Any file name @code{F} without the @code{.ali}
16586 extension will be taken as the main @code{ALI} file if a file exists
16587 whose name is the concatenation of @code{F} and @code{.ali}.
16589 @code{mainprog.ali} references the ALI file of the main program.
16590 The @code{.ali} extension of this file can be omitted. From this
16591 reference, @code{gnatlink} locates the corresponding binder file
16592 @code{b~mainprog.adb} and, using the information in this file along
16593 with the list of non-Ada objects and linker options, constructs a
16594 linker command file to create the executable.
16596 The arguments other than the @code{gnatlink} switches and the main
16597 @code{ALI} file are passed to the linker uninterpreted.
16598 They typically include the names of
16599 object files for units written in other languages than Ada and any library
16600 references required to resolve references in any of these foreign language
16601 units, or in @code{Import} pragmas in any Ada units.
16603 @code{linker options} is an optional list of linker specific
16605 The default linker called by gnatlink is @code{gcc} which in
16606 turn calls the appropriate system linker.
16608 One useful option for the linker is @code{-s}: it reduces the size of the
16609 executable by removing all symbol table and relocation information from the
16612 Standard options for the linker such as @code{-lmy_lib} or
16613 @code{-Ldir} can be added as is.
16614 For options that are not recognized by
16615 @code{gcc} as linker options, use the @code{gcc} switches
16616 @code{-Xlinker} or @code{-Wl,}.
16618 Refer to the GCC documentation for
16621 Here is an example showing how to generate a linker map:
16624 $ gnatlink my_prog -Wl,-Map,MAPFILE
16627 Using @code{linker options} it is possible to set the program stack and
16629 See @ref{136,,Setting Stack Size from gnatlink} and
16630 @ref{137,,Setting Heap Size from gnatlink}.
16632 @code{gnatlink} determines the list of objects required by the Ada
16633 program and prepends them to the list of objects passed to the linker.
16634 @code{gnatlink} also gathers any arguments set by the use of
16635 @code{pragma Linker_Options} and adds them to the list of arguments
16636 presented to the linker.
16638 @node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
16639 @anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{138}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{139}
16640 @subsection Switches for @code{gnatlink}
16643 The following switches are available with the @code{gnatlink} utility:
16645 @geindex --version (gnatlink)
16650 @item @code{--version}
16652 Display Copyright and version, then exit disregarding all other options.
16655 @geindex --help (gnatlink)
16660 @item @code{--help}
16662 If @code{--version} was not used, display usage, then exit disregarding
16666 @geindex Command line length
16668 @geindex -f (gnatlink)
16675 On some targets, the command line length is limited, and @code{gnatlink}
16676 will generate a separate file for the linker if the list of object files
16678 The @code{-f} switch forces this file
16679 to be generated even if
16680 the limit is not exceeded. This is useful in some cases to deal with
16681 special situations where the command line length is exceeded.
16684 @geindex Debugging information
16687 @geindex -g (gnatlink)
16694 The option to include debugging information causes the Ada bind file (in
16695 other words, @code{b~mainprog.adb}) to be compiled with @code{-g}.
16696 In addition, the binder does not delete the @code{b~mainprog.adb},
16697 @code{b~mainprog.o} and @code{b~mainprog.ali} files.
16698 Without @code{-g}, the binder removes these files by default.
16701 @geindex -n (gnatlink)
16708 Do not compile the file generated by the binder. This may be used when
16709 a link is rerun with different options, but there is no need to recompile
16713 @geindex -v (gnatlink)
16720 Verbose mode. Causes additional information to be output, including a full
16721 list of the included object files.
16722 This switch option is most useful when you want
16723 to see what set of object files are being used in the link step.
16726 @geindex -v -v (gnatlink)
16733 Very verbose mode. Requests that the compiler operate in verbose mode when
16734 it compiles the binder file, and that the system linker run in verbose mode.
16737 @geindex -o (gnatlink)
16742 @item @code{-o @emph{exec-name}}
16744 @code{exec-name} specifies an alternate name for the generated
16745 executable program. If this switch is omitted, the executable has the same
16746 name as the main unit. For example, @code{gnatlink try.ali} creates
16747 an executable called @code{try}.
16750 @geindex -b (gnatlink)
16755 @item @code{-b @emph{target}}
16757 Compile your program to run on @code{target}, which is the name of a
16758 system configuration. You must have a GNAT cross-compiler built if
16759 @code{target} is not the same as your host system.
16762 @geindex -B (gnatlink)
16767 @item @code{-B@emph{dir}}
16769 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
16770 from @code{dir} instead of the default location. Only use this switch
16771 when multiple versions of the GNAT compiler are available.
16772 See the @code{Directory Options} section in @cite{The_GNU_Compiler_Collection}
16773 for further details. You would normally use the @code{-b} or
16774 @code{-V} switch instead.
16777 @geindex -M (gnatlink)
16784 When linking an executable, create a map file. The name of the map file
16785 has the same name as the executable with extension ".map".
16788 @geindex -M= (gnatlink)
16793 @item @code{-M=@emph{mapfile}}
16795 When linking an executable, create a map file. The name of the map file is
16799 @geindex --GCC=compiler_name (gnatlink)
16804 @item @code{--GCC=@emph{compiler_name}}
16806 Program used for compiling the binder file. The default is
16807 @code{gcc}. You need to use quotes around @code{compiler_name} if
16808 @code{compiler_name} contains spaces or other separator characters.
16809 As an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to
16810 use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
16811 inserted after your command name. Thus in the above example the compiler
16812 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
16813 A limitation of this syntax is that the name and path name of the executable
16814 itself must not include any embedded spaces. If the compiler executable is
16815 different from the default one (gcc or <prefix>-gcc), then the back-end
16816 switches in the ALI file are not used to compile the binder generated source.
16817 For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
16818 switches will be used for @code{--GCC="gcc -gnatv"}. If several
16819 @code{--GCC=compiler_name} are used, only the last @code{compiler_name}
16820 is taken into account. However, all the additional switches are also taken
16821 into account. Thus,
16822 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
16823 @code{--GCC="bar -x -y -z -t"}.
16826 @geindex --LINK= (gnatlink)
16831 @item @code{--LINK=@emph{name}}
16833 @code{name} is the name of the linker to be invoked. This is especially
16834 useful in mixed language programs since languages such as C++ require
16835 their own linker to be used. When this switch is omitted, the default
16836 name for the linker is @code{gcc}. When this switch is used, the
16837 specified linker is called instead of @code{gcc} with exactly the same
16838 parameters that would have been passed to @code{gcc} so if the desired
16839 linker requires different parameters it is necessary to use a wrapper
16840 script that massages the parameters before invoking the real linker. It
16841 may be useful to control the exact invocation by using the verbose
16845 @node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
16846 @anchor{gnat_ugn/building_executable_programs_with_gnat using-the-gnu-make-utility}@anchor{1f}@anchor{gnat_ugn/building_executable_programs_with_gnat id48}@anchor{13a}
16847 @section Using the GNU @code{make} Utility
16850 @geindex make (GNU)
16853 This chapter offers some examples of makefiles that solve specific
16854 problems. It does not explain how to write a makefile, nor does it try to replace the
16855 @code{gnatmake} utility (@ref{1b,,Building with gnatmake}).
16857 All the examples in this section are specific to the GNU version of
16858 make. Although @code{make} is a standard utility, and the basic language
16859 is the same, these examples use some advanced features found only in
16863 * Using gnatmake in a Makefile::
16864 * Automatically Creating a List of Directories::
16865 * Generating the Command Line Switches::
16866 * Overcoming Command Line Length Limits::
16870 @node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
16871 @anchor{gnat_ugn/building_executable_programs_with_gnat using-gnatmake-in-a-makefile}@anchor{13b}@anchor{gnat_ugn/building_executable_programs_with_gnat id49}@anchor{13c}
16872 @subsection Using gnatmake in a Makefile
16875 @c index makefile (GNU make)
16877 Complex project organizations can be handled in a very powerful way by
16878 using GNU make combined with gnatmake. For instance, here is a Makefile
16879 which allows you to build each subsystem of a big project into a separate
16880 shared library. Such a makefile allows you to significantly reduce the link
16881 time of very big applications while maintaining full coherence at
16882 each step of the build process.
16884 The list of dependencies are handled automatically by
16885 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
16886 the appropriate directories.
16888 Note that you should also read the example on how to automatically
16889 create the list of directories
16890 (@ref{13d,,Automatically Creating a List of Directories})
16891 which might help you in case your project has a lot of subdirectories.
16894 ## This Makefile is intended to be used with the following directory
16896 ## - The sources are split into a series of csc (computer software components)
16897 ## Each of these csc is put in its own directory.
16898 ## Their name are referenced by the directory names.
16899 ## They will be compiled into shared library (although this would also work
16900 ## with static libraries
16901 ## - The main program (and possibly other packages that do not belong to any
16902 ## csc is put in the top level directory (where the Makefile is).
16903 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
16904 ## \\_ second_csc (sources) __ lib (will contain the library)
16906 ## Although this Makefile is build for shared library, it is easy to modify
16907 ## to build partial link objects instead (modify the lines with -shared and
16910 ## With this makefile, you can change any file in the system or add any new
16911 ## file, and everything will be recompiled correctly (only the relevant shared
16912 ## objects will be recompiled, and the main program will be re-linked).
16914 # The list of computer software component for your project. This might be
16915 # generated automatically.
16918 # Name of the main program (no extension)
16921 # If we need to build objects with -fPIC, uncomment the following line
16924 # The following variable should give the directory containing libgnat.so
16925 # You can get this directory through 'gnatls -v'. This is usually the last
16926 # directory in the Object_Path.
16929 # The directories for the libraries
16930 # (This macro expands the list of CSC to the list of shared libraries, you
16931 # could simply use the expanded form:
16932 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16933 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16935 $@{MAIN@}: objects $@{LIB_DIR@}
16936 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16937 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16940 # recompile the sources
16941 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16943 # Note: In a future version of GNAT, the following commands will be simplified
16944 # by a new tool, gnatmlib
16946 mkdir -p $@{dir $@@ @}
16947 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16948 cd $@{dir $@@ @} && cp -f ../*.ali .
16950 # The dependencies for the modules
16951 # Note that we have to force the expansion of *.o, since in some cases
16952 # make won't be able to do it itself.
16953 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16954 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16955 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16957 # Make sure all of the shared libraries are in the path before starting the
16960 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16963 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16964 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16965 $@{RM@} $@{CSC_LIST:%=%/*.o@}
16966 $@{RM@} *.o *.ali $@{MAIN@}
16969 @node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
16970 @anchor{gnat_ugn/building_executable_programs_with_gnat id50}@anchor{13e}@anchor{gnat_ugn/building_executable_programs_with_gnat automatically-creating-a-list-of-directories}@anchor{13d}
16971 @subsection Automatically Creating a List of Directories
16974 In most makefiles, you will have to specify a list of directories, and
16975 store it in a variable. For small projects, it is often easier to
16976 specify each of them by hand, since you then have full control over what
16977 is the proper order for these directories, which ones should be
16980 However, in larger projects, which might involve hundreds of
16981 subdirectories, it might be more convenient to generate this list
16984 The example below presents two methods. The first one, although less
16985 general, gives you more control over the list. It involves wildcard
16986 characters, that are automatically expanded by @code{make}. Its
16987 shortcoming is that you need to explicitly specify some of the
16988 organization of your project, such as for instance the directory tree
16989 depth, whether some directories are found in a separate tree, etc.
16991 The second method is the most general one. It requires an external
16992 program, called @code{find}, which is standard on all Unix systems. All
16993 the directories found under a given root directory will be added to the
16997 # The examples below are based on the following directory hierarchy:
16998 # All the directories can contain any number of files
16999 # ROOT_DIRECTORY -> a -> aa -> aaa
17002 # -> b -> ba -> baa
17005 # This Makefile creates a variable called DIRS, that can be reused any time
17006 # you need this list (see the other examples in this section)
17008 # The root of your project's directory hierarchy
17012 # First method: specify explicitly the list of directories
17013 # This allows you to specify any subset of all the directories you need.
17016 DIRS := a/aa/ a/ab/ b/ba/
17019 # Second method: use wildcards
17020 # Note that the argument(s) to wildcard below should end with a '/'.
17021 # Since wildcards also return file names, we have to filter them out
17022 # to avoid duplicate directory names.
17023 # We thus use make's `@w{`}dir`@w{`} and `@w{`}sort`@w{`} functions.
17024 # It sets DIRs to the following value (note that the directories aaa and baa
17025 # are not given, unless you change the arguments to wildcard).
17026 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17029 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17030 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17033 # Third method: use an external program
17034 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17035 # This is the most complete command: it sets DIRs to the following value:
17036 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17039 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17042 @node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
17043 @anchor{gnat_ugn/building_executable_programs_with_gnat id51}@anchor{13f}@anchor{gnat_ugn/building_executable_programs_with_gnat generating-the-command-line-switches}@anchor{140}
17044 @subsection Generating the Command Line Switches
17047 Once you have created the list of directories as explained in the
17048 previous section (@ref{13d,,Automatically Creating a List of Directories}),
17049 you can easily generate the command line arguments to pass to gnatmake.
17051 For the sake of completeness, this example assumes that the source path
17052 is not the same as the object path, and that you have two separate lists
17056 # see "Automatically creating a list of directories" to create
17061 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17062 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17065 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17068 @node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
17069 @anchor{gnat_ugn/building_executable_programs_with_gnat overcoming-command-line-length-limits}@anchor{141}@anchor{gnat_ugn/building_executable_programs_with_gnat id52}@anchor{142}
17070 @subsection Overcoming Command Line Length Limits
17073 One problem that might be encountered on big projects is that many
17074 operating systems limit the length of the command line. It is thus hard to give
17075 gnatmake the list of source and object directories.
17077 This example shows how you can set up environment variables, which will
17078 make @code{gnatmake} behave exactly as if the directories had been
17079 specified on the command line, but have a much higher length limit (or
17080 even none on most systems).
17082 It assumes that you have created a list of directories in your Makefile,
17083 using one of the methods presented in
17084 @ref{13d,,Automatically Creating a List of Directories}.
17085 For the sake of completeness, we assume that the object
17086 path (where the ALI files are found) is different from the sources patch.
17088 Note a small trick in the Makefile below: for efficiency reasons, we
17089 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17090 expanded immediately by @code{make}. This way we overcome the standard
17091 make behavior which is to expand the variables only when they are
17094 On Windows, if you are using the standard Windows command shell, you must
17095 replace colons with semicolons in the assignments to these variables.
17098 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17099 # This is the same thing as putting the -I arguments on the command line.
17100 # (the equivalent of using -aI on the command line would be to define
17101 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17102 # You can of course have different values for these variables.
17104 # Note also that we need to keep the previous values of these variables, since
17105 # they might have been set before running 'make' to specify where the GNAT
17106 # library is installed.
17108 # see "Automatically creating a list of directories" to create these
17114 space:=$@{empty@} $@{empty@}
17115 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17116 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17117 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17118 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17119 export ADA_INCLUDE_PATH
17120 export ADA_OBJECTS_PATH
17126 @node GNAT Utility Programs,GNAT and Program Execution,Building Executable Programs with GNAT,Top
17127 @anchor{gnat_ugn/gnat_utility_programs doc}@anchor{143}@anchor{gnat_ugn/gnat_utility_programs gnat-utility-programs}@anchor{b}@anchor{gnat_ugn/gnat_utility_programs id1}@anchor{144}
17128 @chapter GNAT Utility Programs
17131 This chapter describes a number of utility programs:
17138 @ref{20,,The File Cleanup Utility gnatclean}
17141 @ref{21,,The GNAT Library Browser gnatls}
17144 @ref{22,,The Cross-Referencing Tools gnatxref and gnatfind}
17147 @ref{23,,The Ada to HTML Converter gnathtml}
17150 Other GNAT utilities are described elsewhere in this manual:
17156 @ref{59,,Handling Arbitrary File Naming Conventions with gnatname}
17159 @ref{63,,File Name Krunching with gnatkr}
17162 @ref{36,,Renaming Files with gnatchop}
17165 @ref{17,,Preprocessing with gnatprep}
17169 * The File Cleanup Utility gnatclean::
17170 * The GNAT Library Browser gnatls::
17171 * The Cross-Referencing Tools gnatxref and gnatfind::
17172 * The Ada to HTML Converter gnathtml::
17176 @node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
17177 @anchor{gnat_ugn/gnat_utility_programs id2}@anchor{145}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{20}
17178 @section The File Cleanup Utility @code{gnatclean}
17181 @geindex File cleanup tool
17185 @code{gnatclean} is a tool that allows the deletion of files produced by the
17186 compiler, binder and linker, including ALI files, object files, tree files,
17187 expanded source files, library files, interface copy source files, binder
17188 generated files and executable files.
17191 * Running gnatclean::
17192 * Switches for gnatclean::
17196 @node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
17197 @anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{146}@anchor{gnat_ugn/gnat_utility_programs id3}@anchor{147}
17198 @subsection Running @code{gnatclean}
17201 The @code{gnatclean} command has the form:
17206 $ gnatclean switches names
17210 where @code{names} is a list of source file names. Suffixes @code{.ads} and
17211 @code{adb} may be omitted. If a project file is specified using switch
17212 @code{-P}, then @code{names} may be completely omitted.
17214 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17215 if switch @code{-c} is not specified, by the binder and
17216 the linker. In informative-only mode, specified by switch
17217 @code{-n}, the list of files that would have been deleted in
17218 normal mode is listed, but no file is actually deleted.
17220 @node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
17221 @anchor{gnat_ugn/gnat_utility_programs id4}@anchor{148}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{149}
17222 @subsection Switches for @code{gnatclean}
17225 @code{gnatclean} recognizes the following switches:
17227 @geindex --version (gnatclean)
17232 @item @code{--version}
17234 Display Copyright and version, then exit disregarding all other options.
17237 @geindex --help (gnatclean)
17242 @item @code{--help}
17244 If @code{--version} was not used, display usage, then exit disregarding
17247 @item @code{--subdirs=@emph{subdir}}
17249 Actual object directory of each project file is the subdirectory subdir of the
17250 object directory specified or defaulted in the project file.
17252 @item @code{--unchecked-shared-lib-imports}
17254 By default, shared library projects are not allowed to import static library
17255 projects. When this switch is used on the command line, this restriction is
17259 @geindex -c (gnatclean)
17266 Only attempt to delete the files produced by the compiler, not those produced
17267 by the binder or the linker. The files that are not to be deleted are library
17268 files, interface copy files, binder generated files and executable files.
17271 @geindex -D (gnatclean)
17276 @item @code{-D @emph{dir}}
17278 Indicate that ALI and object files should normally be found in directory @code{dir}.
17281 @geindex -F (gnatclean)
17288 When using project files, if some errors or warnings are detected during
17289 parsing and verbose mode is not in effect (no use of switch
17290 -v), then error lines start with the full path name of the project
17291 file, rather than its simple file name.
17294 @geindex -h (gnatclean)
17301 Output a message explaining the usage of @code{gnatclean}.
17304 @geindex -n (gnatclean)
17311 Informative-only mode. Do not delete any files. Output the list of the files
17312 that would have been deleted if this switch was not specified.
17315 @geindex -P (gnatclean)
17320 @item @code{-P@emph{project}}
17322 Use project file @code{project}. Only one such switch can be used.
17323 When cleaning a project file, the files produced by the compilation of the
17324 immediate sources or inherited sources of the project files are to be
17325 deleted. This is not depending on the presence or not of executable names
17326 on the command line.
17329 @geindex -q (gnatclean)
17336 Quiet output. If there are no errors, do not output anything, except in
17337 verbose mode (switch -v) or in informative-only mode
17341 @geindex -r (gnatclean)
17348 When a project file is specified (using switch -P),
17349 clean all imported and extended project files, recursively. If this switch
17350 is not specified, only the files related to the main project file are to be
17351 deleted. This switch has no effect if no project file is specified.
17354 @geindex -v (gnatclean)
17364 @geindex -vP (gnatclean)
17369 @item @code{-vP@emph{x}}
17371 Indicates the verbosity of the parsing of GNAT project files.
17372 @ref{de,,Switches Related to Project Files}.
17375 @geindex -X (gnatclean)
17380 @item @code{-X@emph{name}=@emph{value}}
17382 Indicates that external variable @code{name} has the value @code{value}.
17383 The Project Manager will use this value for occurrences of
17384 @code{external(name)} when parsing the project file.
17385 See @ref{de,,Switches Related to Project Files}.
17388 @geindex -aO (gnatclean)
17393 @item @code{-aO@emph{dir}}
17395 When searching for ALI and object files, look in directory @code{dir}.
17398 @geindex -I (gnatclean)
17403 @item @code{-I@emph{dir}}
17405 Equivalent to @code{-aO@emph{dir}}.
17408 @geindex -I- (gnatclean)
17410 @geindex Source files
17411 @geindex suppressing search
17418 Do not look for ALI or object files in the directory
17419 where @code{gnatclean} was invoked.
17422 @node The GNAT Library Browser gnatls,The Cross-Referencing Tools gnatxref and gnatfind,The File Cleanup Utility gnatclean,GNAT Utility Programs
17423 @anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{21}@anchor{gnat_ugn/gnat_utility_programs id5}@anchor{14a}
17424 @section The GNAT Library Browser @code{gnatls}
17427 @geindex Library browser
17431 @code{gnatls} is a tool that outputs information about compiled
17432 units. It gives the relationship between objects, unit names and source
17433 files. It can also be used to check the source dependencies of a unit
17434 as well as various characteristics.
17438 * Switches for gnatls::
17439 * Example of gnatls Usage::
17443 @node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
17444 @anchor{gnat_ugn/gnat_utility_programs id6}@anchor{14b}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{14c}
17445 @subsection Running @code{gnatls}
17448 The @code{gnatls} command has the form
17453 $ gnatls switches object_or_ali_file
17457 The main argument is the list of object or @code{ali} files
17458 (see @ref{42,,The Ada Library Information Files})
17459 for which information is requested.
17461 In normal mode, without additional option, @code{gnatls} produces a
17462 four-column listing. Each line represents information for a specific
17463 object. The first column gives the full path of the object, the second
17464 column gives the name of the principal unit in this object, the third
17465 column gives the status of the source and the fourth column gives the
17466 full path of the source representing this unit.
17467 Here is a simple example of use:
17473 ./demo1.o demo1 DIF demo1.adb
17474 ./demo2.o demo2 OK demo2.adb
17475 ./hello.o h1 OK hello.adb
17476 ./instr-child.o instr.child MOK instr-child.adb
17477 ./instr.o instr OK instr.adb
17478 ./tef.o tef DIF tef.adb
17479 ./text_io_example.o text_io_example OK text_io_example.adb
17480 ./tgef.o tgef DIF tgef.adb
17484 The first line can be interpreted as follows: the main unit which is
17486 object file @code{demo1.o} is demo1, whose main source is in
17487 @code{demo1.adb}. Furthermore, the version of the source used for the
17488 compilation of demo1 has been modified (DIF). Each source file has a status
17489 qualifier which can be:
17494 @item @emph{OK (unchanged)}
17496 The version of the source file used for the compilation of the
17497 specified unit corresponds exactly to the actual source file.
17499 @item @emph{MOK (slightly modified)}
17501 The version of the source file used for the compilation of the
17502 specified unit differs from the actual source file but not enough to
17503 require recompilation. If you use gnatmake with the option
17504 @code{-m} (minimal recompilation), a file marked
17505 MOK will not be recompiled.
17507 @item @emph{DIF (modified)}
17509 No version of the source found on the path corresponds to the source
17510 used to build this object.
17512 @item @emph{??? (file not found)}
17514 No source file was found for this unit.
17516 @item @emph{HID (hidden, unchanged version not first on PATH)}
17518 The version of the source that corresponds exactly to the source used
17519 for compilation has been found on the path but it is hidden by another
17520 version of the same source that has been modified.
17523 @node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
17524 @anchor{gnat_ugn/gnat_utility_programs id7}@anchor{14d}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{14e}
17525 @subsection Switches for @code{gnatls}
17528 @code{gnatls} recognizes the following switches:
17530 @geindex --version (gnatls)
17535 @item @code{--version}
17537 Display Copyright and version, then exit disregarding all other options.
17540 @geindex --help (gnatls)
17545 @item @code{--help}
17547 If @code{--version} was not used, display usage, then exit disregarding
17551 @geindex -a (gnatls)
17558 Consider all units, including those of the predefined Ada library.
17559 Especially useful with @code{-d}.
17562 @geindex -d (gnatls)
17569 List sources from which specified units depend on.
17572 @geindex -h (gnatls)
17579 Output the list of options.
17582 @geindex -o (gnatls)
17589 Only output information about object files.
17592 @geindex -s (gnatls)
17599 Only output information about source files.
17602 @geindex -u (gnatls)
17609 Only output information about compilation units.
17612 @geindex -files (gnatls)
17617 @item @code{-files=@emph{file}}
17619 Take as arguments the files listed in text file @code{file}.
17620 Text file @code{file} may contain empty lines that are ignored.
17621 Each nonempty line should contain the name of an existing file.
17622 Several such switches may be specified simultaneously.
17625 @geindex -aO (gnatls)
17627 @geindex -aI (gnatls)
17629 @geindex -I (gnatls)
17631 @geindex -I- (gnatls)
17636 @item @code{-aO@emph{dir}}, @code{-aI@emph{dir}}, @code{-I@emph{dir}}, @code{-I-}, @code{-nostdinc}
17638 Source path manipulation. Same meaning as the equivalent @code{gnatmake}
17639 flags (@ref{dc,,Switches for gnatmake}).
17642 @geindex -aP (gnatls)
17647 @item @code{-aP@emph{dir}}
17649 Add @code{dir} at the beginning of the project search dir.
17652 @geindex --RTS (gnatls)
17657 @item @code{--RTS=@emph{rts-path}}
17659 Specifies the default location of the runtime library. Same meaning as the
17660 equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
17663 @geindex -v (gnatls)
17670 Verbose mode. Output the complete source, object and project paths. Do not use
17671 the default column layout but instead use long format giving as much as
17672 information possible on each requested units, including special
17673 characteristics such as:
17679 @emph{Preelaborable}: The unit is preelaborable in the Ada sense.
17682 @emph{No_Elab_Code}: No elaboration code has been produced by the compiler for this unit.
17685 @emph{Pure}: The unit is pure in the Ada sense.
17688 @emph{Elaborate_Body}: The unit contains a pragma Elaborate_Body.
17691 @emph{Remote_Types}: The unit contains a pragma Remote_Types.
17694 @emph{Shared_Passive}: The unit contains a pragma Shared_Passive.
17697 @emph{Predefined}: This unit is part of the predefined environment and cannot be modified
17701 @emph{Remote_Call_Interface}: The unit contains a pragma Remote_Call_Interface.
17705 @node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
17706 @anchor{gnat_ugn/gnat_utility_programs id8}@anchor{14f}@anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{150}
17707 @subsection Example of @code{gnatls} Usage
17710 Example of using the verbose switch. Note how the source and
17711 object paths are affected by the -I switch.
17716 $ gnatls -v -I.. demo1.o
17718 GNATLS 5.03w (20041123-34)
17719 Copyright 1997-2004 Free Software Foundation, Inc.
17721 Source Search Path:
17722 <Current_Directory>
17724 /home/comar/local/adainclude/
17726 Object Search Path:
17727 <Current_Directory>
17729 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17731 Project Search Path:
17732 <Current_Directory>
17733 /home/comar/local/lib/gnat/
17738 Kind => subprogram body
17739 Flags => No_Elab_Code
17740 Source => demo1.adb modified
17744 The following is an example of use of the dependency list.
17745 Note the use of the -s switch
17746 which gives a straight list of source files. This can be useful for
17747 building specialized scripts.
17752 $ gnatls -d demo2.o
17753 ./demo2.o demo2 OK demo2.adb
17759 $ gnatls -d -s -a demo1.o
17761 /home/comar/local/adainclude/ada.ads
17762 /home/comar/local/adainclude/a-finali.ads
17763 /home/comar/local/adainclude/a-filico.ads
17764 /home/comar/local/adainclude/a-stream.ads
17765 /home/comar/local/adainclude/a-tags.ads
17768 /home/comar/local/adainclude/gnat.ads
17769 /home/comar/local/adainclude/g-io.ads
17771 /home/comar/local/adainclude/system.ads
17772 /home/comar/local/adainclude/s-exctab.ads
17773 /home/comar/local/adainclude/s-finimp.ads
17774 /home/comar/local/adainclude/s-finroo.ads
17775 /home/comar/local/adainclude/s-secsta.ads
17776 /home/comar/local/adainclude/s-stalib.ads
17777 /home/comar/local/adainclude/s-stoele.ads
17778 /home/comar/local/adainclude/s-stratt.ads
17779 /home/comar/local/adainclude/s-tasoli.ads
17780 /home/comar/local/adainclude/s-unstyp.ads
17781 /home/comar/local/adainclude/unchconv.ads
17785 @node The Cross-Referencing Tools gnatxref and gnatfind,The Ada to HTML Converter gnathtml,The GNAT Library Browser gnatls,GNAT Utility Programs
17786 @anchor{gnat_ugn/gnat_utility_programs the-cross-referencing-tools-gnatxref-and-gnatfind}@anchor{22}@anchor{gnat_ugn/gnat_utility_programs id9}@anchor{151}
17787 @section The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
17794 The compiler generates cross-referencing information (unless
17795 you set the @code{-gnatx} switch), which are saved in the @code{.ali} files.
17796 This information indicates where in the source each entity is declared and
17797 referenced. Note that entities in package Standard are not included, but
17798 entities in all other predefined units are included in the output.
17800 Before using any of these two tools, you need to compile successfully your
17801 application, so that GNAT gets a chance to generate the cross-referencing
17804 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
17805 information to provide the user with the capability to easily locate the
17806 declaration and references to an entity. These tools are quite similar,
17807 the difference being that @code{gnatfind} is intended for locating
17808 definitions and/or references to a specified entity or entities, whereas
17809 @code{gnatxref} is oriented to generating a full report of all
17812 To use these tools, you must not compile your application using the
17813 @code{-gnatx} switch on the @code{gnatmake} command line
17814 (see @ref{1b,,Building with gnatmake}). Otherwise, cross-referencing
17815 information will not be generated.
17818 * gnatxref Switches::
17819 * gnatfind Switches::
17820 * Configuration Files for gnatxref and gnatfind::
17821 * Regular Expressions in gnatfind and gnatxref::
17822 * Examples of gnatxref Usage::
17823 * Examples of gnatfind Usage::
17827 @node gnatxref Switches,gnatfind Switches,,The Cross-Referencing Tools gnatxref and gnatfind
17828 @anchor{gnat_ugn/gnat_utility_programs id10}@anchor{152}@anchor{gnat_ugn/gnat_utility_programs gnatxref-switches}@anchor{153}
17829 @subsection @code{gnatxref} Switches
17832 The command invocation for @code{gnatxref} is:
17837 $ gnatxref [ switches ] sourcefile1 [ sourcefile2 ... ]
17846 @item @code{sourcefile1} [, @code{sourcefile2} ...]
17848 identify the source files for which a report is to be generated. The
17849 @code{with}ed units will be processed too. You must provide at least one file.
17851 These file names are considered to be regular expressions, so for instance
17852 specifying @code{source*.adb} is the same as giving every file in the current
17853 directory whose name starts with @code{source} and whose extension is
17856 You shouldn't specify any directory name, just base names. @code{gnatxref}
17857 and @code{gnatfind} will be able to locate these files by themselves using
17858 the source path. If you specify directories, no result is produced.
17861 The following switches are available for @code{gnatxref}:
17863 @geindex --version (gnatxref)
17868 @item @code{--version}
17870 Display Copyright and version, then exit disregarding all other options.
17873 @geindex --help (gnatxref)
17878 @item @code{--help}
17880 If @code{--version} was not used, display usage, then exit disregarding
17884 @geindex -a (gnatxref)
17891 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
17892 the read-only files found in the library search path. Otherwise, these files
17893 will be ignored. This option can be used to protect Gnat sources or your own
17894 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
17895 much faster, and their output much smaller. Read-only here refers to access
17896 or permissions status in the file system for the current user.
17899 @geindex -aIDIR (gnatxref)
17904 @item @code{-aI@emph{DIR}}
17906 When looking for source files also look in directory DIR. The order in which
17907 source file search is undertaken is the same as for @code{gnatmake}.
17910 @geindex -aODIR (gnatxref)
17915 @item @code{aO@emph{DIR}}
17917 When -searching for library and object files, look in directory
17918 DIR. The order in which library files are searched is the same as for
17922 @geindex -nostdinc (gnatxref)
17927 @item @code{-nostdinc}
17929 Do not look for sources in the system default directory.
17932 @geindex -nostdlib (gnatxref)
17937 @item @code{-nostdlib}
17939 Do not look for library files in the system default directory.
17942 @geindex --ext (gnatxref)
17947 @item @code{--ext=@emph{extension}}
17949 Specify an alternate ali file extension. The default is @code{ali} and other
17950 extensions (e.g. @code{gli} for C/C++ sources when using @code{-fdump-xref})
17951 may be specified via this switch. Note that if this switch overrides the
17952 default, which means that only the new extension will be considered.
17955 @geindex --RTS (gnatxref)
17960 @item @code{--RTS=@emph{rts-path}}
17962 Specifies the default location of the runtime library. Same meaning as the
17963 equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
17966 @geindex -d (gnatxref)
17973 If this switch is set @code{gnatxref} will output the parent type
17974 reference for each matching derived types.
17977 @geindex -f (gnatxref)
17984 If this switch is set, the output file names will be preceded by their
17985 directory (if the file was found in the search path). If this switch is
17986 not set, the directory will not be printed.
17989 @geindex -g (gnatxref)
17996 If this switch is set, information is output only for library-level
17997 entities, ignoring local entities. The use of this switch may accelerate
17998 @code{gnatfind} and @code{gnatxref}.
18001 @geindex -IDIR (gnatxref)
18006 @item @code{-I@emph{DIR}}
18008 Equivalent to @code{-aODIR -aIDIR}.
18011 @geindex -pFILE (gnatxref)
18016 @item @code{-p@emph{FILE}}
18018 Specify a configuration file to use to list the source and object directories.
18020 If a file is specified, then the content of the source directory and object
18021 directory lines are added as if they had been specified respectively
18022 by @code{-aI} and @code{-aO}.
18024 See @ref{154,,Configuration Files for gnatxref and gnatfind} for the syntax
18025 of this configuration file.
18029 Output only unused symbols. This may be really useful if you give your
18030 main compilation unit on the command line, as @code{gnatxref} will then
18031 display every unused entity and 'with'ed package.
18035 Instead of producing the default output, @code{gnatxref} will generate a
18036 @code{tags} file that can be used by vi. For examples how to use this
18037 feature, see @ref{155,,Examples of gnatxref Usage}. The tags file is output
18038 to the standard output, thus you will have to redirect it to a file.
18041 All these switches may be in any order on the command line, and may even
18042 appear after the file names. They need not be separated by spaces, thus
18043 you can say @code{gnatxref -ag} instead of @code{gnatxref -a -g}.
18045 @node gnatfind Switches,Configuration Files for gnatxref and gnatfind,gnatxref Switches,The Cross-Referencing Tools gnatxref and gnatfind
18046 @anchor{gnat_ugn/gnat_utility_programs id11}@anchor{156}@anchor{gnat_ugn/gnat_utility_programs gnatfind-switches}@anchor{157}
18047 @subsection @code{gnatfind} Switches
18050 The command invocation for @code{gnatfind} is:
18055 $ gnatfind [ switches ] pattern[:sourcefile[:line[:column]]]
18060 with the following iterpretation of the command arguments:
18065 @item @emph{pattern}
18067 An entity will be output only if it matches the regular expression found
18068 in @emph{pattern}, see @ref{158,,Regular Expressions in gnatfind and gnatxref}.
18070 Omitting the pattern is equivalent to specifying @code{*}, which
18071 will match any entity. Note that if you do not provide a pattern, you
18072 have to provide both a sourcefile and a line.
18074 Entity names are given in Latin-1, with uppercase/lowercase equivalence
18075 for matching purposes. At the current time there is no support for
18076 8-bit codes other than Latin-1, or for wide characters in identifiers.
18078 @item @emph{sourcefile}
18080 @code{gnatfind} will look for references, bodies or declarations
18081 of symbols referenced in @code{sourcefile}, at line @code{line}
18082 and column @code{column}. See @ref{159,,Examples of gnatfind Usage}
18083 for syntax examples.
18087 A decimal integer identifying the line number containing
18088 the reference to the entity (or entities) to be located.
18090 @item @emph{column}
18092 A decimal integer identifying the exact location on the
18093 line of the first character of the identifier for the
18094 entity reference. Columns are numbered from 1.
18096 @item @emph{file1 file2 ...}
18098 The search will be restricted to these source files. If none are given, then
18099 the search will be conducted for every library file in the search path.
18100 These files must appear only after the pattern or sourcefile.
18102 These file names are considered to be regular expressions, so for instance
18103 specifying @code{source*.adb} is the same as giving every file in the current
18104 directory whose name starts with @code{source} and whose extension is
18107 The location of the spec of the entity will always be displayed, even if it
18108 isn't in one of @code{file1}, @code{file2}, ... The
18109 occurrences of the entity in the separate units of the ones given on the
18110 command line will also be displayed.
18112 Note that if you specify at least one file in this part, @code{gnatfind} may
18113 sometimes not be able to find the body of the subprograms.
18116 At least one of 'sourcefile' or 'pattern' has to be present on
18119 The following switches are available:
18121 @geindex --version (gnatfind)
18126 @item @code{--version}
18128 Display Copyright and version, then exit disregarding all other options.
18131 @geindex --help (gnatfind)
18136 @item @code{--help}
18138 If @code{--version} was not used, display usage, then exit disregarding
18142 @geindex -a (gnatfind)
18149 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
18150 the read-only files found in the library search path. Otherwise, these files
18151 will be ignored. This option can be used to protect Gnat sources or your own
18152 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
18153 much faster, and their output much smaller. Read-only here refers to access
18154 or permission status in the file system for the current user.
18157 @geindex -aIDIR (gnatfind)
18162 @item @code{-aI@emph{DIR}}
18164 When looking for source files also look in directory DIR. The order in which
18165 source file search is undertaken is the same as for @code{gnatmake}.
18168 @geindex -aODIR (gnatfind)
18173 @item @code{-aO@emph{DIR}}
18175 When searching for library and object files, look in directory
18176 DIR. The order in which library files are searched is the same as for
18180 @geindex -nostdinc (gnatfind)
18185 @item @code{-nostdinc}
18187 Do not look for sources in the system default directory.
18190 @geindex -nostdlib (gnatfind)
18195 @item @code{-nostdlib}
18197 Do not look for library files in the system default directory.
18200 @geindex --ext (gnatfind)
18205 @item @code{--ext=@emph{extension}}
18207 Specify an alternate ali file extension. The default is @code{ali} and other
18208 extensions (e.g. @code{gli} for C/C++ sources when using @code{-fdump-xref})
18209 may be specified via this switch. Note that if this switch overrides the
18210 default, which means that only the new extension will be considered.
18213 @geindex --RTS (gnatfind)
18218 @item @code{--RTS=@emph{rts-path}}
18220 Specifies the default location of the runtime library. Same meaning as the
18221 equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
18224 @geindex -d (gnatfind)
18231 If this switch is set, then @code{gnatfind} will output the parent type
18232 reference for each matching derived types.
18235 @geindex -e (gnatfind)
18242 By default, @code{gnatfind} accept the simple regular expression set for
18243 @code{pattern}. If this switch is set, then the pattern will be
18244 considered as full Unix-style regular expression.
18247 @geindex -f (gnatfind)
18254 If this switch is set, the output file names will be preceded by their
18255 directory (if the file was found in the search path). If this switch is
18256 not set, the directory will not be printed.
18259 @geindex -g (gnatfind)
18266 If this switch is set, information is output only for library-level
18267 entities, ignoring local entities. The use of this switch may accelerate
18268 @code{gnatfind} and @code{gnatxref}.
18271 @geindex -IDIR (gnatfind)
18276 @item @code{-I@emph{DIR}}
18278 Equivalent to @code{-aODIR -aIDIR}.
18281 @geindex -pFILE (gnatfind)
18286 @item @code{-p@emph{FILE}}
18288 Specify a configuration file to use to list the source and object directories.
18290 If a file is specified, then the content of the source directory and object
18291 directory lines are added as if they had been specified respectively
18292 by @code{-aI} and @code{-aO}.
18294 See @ref{154,,Configuration Files for gnatxref and gnatfind} for the syntax
18295 of this configuration file.
18298 @geindex -r (gnatfind)
18305 By default, @code{gnatfind} will output only the information about the
18306 declaration, body or type completion of the entities. If this switch is
18307 set, the @code{gnatfind} will locate every reference to the entities in
18308 the files specified on the command line (or in every file in the search
18309 path if no file is given on the command line).
18312 @geindex -s (gnatfind)
18319 If this switch is set, then @code{gnatfind} will output the content
18320 of the Ada source file lines were the entity was found.
18323 @geindex -t (gnatfind)
18330 If this switch is set, then @code{gnatfind} will output the type hierarchy for
18331 the specified type. It act like -d option but recursively from parent
18332 type to parent type. When this switch is set it is not possible to
18333 specify more than one file.
18336 All these switches may be in any order on the command line, and may even
18337 appear after the file names. They need not be separated by spaces, thus
18338 you can say @code{gnatxref -ag} instead of
18339 @code{gnatxref -a -g}.
18341 As stated previously, @code{gnatfind} will search in every directory in the
18342 search path. You can force it to look only in the current directory if
18343 you specify @code{*} at the end of the command line.
18345 @node Configuration Files for gnatxref and gnatfind,Regular Expressions in gnatfind and gnatxref,gnatfind Switches,The Cross-Referencing Tools gnatxref and gnatfind
18346 @anchor{gnat_ugn/gnat_utility_programs configuration-files-for-gnatxref-and-gnatfind}@anchor{154}@anchor{gnat_ugn/gnat_utility_programs id12}@anchor{15a}
18347 @subsection Configuration Files for @code{gnatxref} and @code{gnatfind}
18350 Configuration files are used by @code{gnatxref} and @code{gnatfind} to specify
18351 the list of source and object directories to consider. They can be
18352 specified via the @code{-p} switch.
18354 The following lines can be included, in any order in the file:
18363 @item @emph{src_dir=DIR}
18365 [default: @code{"./"}].
18366 Specifies a directory where to look for source files. Multiple @code{src_dir}
18367 lines can be specified and they will be searched in the order they
18375 @item @emph{obj_dir=DIR}
18377 [default: @code{"./"}].
18378 Specifies a directory where to look for object and library files. Multiple
18379 @code{obj_dir} lines can be specified, and they will be searched in the order
18384 Any other line will be silently ignored.
18386 @node Regular Expressions in gnatfind and gnatxref,Examples of gnatxref Usage,Configuration Files for gnatxref and gnatfind,The Cross-Referencing Tools gnatxref and gnatfind
18387 @anchor{gnat_ugn/gnat_utility_programs id13}@anchor{15b}@anchor{gnat_ugn/gnat_utility_programs regular-expressions-in-gnatfind-and-gnatxref}@anchor{158}
18388 @subsection Regular Expressions in @code{gnatfind} and @code{gnatxref}
18391 As specified in the section about @code{gnatfind}, the pattern can be a
18392 regular expression. Two kinds of regular expressions
18402 @item @emph{Globbing pattern}
18404 These are the most common regular expression. They are the same as are
18405 generally used in a Unix shell command line, or in a DOS session.
18407 Here is a more formal grammar:
18411 term ::= elmt -- matches elmt
18412 term ::= elmt elmt -- concatenation (elmt then elmt)
18413 term ::= * -- any string of 0 or more characters
18414 term ::= ? -- matches any character
18415 term ::= [char @{char@}] -- matches any character listed
18416 term ::= [char - char] -- matches any character in range
18424 @item @emph{Full regular expression}
18426 The second set of regular expressions is much more powerful. This is the
18427 type of regular expressions recognized by utilities such as @code{grep}.
18429 The following is the form of a regular expression, expressed in same BNF
18430 style as is found in the Ada Reference Manual:
18433 regexp ::= term @{| term@} -- alternation (term or term ...)
18435 term ::= item @{item@} -- concatenation (item then item)
18437 item ::= elmt -- match elmt
18438 item ::= elmt * -- zero or more elmt's
18439 item ::= elmt + -- one or more elmt's
18440 item ::= elmt ? -- matches elmt or nothing
18442 elmt ::= nschar -- matches given character
18443 elmt ::= [nschar @{nschar@}] -- matches any character listed
18444 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
18445 elmt ::= [char - char] -- matches chars in given range
18446 elmt ::= \\ char -- matches given character
18447 elmt ::= . -- matches any single character
18448 elmt ::= ( regexp ) -- parens used for grouping
18450 char ::= any character, including special characters
18451 nschar ::= any character except ()[].*+?^
18454 Here are a few examples:
18461 @item @code{abcde|fghi}
18463 will match any of the two strings @code{abcde} and @code{fghi},
18467 will match any string like @code{abd}, @code{abcd}, @code{abccd},
18468 @code{abcccd}, and so on,
18470 @item @code{[a-z]+}
18472 will match any string which has only lowercase characters in it (and at
18473 least one character.
18479 @node Examples of gnatxref Usage,Examples of gnatfind Usage,Regular Expressions in gnatfind and gnatxref,The Cross-Referencing Tools gnatxref and gnatfind
18480 @anchor{gnat_ugn/gnat_utility_programs examples-of-gnatxref-usage}@anchor{155}@anchor{gnat_ugn/gnat_utility_programs id14}@anchor{15c}
18481 @subsection Examples of @code{gnatxref} Usage
18486 * Using gnatxref with vi::
18490 @node General Usage,Using gnatxref with vi,,Examples of gnatxref Usage
18491 @anchor{gnat_ugn/gnat_utility_programs general-usage}@anchor{15d}
18492 @subsubsection General Usage
18495 For the following examples, we will consider the following units:
18503 3: procedure Foo (B : in Integer);
18510 1: package body Main is
18511 2: procedure Foo (B : in Integer) is
18522 2: procedure Print (B : Integer);
18527 The first thing to do is to recompile your application (for instance, in
18528 that case just by doing a @code{gnatmake main}, so that GNAT generates
18529 the cross-referencing information.
18530 You can then issue any of the following commands:
18538 @code{gnatxref main.adb}
18539 @code{gnatxref} generates cross-reference information for main.adb
18540 and every unit 'with'ed by main.adb.
18542 The output would be:
18550 Decl: main.ads 3:20
18551 Body: main.adb 2:20
18552 Ref: main.adb 4:13 5:13 6:19
18555 Ref: main.adb 6:8 7:8
18565 Decl: main.ads 3:15
18566 Body: main.adb 2:15
18569 Body: main.adb 1:14
18572 Ref: main.adb 6:12 7:12
18576 This shows that the entity @code{Main} is declared in main.ads, line 2, column 9,
18577 its body is in main.adb, line 1, column 14 and is not referenced any where.
18579 The entity @code{Print} is declared in @code{bar.ads}, line 2, column 15 and it
18580 is referenced in @code{main.adb}, line 6 column 12 and line 7 column 12.
18583 @code{gnatxref package1.adb package2.ads}
18584 @code{gnatxref} will generates cross-reference information for
18585 @code{package1.adb}, @code{package2.ads} and any other package @code{with}ed by any
18590 @node Using gnatxref with vi,,General Usage,Examples of gnatxref Usage
18591 @anchor{gnat_ugn/gnat_utility_programs using-gnatxref-with-vi}@anchor{15e}
18592 @subsubsection Using @code{gnatxref} with @code{vi}
18595 @code{gnatxref} can generate a tags file output, which can be used
18596 directly from @code{vi}. Note that the standard version of @code{vi}
18597 will not work properly with overloaded symbols. Consider using another
18598 free implementation of @code{vi}, such as @code{vim}.
18603 $ gnatxref -v gnatfind.adb > tags
18607 The following command will generate the tags file for @code{gnatfind} itself
18608 (if the sources are in the search path!):
18613 $ gnatxref -v gnatfind.adb > tags
18617 From @code{vi}, you can then use the command @code{:tag @emph{entity}}
18618 (replacing @code{entity} by whatever you are looking for), and vi will
18619 display a new file with the corresponding declaration of entity.
18621 @node Examples of gnatfind Usage,,Examples of gnatxref Usage,The Cross-Referencing Tools gnatxref and gnatfind
18622 @anchor{gnat_ugn/gnat_utility_programs id15}@anchor{15f}@anchor{gnat_ugn/gnat_utility_programs examples-of-gnatfind-usage}@anchor{159}
18623 @subsection Examples of @code{gnatfind} Usage
18630 @code{gnatfind -f xyz:main.adb}
18631 Find declarations for all entities xyz referenced at least once in
18632 main.adb. The references are search in every library file in the search
18635 The directories will be printed as well (as the @code{-f}
18638 The output will look like:
18643 directory/main.ads:106:14: xyz <= declaration
18644 directory/main.adb:24:10: xyz <= body
18645 directory/foo.ads:45:23: xyz <= declaration
18649 I.e., one of the entities xyz found in main.adb is declared at
18650 line 12 of main.ads (and its body is in main.adb), and another one is
18651 declared at line 45 of foo.ads
18654 @code{gnatfind -fs xyz:main.adb}
18655 This is the same command as the previous one, but @code{gnatfind} will
18656 display the content of the Ada source file lines.
18658 The output will look like:
18661 directory/main.ads:106:14: xyz <= declaration
18663 directory/main.adb:24:10: xyz <= body
18665 directory/foo.ads:45:23: xyz <= declaration
18669 This can make it easier to find exactly the location your are looking
18673 @code{gnatfind -r "*x*":main.ads:123 foo.adb}
18674 Find references to all entities containing an x that are
18675 referenced on line 123 of main.ads.
18676 The references will be searched only in main.ads and foo.adb.
18679 @code{gnatfind main.ads:123}
18680 Find declarations and bodies for all entities that are referenced on
18681 line 123 of main.ads.
18683 This is the same as @code{gnatfind "*":main.adb:123`}
18686 @code{gnatfind mydir/main.adb:123:45}
18687 Find the declaration for the entity referenced at column 45 in
18688 line 123 of file main.adb in directory mydir. Note that it
18689 is usual to omit the identifier name when the column is given,
18690 since the column position identifies a unique reference.
18692 The column has to be the beginning of the identifier, and should not
18693 point to any character in the middle of the identifier.
18696 @node The Ada to HTML Converter gnathtml,,The Cross-Referencing Tools gnatxref and gnatfind,GNAT Utility Programs
18697 @anchor{gnat_ugn/gnat_utility_programs the-ada-to-html-converter-gnathtml}@anchor{23}@anchor{gnat_ugn/gnat_utility_programs id16}@anchor{160}
18698 @section The Ada to HTML Converter @code{gnathtml}
18703 @code{gnathtml} is a Perl script that allows Ada source files to be browsed using
18704 standard Web browsers. For installation information, see @ref{161,,Installing gnathtml}.
18706 Ada reserved keywords are highlighted in a bold font and Ada comments in
18707 a blue font. Unless your program was compiled with the gcc @code{-gnatx}
18708 switch to suppress the generation of cross-referencing information, user
18709 defined variables and types will appear in a different color; you will
18710 be able to click on any identifier and go to its declaration.
18713 * Invoking gnathtml::
18714 * Installing gnathtml::
18718 @node Invoking gnathtml,Installing gnathtml,,The Ada to HTML Converter gnathtml
18719 @anchor{gnat_ugn/gnat_utility_programs invoking-gnathtml}@anchor{162}@anchor{gnat_ugn/gnat_utility_programs id17}@anchor{163}
18720 @subsection Invoking @code{gnathtml}
18723 The command line is as follows:
18728 $ perl gnathtml.pl [ switches ] ada-files
18732 You can specify as many Ada files as you want. @code{gnathtml} will generate
18733 an html file for every ada file, and a global file called @code{index.htm}.
18734 This file is an index of every identifier defined in the files.
18736 The following switches are available:
18738 @geindex -83 (gnathtml)
18745 Only the Ada 83 subset of keywords will be highlighted.
18748 @geindex -cc (gnathtml)
18753 @item @code{cc @emph{color}}
18755 This option allows you to change the color used for comments. The default
18756 value is green. The color argument can be any name accepted by html.
18759 @geindex -d (gnathtml)
18766 If the Ada files depend on some other files (for instance through
18767 @code{with} clauses, the latter files will also be converted to html.
18768 Only the files in the user project will be converted to html, not the files
18769 in the run-time library itself.
18772 @geindex -D (gnathtml)
18779 This command is the same as @code{-d} above, but @code{gnathtml} will
18780 also look for files in the run-time library, and generate html files for them.
18783 @geindex -ext (gnathtml)
18788 @item @code{ext @emph{extension}}
18790 This option allows you to change the extension of the generated HTML files.
18791 If you do not specify an extension, it will default to @code{htm}.
18794 @geindex -f (gnathtml)
18801 By default, gnathtml will generate html links only for global entities
18802 ('with'ed units, global variables and types,...). If you specify
18803 @code{-f} on the command line, then links will be generated for local
18807 @geindex -l (gnathtml)
18812 @item @code{l @emph{number}}
18814 If this switch is provided and @code{number} is not 0, then
18815 @code{gnathtml} will number the html files every @code{number} line.
18818 @geindex -I (gnathtml)
18823 @item @code{I @emph{dir}}
18825 Specify a directory to search for library files (@code{.ALI} files) and
18826 source files. You can provide several -I switches on the command line,
18827 and the directories will be parsed in the order of the command line.
18830 @geindex -o (gnathtml)
18835 @item @code{o @emph{dir}}
18837 Specify the output directory for html files. By default, gnathtml will
18838 saved the generated html files in a subdirectory named @code{html/}.
18841 @geindex -p (gnathtml)
18846 @item @code{p @emph{file}}
18848 If you are using Emacs and the most recent Emacs Ada mode, which provides
18849 a full Integrated Development Environment for compiling, checking,
18850 running and debugging applications, you may use @code{.gpr} files
18851 to give the directories where Emacs can find sources and object files.
18853 Using this switch, you can tell gnathtml to use these files.
18854 This allows you to get an html version of your application, even if it
18855 is spread over multiple directories.
18858 @geindex -sc (gnathtml)
18863 @item @code{sc @emph{color}}
18865 This switch allows you to change the color used for symbol
18867 The default value is red. The color argument can be any name accepted by html.
18870 @geindex -t (gnathtml)
18875 @item @code{t @emph{file}}
18877 This switch provides the name of a file. This file contains a list of
18878 file names to be converted, and the effect is exactly as though they had
18879 appeared explicitly on the command line. This
18880 is the recommended way to work around the command line length limit on some
18884 @node Installing gnathtml,,Invoking gnathtml,The Ada to HTML Converter gnathtml
18885 @anchor{gnat_ugn/gnat_utility_programs installing-gnathtml}@anchor{161}@anchor{gnat_ugn/gnat_utility_programs id18}@anchor{164}
18886 @subsection Installing @code{gnathtml}
18889 @code{Perl} needs to be installed on your machine to run this script.
18890 @code{Perl} is freely available for almost every architecture and
18891 operating system via the Internet.
18893 On Unix systems, you may want to modify the first line of the script
18894 @code{gnathtml}, to explicitly specify where Perl
18895 is located. The syntax of this line is:
18900 #!full_path_name_to_perl
18904 Alternatively, you may run the script using the following command line:
18909 $ perl gnathtml.pl [ switches ] files
18913 @c -- +---------------------------------------------------------------------+
18915 @c -- | The following sections are present only in the PRO and GPL editions |
18917 @c -- +---------------------------------------------------------------------+
18926 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
18928 @node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
18929 @anchor{gnat_ugn/gnat_and_program_execution gnat-and-program-execution}@anchor{c}@anchor{gnat_ugn/gnat_and_program_execution doc}@anchor{165}@anchor{gnat_ugn/gnat_and_program_execution id1}@anchor{166}
18930 @chapter GNAT and Program Execution
18933 This chapter covers several topics:
18939 @ref{167,,Running and Debugging Ada Programs}
18942 @ref{168,,Code Coverage and Profiling}
18945 @ref{169,,Improving Performance}
18948 @ref{16a,,Overflow Check Handling in GNAT}
18951 @ref{16b,,Performing Dimensionality Analysis in GNAT}
18954 @ref{16c,,Stack Related Facilities}
18957 @ref{16d,,Memory Management Issues}
18961 * Running and Debugging Ada Programs::
18962 * Code Coverage and Profiling::
18963 * Improving Performance::
18964 * Overflow Check Handling in GNAT::
18965 * Performing Dimensionality Analysis in GNAT::
18966 * Stack Related Facilities::
18967 * Memory Management Issues::
18971 @node Running and Debugging Ada Programs,Code Coverage and Profiling,,GNAT and Program Execution
18972 @anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{167}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{24}
18973 @section Running and Debugging Ada Programs
18978 This section discusses how to debug Ada programs.
18980 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18986 The illegality may be a violation of the static semantics of Ada. In
18987 that case GNAT diagnoses the constructs in the program that are illegal.
18988 It is then a straightforward matter for the user to modify those parts of
18992 The illegality may be a violation of the dynamic semantics of Ada. In
18993 that case the program compiles and executes, but may generate incorrect
18994 results, or may terminate abnormally with some exception.
18997 When presented with a program that contains convoluted errors, GNAT
18998 itself may terminate abnormally without providing full diagnostics on
18999 the incorrect user program.
19007 * The GNAT Debugger GDB::
19009 * Introduction to GDB Commands::
19010 * Using Ada Expressions::
19011 * Calling User-Defined Subprograms::
19012 * Using the next Command in a Function::
19013 * Stopping When Ada Exceptions Are Raised::
19015 * Debugging Generic Units::
19016 * Remote Debugging with gdbserver::
19017 * GNAT Abnormal Termination or Failure to Terminate::
19018 * Naming Conventions for GNAT Source Files::
19019 * Getting Internal Debugging Information::
19020 * Stack Traceback::
19021 * Pretty-Printers for the GNAT runtime::
19025 @node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
19026 @anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{16e}@anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{16f}
19027 @subsection The GNAT Debugger GDB
19030 @code{GDB} is a general purpose, platform-independent debugger that
19031 can be used to debug mixed-language programs compiled with @code{gcc},
19032 and in particular is capable of debugging Ada programs compiled with
19033 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19034 complex Ada data structures.
19036 See @cite{Debugging with GDB},
19037 for full details on the usage of @code{GDB}, including a section on
19038 its usage on programs. This manual should be consulted for full
19039 details. The section that follows is a brief introduction to the
19040 philosophy and use of @code{GDB}.
19042 When GNAT programs are compiled, the compiler optionally writes debugging
19043 information into the generated object file, including information on
19044 line numbers, and on declared types and variables. This information is
19045 separate from the generated code. It makes the object files considerably
19046 larger, but it does not add to the size of the actual executable that
19047 will be loaded into memory, and has no impact on run-time performance. The
19048 generation of debug information is triggered by the use of the
19049 @code{-g} switch in the @code{gcc} or @code{gnatmake} command
19050 used to carry out the compilations. It is important to emphasize that
19051 the use of these options does not change the generated code.
19053 The debugging information is written in standard system formats that
19054 are used by many tools, including debuggers and profilers. The format
19055 of the information is typically designed to describe C types and
19056 semantics, but GNAT implements a translation scheme which allows full
19057 details about Ada types and variables to be encoded into these
19058 standard C formats. Details of this encoding scheme may be found in
19059 the file exp_dbug.ads in the GNAT source distribution. However, the
19060 details of this encoding are, in general, of no interest to a user,
19061 since @code{GDB} automatically performs the necessary decoding.
19063 When a program is bound and linked, the debugging information is
19064 collected from the object files, and stored in the executable image of
19065 the program. Again, this process significantly increases the size of
19066 the generated executable file, but it does not increase the size of
19067 the executable program itself. Furthermore, if this program is run in
19068 the normal manner, it runs exactly as if the debug information were
19069 not present, and takes no more actual memory.
19071 However, if the program is run under control of @code{GDB}, the
19072 debugger is activated. The image of the program is loaded, at which
19073 point it is ready to run. If a run command is given, then the program
19074 will run exactly as it would have if @code{GDB} were not present. This
19075 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
19076 entirely non-intrusive until a breakpoint is encountered. If no
19077 breakpoint is ever hit, the program will run exactly as it would if no
19078 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19079 the debugging information and can respond to user commands to inspect
19080 variables, and more generally to report on the state of execution.
19082 @node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
19083 @anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{170}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{171}
19084 @subsection Running GDB
19087 This section describes how to initiate the debugger.
19089 The debugger can be launched from a @code{GPS} menu or
19090 directly from the command line. The description below covers the latter use.
19091 All the commands shown can be used in the @code{GPS} debug console window,
19092 but there are usually more GUI-based ways to achieve the same effect.
19094 The command to run @code{GDB} is
19103 where @code{program} is the name of the executable file. This
19104 activates the debugger and results in a prompt for debugger commands.
19105 The simplest command is simply @code{run}, which causes the program to run
19106 exactly as if the debugger were not present. The following section
19107 describes some of the additional commands that can be given to @code{GDB}.
19109 @node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
19110 @anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{172}@anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{173}
19111 @subsection Introduction to GDB Commands
19114 @code{GDB} contains a large repertoire of commands.
19115 See @cite{Debugging with GDB} for extensive documentation on the use
19116 of these commands, together with examples of their use. Furthermore,
19117 the command @emph{help} invoked from within GDB activates a simple help
19118 facility which summarizes the available commands and their options.
19119 In this section we summarize a few of the most commonly
19120 used commands to give an idea of what @code{GDB} is about. You should create
19121 a simple program with debugging information and experiment with the use of
19122 these @code{GDB} commands on the program as you read through the
19132 @item @code{set args @emph{arguments}}
19134 The @emph{arguments} list above is a list of arguments to be passed to
19135 the program on a subsequent run command, just as though the arguments
19136 had been entered on a normal invocation of the program. The @code{set args}
19137 command is not needed if the program does not require arguments.
19146 The @code{run} command causes execution of the program to start from
19147 the beginning. If the program is already running, that is to say if
19148 you are currently positioned at a breakpoint, then a prompt will ask
19149 for confirmation that you want to abandon the current execution and
19157 @item @code{breakpoint @emph{location}}
19159 The breakpoint command sets a breakpoint, that is to say a point at which
19160 execution will halt and @code{GDB} will await further
19161 commands. @emph{location} is
19162 either a line number within a file, given in the format @code{file:linenumber},
19163 or it is the name of a subprogram. If you request that a breakpoint be set on
19164 a subprogram that is overloaded, a prompt will ask you to specify on which of
19165 those subprograms you want to breakpoint. You can also
19166 specify that all of them should be breakpointed. If the program is run
19167 and execution encounters the breakpoint, then the program
19168 stops and @code{GDB} signals that the breakpoint was encountered by
19169 printing the line of code before which the program is halted.
19176 @item @code{catch exception @emph{name}}
19178 This command causes the program execution to stop whenever exception
19179 @code{name} is raised. If @code{name} is omitted, then the execution is
19180 suspended when any exception is raised.
19187 @item @code{print @emph{expression}}
19189 This will print the value of the given expression. Most simple
19190 Ada expression formats are properly handled by @code{GDB}, so the expression
19191 can contain function calls, variables, operators, and attribute references.
19198 @item @code{continue}
19200 Continues execution following a breakpoint, until the next breakpoint or the
19201 termination of the program.
19210 Executes a single line after a breakpoint. If the next statement
19211 is a subprogram call, execution continues into (the first statement of)
19212 the called subprogram.
19221 Executes a single line. If this line is a subprogram call, executes and
19222 returns from the call.
19231 Lists a few lines around the current source location. In practice, it
19232 is usually more convenient to have a separate edit window open with the
19233 relevant source file displayed. Successive applications of this command
19234 print subsequent lines. The command can be given an argument which is a
19235 line number, in which case it displays a few lines around the specified one.
19242 @item @code{backtrace}
19244 Displays a backtrace of the call chain. This command is typically
19245 used after a breakpoint has occurred, to examine the sequence of calls that
19246 leads to the current breakpoint. The display includes one line for each
19247 activation record (frame) corresponding to an active subprogram.
19256 At a breakpoint, @code{GDB} can display the values of variables local
19257 to the current frame. The command @code{up} can be used to
19258 examine the contents of other active frames, by moving the focus up
19259 the stack, that is to say from callee to caller, one frame at a time.
19268 Moves the focus of @code{GDB} down from the frame currently being
19269 examined to the frame of its callee (the reverse of the previous command),
19276 @item @code{frame @emph{n}}
19278 Inspect the frame with the given number. The value 0 denotes the frame
19279 of the current breakpoint, that is to say the top of the call stack.
19288 Kills the child process in which the program is running under GDB.
19289 This may be useful for several purposes:
19295 It allows you to recompile and relink your program, since on many systems
19296 you cannot regenerate an executable file while it is running in a process.
19299 You can run your program outside the debugger, on systems that do not
19300 permit executing a program outside GDB while breakpoints are set
19304 It allows you to debug a core dump rather than a running process.
19309 The above list is a very short introduction to the commands that
19310 @code{GDB} provides. Important additional capabilities, including conditional
19311 breakpoints, the ability to execute command sequences on a breakpoint,
19312 the ability to debug at the machine instruction level and many other
19313 features are described in detail in @cite{Debugging with GDB}.
19314 Note that most commands can be abbreviated
19315 (for example, c for continue, bt for backtrace).
19317 @node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
19318 @anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{174}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{175}
19319 @subsection Using Ada Expressions
19322 @geindex Ada expressions (in gdb)
19324 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19325 extensions. The philosophy behind the design of this subset is
19333 That @code{GDB} should provide basic literals and access to operations for
19334 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19335 leaving more sophisticated computations to subprograms written into the
19336 program (which therefore may be called from @code{GDB}).
19339 That type safety and strict adherence to Ada language restrictions
19340 are not particularly relevant in a debugging context.
19343 That brevity is important to the @code{GDB} user.
19347 Thus, for brevity, the debugger acts as if there were
19348 implicit @code{with} and @code{use} clauses in effect for all user-written
19349 packages, thus making it unnecessary to fully qualify most names with
19350 their packages, regardless of context. Where this causes ambiguity,
19351 @code{GDB} asks the user's intent.
19353 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
19355 @node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
19356 @anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{176}@anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{177}
19357 @subsection Calling User-Defined Subprograms
19360 An important capability of @code{GDB} is the ability to call user-defined
19361 subprograms while debugging. This is achieved simply by entering
19362 a subprogram call statement in the form:
19367 call subprogram-name (parameters)
19371 The keyword @code{call} can be omitted in the normal case where the
19372 @code{subprogram-name} does not coincide with any of the predefined
19373 @code{GDB} commands.
19375 The effect is to invoke the given subprogram, passing it the
19376 list of parameters that is supplied. The parameters can be expressions and
19377 can include variables from the program being debugged. The
19378 subprogram must be defined
19379 at the library level within your program, and @code{GDB} will call the
19380 subprogram within the environment of your program execution (which
19381 means that the subprogram is free to access or even modify variables
19382 within your program).
19384 The most important use of this facility is in allowing the inclusion of
19385 debugging routines that are tailored to particular data structures
19386 in your program. Such debugging routines can be written to provide a suitably
19387 high-level description of an abstract type, rather than a low-level dump
19388 of its physical layout. After all, the standard
19389 @code{GDB print} command only knows the physical layout of your
19390 types, not their abstract meaning. Debugging routines can provide information
19391 at the desired semantic level and are thus enormously useful.
19393 For example, when debugging GNAT itself, it is crucial to have access to
19394 the contents of the tree nodes used to represent the program internally.
19395 But tree nodes are represented simply by an integer value (which in turn
19396 is an index into a table of nodes).
19397 Using the @code{print} command on a tree node would simply print this integer
19398 value, which is not very useful. But the PN routine (defined in file
19399 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19400 a useful high level representation of the tree node, which includes the
19401 syntactic category of the node, its position in the source, the integers
19402 that denote descendant nodes and parent node, as well as varied
19403 semantic information. To study this example in more detail, you might want to
19404 look at the body of the PN procedure in the stated file.
19406 Another useful application of this capability is to deal with situations of
19407 complex data which are not handled suitably by GDB. For example, if you specify
19408 Convention Fortran for a multi-dimensional array, GDB does not know that
19409 the ordering of array elements has been switched and will not properly
19410 address the array elements. In such a case, instead of trying to print the
19411 elements directly from GDB, you can write a callable procedure that prints
19412 the elements in the desired format.
19414 @node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
19415 @anchor{gnat_ugn/gnat_and_program_execution using-the-next-command-in-a-function}@anchor{178}@anchor{gnat_ugn/gnat_and_program_execution id8}@anchor{179}
19416 @subsection Using the @emph{next} Command in a Function
19419 When you use the @code{next} command in a function, the current source
19420 location will advance to the next statement as usual. A special case
19421 arises in the case of a @code{return} statement.
19423 Part of the code for a return statement is the 'epilogue' of the function.
19424 This is the code that returns to the caller. There is only one copy of
19425 this epilogue code, and it is typically associated with the last return
19426 statement in the function if there is more than one return. In some
19427 implementations, this epilogue is associated with the first statement
19430 The result is that if you use the @code{next} command from a return
19431 statement that is not the last return statement of the function you
19432 may see a strange apparent jump to the last return statement or to
19433 the start of the function. You should simply ignore this odd jump.
19434 The value returned is always that from the first return statement
19435 that was stepped through.
19437 @node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
19438 @anchor{gnat_ugn/gnat_and_program_execution stopping-when-ada-exceptions-are-raised}@anchor{17a}@anchor{gnat_ugn/gnat_and_program_execution id9}@anchor{17b}
19439 @subsection Stopping When Ada Exceptions Are Raised
19442 @geindex Exceptions (in gdb)
19444 You can set catchpoints that stop the program execution when your program
19445 raises selected exceptions.
19454 @item @code{catch exception}
19456 Set a catchpoint that stops execution whenever (any task in the) program
19457 raises any exception.
19464 @item @code{catch exception @emph{name}}
19466 Set a catchpoint that stops execution whenever (any task in the) program
19467 raises the exception @emph{name}.
19474 @item @code{catch exception unhandled}
19476 Set a catchpoint that stops executing whenever (any task in the) program
19477 raises an exception for which there is no handler.
19484 @item @code{info exceptions}, @code{info exceptions @emph{regexp}}
19486 The @code{info exceptions} command permits the user to examine all defined
19487 exceptions within Ada programs. With a regular expression, @emph{regexp}, as
19488 argument, prints out only those exceptions whose name matches @emph{regexp}.
19492 @geindex Tasks (in gdb)
19494 @node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
19495 @anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{17c}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{17d}
19496 @subsection Ada Tasks
19499 @code{GDB} allows the following task-related commands:
19508 @item @code{info tasks}
19510 This command shows a list of current Ada tasks, as in the following example:
19514 ID TID P-ID Thread Pri State Name
19515 1 8088000 0 807e000 15 Child Activation Wait main_task
19516 2 80a4000 1 80ae000 15 Accept/Select Wait b
19517 3 809a800 1 80a4800 15 Child Activation Wait a
19518 * 4 80ae800 3 80b8000 15 Running c
19521 In this listing, the asterisk before the first task indicates it to be the
19522 currently running task. The first column lists the task ID that is used
19523 to refer to tasks in the following commands.
19527 @geindex Breakpoints and tasks
19533 @code{break`@w{`}*linespec* `@w{`}task} @emph{taskid}, @code{break} @emph{linespec} @code{task} @emph{taskid} @code{if} ...
19537 These commands are like the @code{break ... thread ...}.
19538 @emph{linespec} specifies source lines.
19540 Use the qualifier @code{task @emph{taskid}} with a breakpoint command
19541 to specify that you only want @code{GDB} to stop the program when a
19542 particular Ada task reaches this breakpoint. @emph{taskid} is one of the
19543 numeric task identifiers assigned by @code{GDB}, shown in the first
19544 column of the @code{info tasks} display.
19546 If you do not specify @code{task @emph{taskid}} when you set a
19547 breakpoint, the breakpoint applies to @emph{all} tasks of your
19550 You can use the @code{task} qualifier on conditional breakpoints as
19551 well; in this case, place @code{task @emph{taskid}} before the
19552 breakpoint condition (before the @code{if}).
19556 @geindex Task switching (in gdb)
19562 @code{task @emph{taskno}}
19566 This command allows switching to the task referred by @emph{taskno}. In
19567 particular, this allows browsing of the backtrace of the specified
19568 task. It is advisable to switch back to the original task before
19569 continuing execution otherwise the scheduling of the program may be
19574 For more detailed information on the tasking support,
19575 see @cite{Debugging with GDB}.
19577 @geindex Debugging Generic Units
19581 @node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
19582 @anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{17e}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{17f}
19583 @subsection Debugging Generic Units
19586 GNAT always uses code expansion for generic instantiation. This means that
19587 each time an instantiation occurs, a complete copy of the original code is
19588 made, with appropriate substitutions of formals by actuals.
19590 It is not possible to refer to the original generic entities in
19591 @code{GDB}, but it is always possible to debug a particular instance of
19592 a generic, by using the appropriate expanded names. For example, if we have
19599 generic package k is
19600 procedure kp (v1 : in out integer);
19604 procedure kp (v1 : in out integer) is
19610 package k1 is new k;
19611 package k2 is new k;
19613 var : integer := 1;
19624 Then to break on a call to procedure kp in the k2 instance, simply
19630 (gdb) break g.k2.kp
19634 When the breakpoint occurs, you can step through the code of the
19635 instance in the normal manner and examine the values of local variables, as for
19638 @geindex Remote Debugging with gdbserver
19640 @node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
19641 @anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{180}@anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{181}
19642 @subsection Remote Debugging with gdbserver
19645 On platforms where gdbserver is supported, it is possible to use this tool
19646 to debug your application remotely. This can be useful in situations
19647 where the program needs to be run on a target host that is different
19648 from the host used for development, particularly when the target has
19649 a limited amount of resources (either CPU and/or memory).
19651 To do so, start your program using gdbserver on the target machine.
19652 gdbserver then automatically suspends the execution of your program
19653 at its entry point, waiting for a debugger to connect to it. The
19654 following commands starts an application and tells gdbserver to
19655 wait for a connection with the debugger on localhost port 4444.
19660 $ gdbserver localhost:4444 program
19661 Process program created; pid = 5685
19662 Listening on port 4444
19666 Once gdbserver has started listening, we can tell the debugger to establish
19667 a connection with this gdbserver, and then start the same debugging session
19668 as if the program was being debugged on the same host, directly under
19669 the control of GDB.
19675 (gdb) target remote targethost:4444
19676 Remote debugging using targethost:4444
19677 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19679 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19683 Breakpoint 1, foo () at foo.adb:4
19688 It is also possible to use gdbserver to attach to an already running
19689 program, in which case the execution of that program is simply suspended
19690 until the connection between the debugger and gdbserver is established.
19692 For more information on how to use gdbserver, see the @emph{Using the gdbserver Program}
19693 section in @cite{Debugging with GDB}.
19694 GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
19696 @geindex Abnormal Termination or Failure to Terminate
19698 @node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
19699 @anchor{gnat_ugn/gnat_and_program_execution gnat-abnormal-termination-or-failure-to-terminate}@anchor{182}@anchor{gnat_ugn/gnat_and_program_execution id13}@anchor{183}
19700 @subsection GNAT Abnormal Termination or Failure to Terminate
19703 When presented with programs that contain serious errors in syntax
19705 GNAT may on rare occasions experience problems in operation, such
19707 segmentation fault or illegal memory access, raising an internal
19708 exception, terminating abnormally, or failing to terminate at all.
19709 In such cases, you can activate
19710 various features of GNAT that can help you pinpoint the construct in your
19711 program that is the likely source of the problem.
19713 The following strategies are presented in increasing order of
19714 difficulty, corresponding to your experience in using GNAT and your
19715 familiarity with compiler internals.
19721 Run @code{gcc} with the @code{-gnatf}. This first
19722 switch causes all errors on a given line to be reported. In its absence,
19723 only the first error on a line is displayed.
19725 The @code{-gnatdO} switch causes errors to be displayed as soon as they
19726 are encountered, rather than after compilation is terminated. If GNAT
19727 terminates prematurely or goes into an infinite loop, the last error
19728 message displayed may help to pinpoint the culprit.
19731 Run @code{gcc} with the @code{-v} (verbose) switch. In this
19732 mode, @code{gcc} produces ongoing information about the progress of the
19733 compilation and provides the name of each procedure as code is
19734 generated. This switch allows you to find which Ada procedure was being
19735 compiled when it encountered a code generation problem.
19738 @geindex -gnatdc switch
19744 Run @code{gcc} with the @code{-gnatdc} switch. This is a GNAT specific
19745 switch that does for the front-end what @code{-v} does
19746 for the back end. The system prints the name of each unit,
19747 either a compilation unit or nested unit, as it is being analyzed.
19750 Finally, you can start
19751 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19752 front-end of GNAT, and can be run independently (normally it is just
19753 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
19754 would on a C program (but @ref{16e,,The GNAT Debugger GDB} for caveats). The
19755 @code{where} command is the first line of attack; the variable
19756 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19757 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
19758 which the execution stopped, and @code{input_file name} indicates the name of
19762 @node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
19763 @anchor{gnat_ugn/gnat_and_program_execution naming-conventions-for-gnat-source-files}@anchor{184}@anchor{gnat_ugn/gnat_and_program_execution id14}@anchor{185}
19764 @subsection Naming Conventions for GNAT Source Files
19767 In order to examine the workings of the GNAT system, the following
19768 brief description of its organization may be helpful:
19774 Files with prefix @code{sc} contain the lexical scanner.
19777 All files prefixed with @code{par} are components of the parser. The
19778 numbers correspond to chapters of the Ada Reference Manual. For example,
19779 parsing of select statements can be found in @code{par-ch9.adb}.
19782 All files prefixed with @code{sem} perform semantic analysis. The
19783 numbers correspond to chapters of the Ada standard. For example, all
19784 issues involving context clauses can be found in @code{sem_ch10.adb}. In
19785 addition, some features of the language require sufficient special processing
19786 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19787 dynamic dispatching, etc.
19790 All files prefixed with @code{exp} perform normalization and
19791 expansion of the intermediate representation (abstract syntax tree, or AST).
19792 these files use the same numbering scheme as the parser and semantics files.
19793 For example, the construction of record initialization procedures is done in
19794 @code{exp_ch3.adb}.
19797 The files prefixed with @code{bind} implement the binder, which
19798 verifies the consistency of the compilation, determines an order of
19799 elaboration, and generates the bind file.
19802 The files @code{atree.ads} and @code{atree.adb} detail the low-level
19803 data structures used by the front-end.
19806 The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
19807 the abstract syntax tree as produced by the parser.
19810 The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
19811 all entities, computed during semantic analysis.
19814 Library management issues are dealt with in files with prefix
19817 @geindex Annex A (in Ada Reference Manual)
19820 Ada files with the prefix @code{a-} are children of @code{Ada}, as
19821 defined in Annex A.
19823 @geindex Annex B (in Ada reference Manual)
19826 Files with prefix @code{i-} are children of @code{Interfaces}, as
19827 defined in Annex B.
19829 @geindex System (package in Ada Reference Manual)
19832 Files with prefix @code{s-} are children of @code{System}. This includes
19833 both language-defined children and GNAT run-time routines.
19835 @geindex GNAT (package)
19838 Files with prefix @code{g-} are children of @code{GNAT}. These are useful
19839 general-purpose packages, fully documented in their specs. All
19840 the other @code{.c} files are modifications of common @code{gcc} files.
19843 @node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
19844 @anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{186}@anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{187}
19845 @subsection Getting Internal Debugging Information
19848 Most compilers have internal debugging switches and modes. GNAT
19849 does also, except GNAT internal debugging switches and modes are not
19850 secret. A summary and full description of all the compiler and binder
19851 debug flags are in the file @code{debug.adb}. You must obtain the
19852 sources of the compiler to see the full detailed effects of these flags.
19854 The switches that print the source of the program (reconstructed from
19855 the internal tree) are of general interest for user programs, as are the
19857 the full internal tree, and the entity table (the symbol table
19858 information). The reconstructed source provides a readable version of the
19859 program after the front-end has completed analysis and expansion,
19860 and is useful when studying the performance of specific constructs.
19861 For example, constraint checks are indicated, complex aggregates
19862 are replaced with loops and assignments, and tasking primitives
19863 are replaced with run-time calls.
19867 @geindex stack traceback
19869 @geindex stack unwinding
19871 @node Stack Traceback,Pretty-Printers for the GNAT runtime,Getting Internal Debugging Information,Running and Debugging Ada Programs
19872 @anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{188}@anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{189}
19873 @subsection Stack Traceback
19876 Traceback is a mechanism to display the sequence of subprogram calls that
19877 leads to a specified execution point in a program. Often (but not always)
19878 the execution point is an instruction at which an exception has been raised.
19879 This mechanism is also known as @emph{stack unwinding} because it obtains
19880 its information by scanning the run-time stack and recovering the activation
19881 records of all active subprograms. Stack unwinding is one of the most
19882 important tools for program debugging.
19884 The first entry stored in traceback corresponds to the deepest calling level,
19885 that is to say the subprogram currently executing the instruction
19886 from which we want to obtain the traceback.
19888 Note that there is no runtime performance penalty when stack traceback
19889 is enabled, and no exception is raised during program execution.
19892 @geindex non-symbolic
19895 * Non-Symbolic Traceback::
19896 * Symbolic Traceback::
19900 @node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
19901 @anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{18a}@anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{18b}
19902 @subsubsection Non-Symbolic Traceback
19905 Note: this feature is not supported on all platforms. See
19906 @code{GNAT.Traceback} spec in @code{g-traceb.ads}
19907 for a complete list of supported platforms.
19909 @subsubheading Tracebacks From an Unhandled Exception
19912 A runtime non-symbolic traceback is a list of addresses of call instructions.
19913 To enable this feature you must use the @code{-E}
19914 @code{gnatbind} option. With this option a stack traceback is stored as part
19915 of exception information. You can retrieve this information using the
19916 @code{addr2line} tool.
19918 Here is a simple example:
19927 raise Constraint_Error;
19941 $ gnatmake stb -bargs -E
19944 Execution terminated by unhandled exception
19945 Exception name: CONSTRAINT_ERROR
19947 Call stack traceback locations:
19948 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19952 As we see the traceback lists a sequence of addresses for the unhandled
19953 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19954 guess that this exception come from procedure P1. To translate these
19955 addresses into the source lines where the calls appear, the
19956 @code{addr2line} tool, described below, is invaluable. The use of this tool
19957 requires the program to be compiled with debug information.
19962 $ gnatmake -g stb -bargs -E
19965 Execution terminated by unhandled exception
19966 Exception name: CONSTRAINT_ERROR
19968 Call stack traceback locations:
19969 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19971 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19972 0x4011f1 0x77e892a4
19974 00401373 at d:/stb/stb.adb:5
19975 0040138B at d:/stb/stb.adb:10
19976 0040139C at d:/stb/stb.adb:14
19977 00401335 at d:/stb/b~stb.adb:104
19978 004011C4 at /build/.../crt1.c:200
19979 004011F1 at /build/.../crt1.c:222
19980 77E892A4 in ?? at ??:0
19984 The @code{addr2line} tool has several other useful options:
19989 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
19996 to get the function name corresponding to any location
20000 @code{--demangle=gnat}
20004 to use the gnat decoding mode for the function names.
20005 Note that for binutils version 2.9.x the option is
20006 simply @code{--demangle}.
20012 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
20013 0x40139c 0x401335 0x4011c4 0x4011f1
20015 00401373 in stb.p1 at d:/stb/stb.adb:5
20016 0040138B in stb.p2 at d:/stb/stb.adb:10
20017 0040139C in stb at d:/stb/stb.adb:14
20018 00401335 in main at d:/stb/b~stb.adb:104
20019 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
20020 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
20024 From this traceback we can see that the exception was raised in
20025 @code{stb.adb} at line 5, which was reached from a procedure call in
20026 @code{stb.adb} at line 10, and so on. The @code{b~std.adb} is the binder file,
20027 which contains the call to the main program.
20028 @ref{11c,,Running gnatbind}. The remaining entries are assorted runtime routines,
20029 and the output will vary from platform to platform.
20031 It is also possible to use @code{GDB} with these traceback addresses to debug
20032 the program. For example, we can break at a given code location, as reported
20033 in the stack traceback:
20042 Furthermore, this feature is not implemented inside Windows DLL. Only
20043 the non-symbolic traceback is reported in this case.
20048 (gdb) break *0x401373
20049 Breakpoint 1 at 0x401373: file stb.adb, line 5.
20053 It is important to note that the stack traceback addresses
20054 do not change when debug information is included. This is particularly useful
20055 because it makes it possible to release software without debug information (to
20056 minimize object size), get a field report that includes a stack traceback
20057 whenever an internal bug occurs, and then be able to retrieve the sequence
20058 of calls with the same program compiled with debug information.
20060 @subsubheading Tracebacks From Exception Occurrences
20063 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
20064 The stack traceback is attached to the exception information string, and can
20065 be retrieved in an exception handler within the Ada program, by means of the
20066 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
20072 with Ada.Exceptions;
20077 use Ada.Exceptions;
20085 Text_IO.Put_Line (Exception_Information (E));
20099 This program will output:
20106 Exception name: CONSTRAINT_ERROR
20107 Message: stb.adb:12
20108 Call stack traceback locations:
20109 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20113 @subsubheading Tracebacks From Anywhere in a Program
20116 It is also possible to retrieve a stack traceback from anywhere in a
20117 program. For this you need to
20118 use the @code{GNAT.Traceback} API. This package includes a procedure called
20119 @code{Call_Chain} that computes a complete stack traceback, as well as useful
20120 display procedures described below. It is not necessary to use the
20121 @code{-E} @code{gnatbind} option in this case, because the stack traceback mechanism
20122 is invoked explicitly.
20124 In the following example we compute a traceback at a specific location in
20125 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20126 convert addresses to strings:
20132 with GNAT.Traceback;
20133 with GNAT.Debug_Utilities;
20139 use GNAT.Traceback;
20142 TB : Tracebacks_Array (1 .. 10);
20143 -- We are asking for a maximum of 10 stack frames.
20145 -- Len will receive the actual number of stack frames returned.
20147 Call_Chain (TB, Len);
20149 Text_IO.Put ("In STB.P1 : ");
20151 for K in 1 .. Len loop
20152 Text_IO.Put (Debug_Utilities.Image (TB (K)));
20173 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20174 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20178 You can then get further information by invoking the @code{addr2line}
20179 tool as described earlier (note that the hexadecimal addresses
20180 need to be specified in C format, with a leading '0x').
20185 @node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
20186 @anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{18c}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{18d}
20187 @subsubsection Symbolic Traceback
20190 A symbolic traceback is a stack traceback in which procedure names are
20191 associated with each code location.
20193 Note that this feature is not supported on all platforms. See
20194 @code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
20195 list of currently supported platforms.
20197 Note that the symbolic traceback requires that the program be compiled
20198 with debug information. If it is not compiled with debug information
20199 only the non-symbolic information will be valid.
20201 @subsubheading Tracebacks From Exception Occurrences
20204 Here is an example:
20210 with GNAT.Traceback.Symbolic;
20216 raise Constraint_Error;
20233 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20238 $ gnatmake -g .\stb -bargs -E
20241 0040149F in stb.p1 at stb.adb:8
20242 004014B7 in stb.p2 at stb.adb:13
20243 004014CF in stb.p3 at stb.adb:18
20244 004015DD in ada.stb at stb.adb:22
20245 00401461 in main at b~stb.adb:168
20246 004011C4 in __mingw_CRTStartup at crt1.c:200
20247 004011F1 in mainCRTStartup at crt1.c:222
20248 77E892A4 in ?? at ??:0
20252 In the above example the @code{.\} syntax in the @code{gnatmake} command
20253 is currently required by @code{addr2line} for files that are in
20254 the current working directory.
20255 Moreover, the exact sequence of linker options may vary from platform
20257 The above @code{-largs} section is for Windows platforms. By contrast,
20258 under Unix there is no need for the @code{-largs} section.
20259 Differences across platforms are due to details of linker implementation.
20261 @subsubheading Tracebacks From Anywhere in a Program
20264 It is possible to get a symbolic stack traceback
20265 from anywhere in a program, just as for non-symbolic tracebacks.
20266 The first step is to obtain a non-symbolic
20267 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20268 information. Here is an example:
20274 with GNAT.Traceback;
20275 with GNAT.Traceback.Symbolic;
20280 use GNAT.Traceback;
20281 use GNAT.Traceback.Symbolic;
20284 TB : Tracebacks_Array (1 .. 10);
20285 -- We are asking for a maximum of 10 stack frames.
20287 -- Len will receive the actual number of stack frames returned.
20289 Call_Chain (TB, Len);
20290 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20304 @subsubheading Automatic Symbolic Tracebacks
20307 Symbolic tracebacks may also be enabled by using the -Es switch to gnatbind (as
20308 in @code{gprbuild -g ... -bargs -Es}).
20309 This will cause the Exception_Information to contain a symbolic traceback,
20310 which will also be printed if an unhandled exception terminates the
20313 @node Pretty-Printers for the GNAT runtime,,Stack Traceback,Running and Debugging Ada Programs
20314 @anchor{gnat_ugn/gnat_and_program_execution id19}@anchor{18e}@anchor{gnat_ugn/gnat_and_program_execution pretty-printers-for-the-gnat-runtime}@anchor{18f}
20315 @subsection Pretty-Printers for the GNAT runtime
20318 As discussed in @cite{Calling User-Defined Subprograms}, GDB's
20319 @code{print} command only knows about the physical layout of program data
20320 structures and therefore normally displays only low-level dumps, which
20321 are often hard to understand.
20323 An example of this is when trying to display the contents of an Ada
20324 standard container, such as @code{Ada.Containers.Ordered_Maps.Map}:
20329 with Ada.Containers.Ordered_Maps;
20332 package Int_To_Nat is
20333 new Ada.Containers.Ordered_Maps (Integer, Natural);
20335 Map : Int_To_Nat.Map;
20337 Map.Insert (1, 10);
20338 Map.Insert (2, 20);
20339 Map.Insert (3, 30);
20341 Map.Clear; -- BREAK HERE
20346 When this program is built with debugging information and run under
20347 GDB up to the @code{Map.Clear} statement, trying to print @code{Map} will
20348 yield information that is only relevant to the developers of our standard
20370 Fortunately, GDB has a feature called pretty-printers@footnote{http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Introduction},
20371 which allows customizing how GDB displays data structures. The GDB
20372 shipped with GNAT embeds such pretty-printers for the most common
20373 containers in the standard library. To enable them, either run the
20374 following command manually under GDB or add it to your @code{.gdbinit} file:
20379 python import gnatdbg; gnatdbg.setup()
20383 Once this is done, GDB's @code{print} command will automatically use
20384 these pretty-printers when appropriate. Using the previous example:
20390 $1 = pp.int_to_nat.map of length 3 = @{
20398 Pretty-printers are invoked each time GDB tries to display a value,
20399 including when displaying the arguments of a called subprogram (in
20400 GDB's @code{backtrace} command) or when printing the value returned by a
20401 function (in GDB's @code{finish} command).
20403 To display a value without involving pretty-printers, @code{print} can be
20404 invoked with its @code{/r} option:
20415 Finer control of pretty-printers is also possible: see GDB's online documentation@footnote{http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Commands}
20416 for more information.
20418 @geindex Code Coverage
20422 @node Code Coverage and Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
20423 @anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{168}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-and-profiling}@anchor{25}
20424 @section Code Coverage and Profiling
20427 This section describes how to use the @code{gcov} coverage testing tool and
20428 the @code{gprof} profiler tool on Ada programs.
20433 * Code Coverage of Ada Programs with gcov::
20434 * Profiling an Ada Program with gprof::
20438 @node Code Coverage of Ada Programs with gcov,Profiling an Ada Program with gprof,,Code Coverage and Profiling
20439 @anchor{gnat_ugn/gnat_and_program_execution id21}@anchor{190}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-of-ada-programs-with-gcov}@anchor{191}
20440 @subsection Code Coverage of Ada Programs with gcov
20443 @code{gcov} is a test coverage program: it analyzes the execution of a given
20444 program on selected tests, to help you determine the portions of the program
20445 that are still untested.
20447 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
20448 User's Guide. You can refer to this documentation for a more complete
20451 This chapter provides a quick startup guide, and
20452 details some GNAT-specific features.
20455 * Quick startup guide::
20460 @node Quick startup guide,GNAT specifics,,Code Coverage of Ada Programs with gcov
20461 @anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{192}@anchor{gnat_ugn/gnat_and_program_execution quick-startup-guide}@anchor{193}
20462 @subsubsection Quick startup guide
20465 In order to perform coverage analysis of a program using @code{gcov}, several
20472 Instrument the code during the compilation process,
20475 Execute the instrumented program, and
20478 Invoke the @code{gcov} tool to generate the coverage results.
20481 @geindex -fprofile-arcs (gcc)
20483 @geindex -ftest-coverage (gcc
20485 @geindex -fprofile-arcs (gnatbind)
20487 The code instrumentation needed by gcov is created at the object level.
20488 The source code is not modified in any way, because the instrumentation code is
20489 inserted by gcc during the compilation process. To compile your code with code
20490 coverage activated, you need to recompile your whole project using the
20492 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20493 @code{-fprofile-arcs}.
20498 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \\
20499 -largs -fprofile-arcs
20503 This compilation process will create @code{.gcno} files together with
20504 the usual object files.
20506 Once the program is compiled with coverage instrumentation, you can
20507 run it as many times as needed -- on portions of a test suite for
20508 example. The first execution will produce @code{.gcda} files at the
20509 same location as the @code{.gcno} files. Subsequent executions
20510 will update those files, so that a cumulative result of the covered
20511 portions of the program is generated.
20513 Finally, you need to call the @code{gcov} tool. The different options of
20514 @code{gcov} are described in the GCC User's Guide, section @emph{Invoking gcov}.
20516 This will create annotated source files with a @code{.gcov} extension:
20517 @code{my_main.adb} file will be analyzed in @code{my_main.adb.gcov}.
20519 @node GNAT specifics,,Quick startup guide,Code Coverage of Ada Programs with gcov
20520 @anchor{gnat_ugn/gnat_and_program_execution gnat-specifics}@anchor{194}@anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{195}
20521 @subsubsection GNAT specifics
20524 Because of Ada semantics, portions of the source code may be shared among
20525 several object files. This is the case for example when generics are
20526 involved, when inlining is active or when declarations generate initialisation
20527 calls. In order to take
20528 into account this shared code, you need to call @code{gcov} on all
20529 source files of the tested program at once.
20531 The list of source files might exceed the system's maximum command line
20532 length. In order to bypass this limitation, a new mechanism has been
20533 implemented in @code{gcov}: you can now list all your project's files into a
20534 text file, and provide this file to gcov as a parameter, preceded by a @code{@@}
20535 (e.g. @code{gcov @@mysrclist.txt}).
20537 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20538 not supported as there can be unresolved symbols during the final link.
20544 @node Profiling an Ada Program with gprof,,Code Coverage of Ada Programs with gcov,Code Coverage and Profiling
20545 @anchor{gnat_ugn/gnat_and_program_execution profiling-an-ada-program-with-gprof}@anchor{196}@anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{197}
20546 @subsection Profiling an Ada Program with gprof
20549 This section is not meant to be an exhaustive documentation of @code{gprof}.
20550 Full documentation for it can be found in the @cite{GNU Profiler User's Guide}
20551 documentation that is part of this GNAT distribution.
20553 Profiling a program helps determine the parts of a program that are executed
20554 most often, and are therefore the most time-consuming.
20556 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
20557 better handle Ada programs and multitasking.
20558 It is currently supported on the following platforms
20567 solaris sparc/sparc64/x86
20573 In order to profile a program using @code{gprof}, several steps are needed:
20579 Instrument the code, which requires a full recompilation of the project with the
20583 Execute the program under the analysis conditions, i.e. with the desired
20587 Analyze the results using the @code{gprof} tool.
20590 The following sections detail the different steps, and indicate how
20591 to interpret the results.
20594 * Compilation for profiling::
20595 * Program execution::
20597 * Interpretation of profiling results::
20601 @node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
20602 @anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{198}@anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{199}
20603 @subsubsection Compilation for profiling
20607 @geindex for profiling
20609 @geindex -pg (gnatlink)
20610 @geindex for profiling
20612 In order to profile a program the first step is to tell the compiler
20613 to generate the necessary profiling information. The compiler switch to be used
20614 is @code{-pg}, which must be added to other compilation switches. This
20615 switch needs to be specified both during compilation and link stages, and can
20616 be specified once when using gnatmake:
20621 $ gnatmake -f -pg -P my_project
20625 Note that only the objects that were compiled with the @code{-pg} switch will
20626 be profiled; if you need to profile your whole project, use the @code{-f}
20627 gnatmake switch to force full recompilation.
20629 @node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
20630 @anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{19a}@anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{19b}
20631 @subsubsection Program execution
20634 Once the program has been compiled for profiling, you can run it as usual.
20636 The only constraint imposed by profiling is that the program must terminate
20637 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20640 Once the program completes execution, a data file called @code{gmon.out} is
20641 generated in the directory where the program was launched from. If this file
20642 already exists, it will be overwritten.
20644 @node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
20645 @anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{19c}@anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{19d}
20646 @subsubsection Running gprof
20649 The @code{gprof} tool is called as follow:
20654 $ gprof my_prog gmon.out
20667 The complete form of the gprof command line is the following:
20672 $ gprof [switches] [executable [data-file]]
20676 @code{gprof} supports numerous switches. The order of these
20677 switch does not matter. The full list of options can be found in
20678 the GNU Profiler User's Guide documentation that comes with this documentation.
20680 The following is the subset of those switches that is most relevant:
20682 @geindex --demangle (gprof)
20687 @item @code{--demangle[=@emph{style}]}, @code{--no-demangle}
20689 These options control whether symbol names should be demangled when
20690 printing output. The default is to demangle C++ symbols. The
20691 @code{--no-demangle} option may be used to turn off demangling. Different
20692 compilers have different mangling styles. The optional demangling style
20693 argument can be used to choose an appropriate demangling style for your
20694 compiler, in particular Ada symbols generated by GNAT can be demangled using
20695 @code{--demangle=gnat}.
20698 @geindex -e (gprof)
20703 @item @code{-e @emph{function_name}}
20705 The @code{-e @emph{function}} option tells @code{gprof} not to print
20706 information about the function @code{function_name} (and its
20707 children...) in the call graph. The function will still be listed
20708 as a child of any functions that call it, but its index number will be
20709 shown as @code{[not printed]}. More than one @code{-e} option may be
20710 given; only one @code{function_name} may be indicated with each @code{-e}
20714 @geindex -E (gprof)
20719 @item @code{-E @emph{function_name}}
20721 The @code{-E @emph{function}} option works like the @code{-e} option, but
20722 execution time spent in the function (and children who were not called from
20723 anywhere else), will not be used to compute the percentages-of-time for
20724 the call graph. More than one @code{-E} option may be given; only one
20725 @code{function_name} may be indicated with each @code{-E`} option.
20728 @geindex -f (gprof)
20733 @item @code{-f @emph{function_name}}
20735 The @code{-f @emph{function}} option causes @code{gprof} to limit the
20736 call graph to the function @code{function_name} and its children (and
20737 their children...). More than one @code{-f} option may be given;
20738 only one @code{function_name} may be indicated with each @code{-f}
20742 @geindex -F (gprof)
20747 @item @code{-F @emph{function_name}}
20749 The @code{-F @emph{function}} option works like the @code{-f} option, but
20750 only time spent in the function and its children (and their
20751 children...) will be used to determine total-time and
20752 percentages-of-time for the call graph. More than one @code{-F} option
20753 may be given; only one @code{function_name} may be indicated with each
20754 @code{-F} option. The @code{-F} option overrides the @code{-E} option.
20757 @node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
20758 @anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{19e}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{19f}
20759 @subsubsection Interpretation of profiling results
20762 The results of the profiling analysis are represented by two arrays: the
20763 'flat profile' and the 'call graph'. Full documentation of those outputs
20764 can be found in the GNU Profiler User's Guide.
20766 The flat profile shows the time spent in each function of the program, and how
20767 many time it has been called. This allows you to locate easily the most
20768 time-consuming functions.
20770 The call graph shows, for each subprogram, the subprograms that call it,
20771 and the subprograms that it calls. It also provides an estimate of the time
20772 spent in each of those callers/called subprograms.
20774 @node Improving Performance,Overflow Check Handling in GNAT,Code Coverage and Profiling,GNAT and Program Execution
20775 @anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{169}@anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{26}
20776 @section Improving Performance
20779 @geindex Improving performance
20781 This section presents several topics related to program performance.
20782 It first describes some of the tradeoffs that need to be considered
20783 and some of the techniques for making your program run faster.
20786 It then documents the unused subprogram/data elimination feature,
20787 which can reduce the size of program executables.
20790 * Performance Considerations::
20791 * Text_IO Suggestions::
20792 * Reducing Size of Executables with Unused Subprogram/Data Elimination::
20796 @node Performance Considerations,Text_IO Suggestions,,Improving Performance
20797 @anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{1a0}@anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{1a1}
20798 @subsection Performance Considerations
20801 The GNAT system provides a number of options that allow a trade-off
20808 performance of the generated code
20811 speed of compilation
20814 minimization of dependences and recompilation
20817 the degree of run-time checking.
20820 The defaults (if no options are selected) aim at improving the speed
20821 of compilation and minimizing dependences, at the expense of performance
20822 of the generated code:
20831 no inlining of subprogram calls
20834 all run-time checks enabled except overflow and elaboration checks
20837 These options are suitable for most program development purposes. This
20838 section describes how you can modify these choices, and also provides
20839 some guidelines on debugging optimized code.
20842 * Controlling Run-Time Checks::
20843 * Use of Restrictions::
20844 * Optimization Levels::
20845 * Debugging Optimized Code::
20846 * Inlining of Subprograms::
20847 * Floating_Point_Operations::
20848 * Vectorization of loops::
20849 * Other Optimization Switches::
20850 * Optimization and Strict Aliasing::
20851 * Aliased Variables and Optimization::
20852 * Atomic Variables and Optimization::
20853 * Passive Task Optimization::
20857 @node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
20858 @anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{1a2}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{1a3}
20859 @subsubsection Controlling Run-Time Checks
20862 By default, GNAT generates all run-time checks, except stack overflow
20863 checks, and checks for access before elaboration on subprogram
20864 calls. The latter are not required in default mode, because all
20865 necessary checking is done at compile time.
20867 @geindex -gnatp (gcc)
20869 @geindex -gnato (gcc)
20871 The gnat switch, @code{-gnatp} allows this default to be modified. See
20872 @ref{f9,,Run-Time Checks}.
20874 Our experience is that the default is suitable for most development
20877 Elaboration checks are off by default, and also not needed by default, since
20878 GNAT uses a static elaboration analysis approach that avoids the need for
20879 run-time checking. This manual contains a full chapter discussing the issue
20880 of elaboration checks, and if the default is not satisfactory for your use,
20881 you should read this chapter.
20883 For validity checks, the minimal checks required by the Ada Reference
20884 Manual (for case statements and assignments to array elements) are on
20885 by default. These can be suppressed by use of the @code{-gnatVn} switch.
20886 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
20887 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
20888 it may be reasonable to routinely use @code{-gnatVn}. Validity checks
20889 are also suppressed entirely if @code{-gnatp} is used.
20891 @geindex Overflow checks
20898 @geindex Unsuppress
20900 @geindex pragma Suppress
20902 @geindex pragma Unsuppress
20904 Note that the setting of the switches controls the default setting of
20905 the checks. They may be modified using either @code{pragma Suppress} (to
20906 remove checks) or @code{pragma Unsuppress} (to add back suppressed
20907 checks) in the program source.
20909 @node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
20910 @anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{1a4}@anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{1a5}
20911 @subsubsection Use of Restrictions
20914 The use of pragma Restrictions allows you to control which features are
20915 permitted in your program. Apart from the obvious point that if you avoid
20916 relatively expensive features like finalization (enforceable by the use
20917 of pragma Restrictions (No_Finalization), the use of this pragma does not
20918 affect the generated code in most cases.
20920 One notable exception to this rule is that the possibility of task abort
20921 results in some distributed overhead, particularly if finalization or
20922 exception handlers are used. The reason is that certain sections of code
20923 have to be marked as non-abortable.
20925 If you use neither the @code{abort} statement, nor asynchronous transfer
20926 of control (@code{select ... then abort}), then this distributed overhead
20927 is removed, which may have a general positive effect in improving
20928 overall performance. Especially code involving frequent use of tasking
20929 constructs and controlled types will show much improved performance.
20930 The relevant restrictions pragmas are
20935 pragma Restrictions (No_Abort_Statements);
20936 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
20940 It is recommended that these restriction pragmas be used if possible. Note
20941 that this also means that you can write code without worrying about the
20942 possibility of an immediate abort at any point.
20944 @node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
20945 @anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{1a6}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{fc}
20946 @subsubsection Optimization Levels
20951 Without any optimization option,
20952 the compiler's goal is to reduce the cost of
20953 compilation and to make debugging produce the expected results.
20954 Statements are independent: if you stop the program with a breakpoint between
20955 statements, you can then assign a new value to any variable or change
20956 the program counter to any other statement in the subprogram and get exactly
20957 the results you would expect from the source code.
20959 Turning on optimization makes the compiler attempt to improve the
20960 performance and/or code size at the expense of compilation time and
20961 possibly the ability to debug the program.
20963 If you use multiple
20964 -O options, with or without level numbers,
20965 the last such option is the one that is effective.
20967 The default is optimization off. This results in the fastest compile
20968 times, but GNAT makes absolutely no attempt to optimize, and the
20969 generated programs are considerably larger and slower than when
20970 optimization is enabled. You can use the
20971 @code{-O} switch (the permitted forms are @code{-O0}, @code{-O1}
20972 @code{-O2}, @code{-O3}, and @code{-Os})
20973 to @code{gcc} to control the optimization level:
20984 No optimization (the default);
20985 generates unoptimized code but has
20986 the fastest compilation time.
20988 Note that many other compilers do substantial optimization even
20989 if 'no optimization' is specified. With gcc, it is very unusual
20990 to use @code{-O0} for production if execution time is of any concern,
20991 since @code{-O0} means (almost) no optimization. This difference
20992 between gcc and other compilers should be kept in mind when
20993 doing performance comparisons.
21002 Moderate optimization;
21003 optimizes reasonably well but does not
21004 degrade compilation time significantly.
21014 generates highly optimized code and has
21015 the slowest compilation time.
21024 Full optimization as in @code{-O2};
21025 also uses more aggressive automatic inlining of subprograms within a unit
21026 (@ref{10f,,Inlining of Subprograms}) and attempts to vectorize loops.
21035 Optimize space usage (code and data) of resulting program.
21039 Higher optimization levels perform more global transformations on the
21040 program and apply more expensive analysis algorithms in order to generate
21041 faster and more compact code. The price in compilation time, and the
21042 resulting improvement in execution time,
21043 both depend on the particular application and the hardware environment.
21044 You should experiment to find the best level for your application.
21046 Since the precise set of optimizations done at each level will vary from
21047 release to release (and sometime from target to target), it is best to think
21048 of the optimization settings in general terms.
21049 See the @emph{Options That Control Optimization} section in
21050 @cite{Using the GNU Compiler Collection (GCC)}
21052 the @code{-O} settings and a number of @code{-f} options that
21053 individually enable or disable specific optimizations.
21055 Unlike some other compilation systems, @code{gcc} has
21056 been tested extensively at all optimization levels. There are some bugs
21057 which appear only with optimization turned on, but there have also been
21058 bugs which show up only in @emph{unoptimized} code. Selecting a lower
21059 level of optimization does not improve the reliability of the code
21060 generator, which in practice is highly reliable at all optimization
21063 Note regarding the use of @code{-O3}: The use of this optimization level
21064 ought not to be automatically preferred over that of level @code{-O2},
21065 since it often results in larger executables which may run more slowly.
21066 See further discussion of this point in @ref{10f,,Inlining of Subprograms}.
21068 @node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
21069 @anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{1a7}@anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{1a8}
21070 @subsubsection Debugging Optimized Code
21073 @geindex Debugging optimized code
21075 @geindex Optimization and debugging
21077 Although it is possible to do a reasonable amount of debugging at
21078 nonzero optimization levels,
21079 the higher the level the more likely that
21080 source-level constructs will have been eliminated by optimization.
21081 For example, if a loop is strength-reduced, the loop
21082 control variable may be completely eliminated and thus cannot be
21083 displayed in the debugger.
21084 This can only happen at @code{-O2} or @code{-O3}.
21085 Explicit temporary variables that you code might be eliminated at
21086 level @code{-O1} or higher.
21090 The use of the @code{-g} switch,
21091 which is needed for source-level debugging,
21092 affects the size of the program executable on disk,
21093 and indeed the debugging information can be quite large.
21094 However, it has no effect on the generated code (and thus does not
21095 degrade performance)
21097 Since the compiler generates debugging tables for a compilation unit before
21098 it performs optimizations, the optimizing transformations may invalidate some
21099 of the debugging data. You therefore need to anticipate certain
21100 anomalous situations that may arise while debugging optimized code.
21101 These are the most common cases:
21107 @emph{The 'hopping Program Counter':} Repeated @code{step} or @code{next}
21109 the PC bouncing back and forth in the code. This may result from any of
21110 the following optimizations:
21116 @emph{Common subexpression elimination:} using a single instance of code for a
21117 quantity that the source computes several times. As a result you
21118 may not be able to stop on what looks like a statement.
21121 @emph{Invariant code motion:} moving an expression that does not change within a
21122 loop, to the beginning of the loop.
21125 @emph{Instruction scheduling:} moving instructions so as to
21126 overlap loads and stores (typically) with other code, or in
21127 general to move computations of values closer to their uses. Often
21128 this causes you to pass an assignment statement without the assignment
21129 happening and then later bounce back to the statement when the
21130 value is actually needed. Placing a breakpoint on a line of code
21131 and then stepping over it may, therefore, not always cause all the
21132 expected side-effects.
21136 @emph{The 'big leap':} More commonly known as @emph{cross-jumping}, in which
21137 two identical pieces of code are merged and the program counter suddenly
21138 jumps to a statement that is not supposed to be executed, simply because
21139 it (and the code following) translates to the same thing as the code
21140 that @emph{was} supposed to be executed. This effect is typically seen in
21141 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
21142 a @code{break} in a C @code{switch} statement.
21145 @emph{The 'roving variable':} The symptom is an unexpected value in a variable.
21146 There are various reasons for this effect:
21152 In a subprogram prologue, a parameter may not yet have been moved to its
21156 A variable may be dead, and its register re-used. This is
21157 probably the most common cause.
21160 As mentioned above, the assignment of a value to a variable may
21164 A variable may be eliminated entirely by value propagation or
21165 other means. In this case, GCC may incorrectly generate debugging
21166 information for the variable
21169 In general, when an unexpected value appears for a local variable or parameter
21170 you should first ascertain if that value was actually computed by
21171 your program, as opposed to being incorrectly reported by the debugger.
21173 array elements in an object designated by an access value
21174 are generally less of a problem, once you have ascertained that the access
21176 Typically, this means checking variables in the preceding code and in the
21177 calling subprogram to verify that the value observed is explainable from other
21178 values (one must apply the procedure recursively to those
21179 other values); or re-running the code and stopping a little earlier
21180 (perhaps before the call) and stepping to better see how the variable obtained
21181 the value in question; or continuing to step @emph{from} the point of the
21182 strange value to see if code motion had simply moved the variable's
21186 In light of such anomalies, a recommended technique is to use @code{-O0}
21187 early in the software development cycle, when extensive debugging capabilities
21188 are most needed, and then move to @code{-O1} and later @code{-O2} as
21189 the debugger becomes less critical.
21190 Whether to use the @code{-g} switch in the release version is
21191 a release management issue.
21192 Note that if you use @code{-g} you can then use the @code{strip} program
21193 on the resulting executable,
21194 which removes both debugging information and global symbols.
21196 @node Inlining of Subprograms,Floating_Point_Operations,Debugging Optimized Code,Performance Considerations
21197 @anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{1a9}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{10f}
21198 @subsubsection Inlining of Subprograms
21201 A call to a subprogram in the current unit is inlined if all the
21202 following conditions are met:
21208 The optimization level is at least @code{-O1}.
21211 The called subprogram is suitable for inlining: It must be small enough
21212 and not contain something that @code{gcc} cannot support in inlined
21215 @geindex pragma Inline
21220 Any one of the following applies: @code{pragma Inline} is applied to the
21221 subprogram; the subprogram is local to the unit and called once from
21222 within it; the subprogram is small and optimization level @code{-O2} is
21223 specified; optimization level @code{-O3} is specified.
21226 Calls to subprograms in @emph{with}ed units are normally not inlined.
21227 To achieve actual inlining (that is, replacement of the call by the code
21228 in the body of the subprogram), the following conditions must all be true:
21234 The optimization level is at least @code{-O1}.
21237 The called subprogram is suitable for inlining: It must be small enough
21238 and not contain something that @code{gcc} cannot support in inlined
21242 There is a @code{pragma Inline} for the subprogram.
21245 The @code{-gnatn} switch is used on the command line.
21248 Even if all these conditions are met, it may not be possible for
21249 the compiler to inline the call, due to the length of the body,
21250 or features in the body that make it impossible for the compiler
21251 to do the inlining.
21253 Note that specifying the @code{-gnatn} switch causes additional
21254 compilation dependencies. Consider the following:
21276 With the default behavior (no @code{-gnatn} switch specified), the
21277 compilation of the @code{Main} procedure depends only on its own source,
21278 @code{main.adb}, and the spec of the package in file @code{r.ads}. This
21279 means that editing the body of @code{R} does not require recompiling
21282 On the other hand, the call @code{R.Q} is not inlined under these
21283 circumstances. If the @code{-gnatn} switch is present when @code{Main}
21284 is compiled, the call will be inlined if the body of @code{Q} is small
21285 enough, but now @code{Main} depends on the body of @code{R} in
21286 @code{r.adb} as well as on the spec. This means that if this body is edited,
21287 the main program must be recompiled. Note that this extra dependency
21288 occurs whether or not the call is in fact inlined by @code{gcc}.
21290 The use of front end inlining with @code{-gnatN} generates similar
21291 additional dependencies.
21293 @geindex -fno-inline (gcc)
21295 Note: The @code{-fno-inline} switch overrides all other conditions and ensures that
21296 no inlining occurs, unless requested with pragma Inline_Always for @code{gcc}
21297 back-ends. The extra dependences resulting from @code{-gnatn} will still be active,
21298 even if this switch is used to suppress the resulting inlining actions.
21300 @geindex -fno-inline-functions (gcc)
21302 Note: The @code{-fno-inline-functions} switch can be used to prevent
21303 automatic inlining of subprograms if @code{-O3} is used.
21305 @geindex -fno-inline-small-functions (gcc)
21307 Note: The @code{-fno-inline-small-functions} switch can be used to prevent
21308 automatic inlining of small subprograms if @code{-O2} is used.
21310 @geindex -fno-inline-functions-called-once (gcc)
21312 Note: The @code{-fno-inline-functions-called-once} switch
21313 can be used to prevent inlining of subprograms local to the unit
21314 and called once from within it if @code{-O1} is used.
21316 Note regarding the use of @code{-O3}: @code{-gnatn} is made up of two
21317 sub-switches @code{-gnatn1} and @code{-gnatn2} that can be directly
21318 specified in lieu of it, @code{-gnatn} being translated into one of them
21319 based on the optimization level. With @code{-O2} or below, @code{-gnatn}
21320 is equivalent to @code{-gnatn1} which activates pragma @code{Inline} with
21321 moderate inlining across modules. With @code{-O3}, @code{-gnatn} is
21322 equivalent to @code{-gnatn2} which activates pragma @code{Inline} with
21323 full inlining across modules. If you have used pragma @code{Inline} in
21324 appropriate cases, then it is usually much better to use @code{-O2}
21325 and @code{-gnatn} and avoid the use of @code{-O3} which has the additional
21326 effect of inlining subprograms you did not think should be inlined. We have
21327 found that the use of @code{-O3} may slow down the compilation and increase
21328 the code size by performing excessive inlining, leading to increased
21329 instruction cache pressure from the increased code size and thus minor
21330 performance improvements. So the bottom line here is that you should not
21331 automatically assume that @code{-O3} is better than @code{-O2}, and
21332 indeed you should use @code{-O3} only if tests show that it actually
21333 improves performance for your program.
21335 @node Floating_Point_Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
21336 @anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{1aa}@anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{1ab}
21337 @subsubsection Floating_Point_Operations
21340 @geindex Floating-Point Operations
21342 On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
21343 64-bit standard IEEE floating-point representations, and operations will
21344 use standard IEEE arithmetic as provided by the processor. On most, but
21345 not all, architectures, the attribute Machine_Overflows is False for these
21346 types, meaning that the semantics of overflow is implementation-defined.
21347 In the case of GNAT, these semantics correspond to the normal IEEE
21348 treatment of infinities and NaN (not a number) values. For example,
21349 1.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
21350 avoiding explicit overflow checks, the performance is greatly improved
21351 on many targets. However, if required, floating-point overflow can be
21352 enabled by the use of the pragma Check_Float_Overflow.
21354 Another consideration that applies specifically to x86 32-bit
21355 architectures is which form of floating-point arithmetic is used.
21356 By default the operations use the old style x86 floating-point,
21357 which implements an 80-bit extended precision form (on these
21358 architectures the type Long_Long_Float corresponds to that form).
21359 In addition, generation of efficient code in this mode means that
21360 the extended precision form will be used for intermediate results.
21361 This may be helpful in improving the final precision of a complex
21362 expression. However it means that the results obtained on the x86
21363 will be different from those on other architectures, and for some
21364 algorithms, the extra intermediate precision can be detrimental.
21366 In addition to this old-style floating-point, all modern x86 chips
21367 implement an alternative floating-point operation model referred
21368 to as SSE2. In this model there is no extended form, and furthermore
21369 execution performance is significantly enhanced. To force GNAT to use
21370 this more modern form, use both of the switches:
21374 -msse2 -mfpmath=sse
21377 A unit compiled with these switches will automatically use the more
21378 efficient SSE2 instruction set for Float and Long_Float operations.
21379 Note that the ABI has the same form for both floating-point models,
21380 so it is permissible to mix units compiled with and without these
21383 @node Vectorization of loops,Other Optimization Switches,Floating_Point_Operations,Performance Considerations
21384 @anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{1ac}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{1ad}
21385 @subsubsection Vectorization of loops
21388 @geindex Optimization Switches
21390 You can take advantage of the auto-vectorizer present in the @code{gcc}
21391 back end to vectorize loops with GNAT. The corresponding command line switch
21392 is @code{-ftree-vectorize} but, as it is enabled by default at @code{-O3}
21393 and other aggressive optimizations helpful for vectorization also are enabled
21394 by default at this level, using @code{-O3} directly is recommended.
21396 You also need to make sure that the target architecture features a supported
21397 SIMD instruction set. For example, for the x86 architecture, you should at
21398 least specify @code{-msse2} to get significant vectorization (but you don't
21399 need to specify it for x86-64 as it is part of the base 64-bit architecture).
21400 Similarly, for the PowerPC architecture, you should specify @code{-maltivec}.
21402 The preferred loop form for vectorization is the @code{for} iteration scheme.
21403 Loops with a @code{while} iteration scheme can also be vectorized if they are
21404 very simple, but the vectorizer will quickly give up otherwise. With either
21405 iteration scheme, the flow of control must be straight, in particular no
21406 @code{exit} statement may appear in the loop body. The loop may however
21407 contain a single nested loop, if it can be vectorized when considered alone:
21412 A : array (1..4, 1..4) of Long_Float;
21413 S : array (1..4) of Long_Float;
21417 for I in A'Range(1) loop
21418 for J in A'Range(2) loop
21419 S (I) := S (I) + A (I, J);
21426 The vectorizable operations depend on the targeted SIMD instruction set, but
21427 the adding and some of the multiplying operators are generally supported, as
21428 well as the logical operators for modular types. Note that compiling
21429 with @code{-gnatp} might well reveal cases where some checks do thwart
21432 Type conversions may also prevent vectorization if they involve semantics that
21433 are not directly supported by the code generator or the SIMD instruction set.
21434 A typical example is direct conversion from floating-point to integer types.
21435 The solution in this case is to use the following idiom:
21440 Integer (S'Truncation (F))
21444 if @code{S} is the subtype of floating-point object @code{F}.
21446 In most cases, the vectorizable loops are loops that iterate over arrays.
21447 All kinds of array types are supported, i.e. constrained array types with
21453 type Array_Type is array (1 .. 4) of Long_Float;
21457 constrained array types with dynamic bounds:
21462 type Array_Type is array (1 .. Q.N) of Long_Float;
21464 type Array_Type is array (Q.K .. 4) of Long_Float;
21466 type Array_Type is array (Q.K .. Q.N) of Long_Float;
21470 or unconstrained array types:
21475 type Array_Type is array (Positive range <>) of Long_Float;
21479 The quality of the generated code decreases when the dynamic aspect of the
21480 array type increases, the worst code being generated for unconstrained array
21481 types. This is so because, the less information the compiler has about the
21482 bounds of the array, the more fallback code it needs to generate in order to
21483 fix things up at run time.
21485 It is possible to specify that a given loop should be subject to vectorization
21486 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
21491 pragma Loop_Optimize (Vector);
21495 placed immediately within the loop will convey the appropriate hint to the
21496 compiler for this loop.
21498 It is also possible to help the compiler generate better vectorized code
21499 for a given loop by asserting that there are no loop-carried dependencies
21500 in the loop. Consider for example the procedure:
21505 type Arr is array (1 .. 4) of Long_Float;
21507 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
21509 for I in Arr'Range loop
21510 R(I) := X(I) + Y(I);
21516 By default, the compiler cannot unconditionally vectorize the loop because
21517 assigning to a component of the array designated by R in one iteration could
21518 change the value read from the components of the array designated by X or Y
21519 in a later iteration. As a result, the compiler will generate two versions
21520 of the loop in the object code, one vectorized and the other not vectorized,
21521 as well as a test to select the appropriate version at run time. This can
21522 be overcome by another hint:
21527 pragma Loop_Optimize (Ivdep);
21531 placed immediately within the loop will tell the compiler that it can safely
21532 omit the non-vectorized version of the loop as well as the run-time test.
21534 @node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
21535 @anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{1ae}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{1af}
21536 @subsubsection Other Optimization Switches
21539 @geindex Optimization Switches
21541 Since GNAT uses the @code{gcc} back end, all the specialized
21542 @code{gcc} optimization switches are potentially usable. These switches
21543 have not been extensively tested with GNAT but can generally be expected
21544 to work. Examples of switches in this category are @code{-funroll-loops}
21545 and the various target-specific @code{-m} options (in particular, it has
21546 been observed that @code{-march=xxx} can significantly improve performance
21547 on appropriate machines). For full details of these switches, see
21548 the @emph{Submodel Options} section in the @emph{Hardware Models and Configurations}
21549 chapter of @cite{Using the GNU Compiler Collection (GCC)}.
21551 @node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
21552 @anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{f3}@anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{1b0}
21553 @subsubsection Optimization and Strict Aliasing
21558 @geindex Strict Aliasing
21560 @geindex No_Strict_Aliasing
21562 The strong typing capabilities of Ada allow an optimizer to generate
21563 efficient code in situations where other languages would be forced to
21564 make worst case assumptions preventing such optimizations. Consider
21565 the following example:
21571 type Int1 is new Integer;
21572 type Int2 is new Integer;
21573 type Int1A is access Int1;
21574 type Int2A is access Int2;
21581 for J in Data'Range loop
21582 if Data (J) = Int1V.all then
21583 Int2V.all := Int2V.all + 1;
21591 In this example, since the variable @code{Int1V} can only access objects
21592 of type @code{Int1}, and @code{Int2V} can only access objects of type
21593 @code{Int2}, there is no possibility that the assignment to
21594 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
21595 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
21596 for all iterations of the loop and avoid the extra memory reference
21597 required to dereference it each time through the loop.
21599 This kind of optimization, called strict aliasing analysis, is
21600 triggered by specifying an optimization level of @code{-O2} or
21601 higher or @code{-Os} and allows GNAT to generate more efficient code
21602 when access values are involved.
21604 However, although this optimization is always correct in terms of
21605 the formal semantics of the Ada Reference Manual, difficulties can
21606 arise if features like @code{Unchecked_Conversion} are used to break
21607 the typing system. Consider the following complete program example:
21613 type int1 is new integer;
21614 type int2 is new integer;
21615 type a1 is access int1;
21616 type a2 is access int2;
21621 function to_a2 (Input : a1) return a2;
21624 with Unchecked_Conversion;
21626 function to_a2 (Input : a1) return a2 is
21628 new Unchecked_Conversion (a1, a2);
21630 return to_a2u (Input);
21636 with Text_IO; use Text_IO;
21638 v1 : a1 := new int1;
21639 v2 : a2 := to_a2 (v1);
21643 put_line (int1'image (v1.all));
21648 This program prints out 0 in @code{-O0} or @code{-O1}
21649 mode, but it prints out 1 in @code{-O2} mode. That's
21650 because in strict aliasing mode, the compiler can and
21651 does assume that the assignment to @code{v2.all} could not
21652 affect the value of @code{v1.all}, since different types
21655 This behavior is not a case of non-conformance with the standard, since
21656 the Ada RM specifies that an unchecked conversion where the resulting
21657 bit pattern is not a correct value of the target type can result in an
21658 abnormal value and attempting to reference an abnormal value makes the
21659 execution of a program erroneous. That's the case here since the result
21660 does not point to an object of type @code{int2}. This means that the
21661 effect is entirely unpredictable.
21663 However, although that explanation may satisfy a language
21664 lawyer, in practice an applications programmer expects an
21665 unchecked conversion involving pointers to create true
21666 aliases and the behavior of printing 1 seems plain wrong.
21667 In this case, the strict aliasing optimization is unwelcome.
21669 Indeed the compiler recognizes this possibility, and the
21670 unchecked conversion generates a warning:
21675 p2.adb:5:07: warning: possible aliasing problem with type "a2"
21676 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
21677 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
21681 Unfortunately the problem is recognized when compiling the body of
21682 package @code{p2}, but the actual "bad" code is generated while
21683 compiling the body of @code{m} and this latter compilation does not see
21684 the suspicious @code{Unchecked_Conversion}.
21686 As implied by the warning message, there are approaches you can use to
21687 avoid the unwanted strict aliasing optimization in a case like this.
21689 One possibility is to simply avoid the use of @code{-O2}, but
21690 that is a bit drastic, since it throws away a number of useful
21691 optimizations that do not involve strict aliasing assumptions.
21693 A less drastic approach is to compile the program using the
21694 option @code{-fno-strict-aliasing}. Actually it is only the
21695 unit containing the dereferencing of the suspicious pointer
21696 that needs to be compiled. So in this case, if we compile
21697 unit @code{m} with this switch, then we get the expected
21698 value of zero printed. Analyzing which units might need
21699 the switch can be painful, so a more reasonable approach
21700 is to compile the entire program with options @code{-O2}
21701 and @code{-fno-strict-aliasing}. If the performance is
21702 satisfactory with this combination of options, then the
21703 advantage is that the entire issue of possible "wrong"
21704 optimization due to strict aliasing is avoided.
21706 To avoid the use of compiler switches, the configuration
21707 pragma @code{No_Strict_Aliasing} with no parameters may be
21708 used to specify that for all access types, the strict
21709 aliasing optimization should be suppressed.
21711 However, these approaches are still overkill, in that they causes
21712 all manipulations of all access values to be deoptimized. A more
21713 refined approach is to concentrate attention on the specific
21714 access type identified as problematic.
21716 First, if a careful analysis of uses of the pointer shows
21717 that there are no possible problematic references, then
21718 the warning can be suppressed by bracketing the
21719 instantiation of @code{Unchecked_Conversion} to turn
21725 pragma Warnings (Off);
21727 new Unchecked_Conversion (a1, a2);
21728 pragma Warnings (On);
21732 Of course that approach is not appropriate for this particular
21733 example, since indeed there is a problematic reference. In this
21734 case we can take one of two other approaches.
21736 The first possibility is to move the instantiation of unchecked
21737 conversion to the unit in which the type is declared. In
21738 this example, we would move the instantiation of
21739 @code{Unchecked_Conversion} from the body of package
21740 @code{p2} to the spec of package @code{p1}. Now the
21741 warning disappears. That's because any use of the
21742 access type knows there is a suspicious unchecked
21743 conversion, and the strict aliasing optimization
21744 is automatically suppressed for the type.
21746 If it is not practical to move the unchecked conversion to the same unit
21747 in which the destination access type is declared (perhaps because the
21748 source type is not visible in that unit), you may use pragma
21749 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
21750 same declarative sequence as the declaration of the access type:
21755 type a2 is access int2;
21756 pragma No_Strict_Aliasing (a2);
21760 Here again, the compiler now knows that the strict aliasing optimization
21761 should be suppressed for any reference to type @code{a2} and the
21762 expected behavior is obtained.
21764 Finally, note that although the compiler can generate warnings for
21765 simple cases of unchecked conversions, there are tricker and more
21766 indirect ways of creating type incorrect aliases which the compiler
21767 cannot detect. Examples are the use of address overlays and unchecked
21768 conversions involving composite types containing access types as
21769 components. In such cases, no warnings are generated, but there can
21770 still be aliasing problems. One safe coding practice is to forbid the
21771 use of address clauses for type overlaying, and to allow unchecked
21772 conversion only for primitive types. This is not really a significant
21773 restriction since any possible desired effect can be achieved by
21774 unchecked conversion of access values.
21776 The aliasing analysis done in strict aliasing mode can certainly
21777 have significant benefits. We have seen cases of large scale
21778 application code where the time is increased by up to 5% by turning
21779 this optimization off. If you have code that includes significant
21780 usage of unchecked conversion, you might want to just stick with
21781 @code{-O1} and avoid the entire issue. If you get adequate
21782 performance at this level of optimization level, that's probably
21783 the safest approach. If tests show that you really need higher
21784 levels of optimization, then you can experiment with @code{-O2}
21785 and @code{-O2 -fno-strict-aliasing} to see how much effect this
21786 has on size and speed of the code. If you really need to use
21787 @code{-O2} with strict aliasing in effect, then you should
21788 review any uses of unchecked conversion of access types,
21789 particularly if you are getting the warnings described above.
21791 @node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
21792 @anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{1b1}@anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{1b2}
21793 @subsubsection Aliased Variables and Optimization
21798 There are scenarios in which programs may
21799 use low level techniques to modify variables
21800 that otherwise might be considered to be unassigned. For example,
21801 a variable can be passed to a procedure by reference, which takes
21802 the address of the parameter and uses the address to modify the
21803 variable's value, even though it is passed as an IN parameter.
21804 Consider the following example:
21810 Max_Length : constant Natural := 16;
21811 type Char_Ptr is access all Character;
21813 procedure Get_String(Buffer: Char_Ptr; Size : Integer);
21814 pragma Import (C, Get_String, "get_string");
21816 Name : aliased String (1 .. Max_Length) := (others => ' ');
21819 function Addr (S : String) return Char_Ptr is
21820 function To_Char_Ptr is
21821 new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
21823 return To_Char_Ptr (S (S'First)'Address);
21827 Temp := Addr (Name);
21828 Get_String (Temp, Max_Length);
21833 where Get_String is a C function that uses the address in Temp to
21834 modify the variable @code{Name}. This code is dubious, and arguably
21835 erroneous, and the compiler would be entitled to assume that
21836 @code{Name} is never modified, and generate code accordingly.
21838 However, in practice, this would cause some existing code that
21839 seems to work with no optimization to start failing at high
21840 levels of optimzization.
21842 What the compiler does for such cases is to assume that marking
21843 a variable as aliased indicates that some "funny business" may
21844 be going on. The optimizer recognizes the aliased keyword and
21845 inhibits optimizations that assume the value cannot be assigned.
21846 This means that the above example will in fact "work" reliably,
21847 that is, it will produce the expected results.
21849 @node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
21850 @anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{1b3}@anchor{gnat_ugn/gnat_and_program_execution id41}@anchor{1b4}
21851 @subsubsection Atomic Variables and Optimization
21856 There are two considerations with regard to performance when
21857 atomic variables are used.
21859 First, the RM only guarantees that access to atomic variables
21860 be atomic, it has nothing to say about how this is achieved,
21861 though there is a strong implication that this should not be
21862 achieved by explicit locking code. Indeed GNAT will never
21863 generate any locking code for atomic variable access (it will
21864 simply reject any attempt to make a variable or type atomic
21865 if the atomic access cannot be achieved without such locking code).
21867 That being said, it is important to understand that you cannot
21868 assume that the entire variable will always be accessed. Consider
21875 A,B,C,D : Character;
21878 for R'Alignment use 4;
21881 pragma Atomic (RV);
21888 You cannot assume that the reference to @code{RV.B}
21889 will read the entire 32-bit
21890 variable with a single load instruction. It is perfectly legitimate if
21891 the hardware allows it to do a byte read of just the B field. This read
21892 is still atomic, which is all the RM requires. GNAT can and does take
21893 advantage of this, depending on the architecture and optimization level.
21894 Any assumption to the contrary is non-portable and risky. Even if you
21895 examine the assembly language and see a full 32-bit load, this might
21896 change in a future version of the compiler.
21898 If your application requires that all accesses to @code{RV} in this
21899 example be full 32-bit loads, you need to make a copy for the access
21906 RV_Copy : constant R := RV;
21913 Now the reference to RV must read the whole variable.
21914 Actually one can imagine some compiler which figures
21915 out that the whole copy is not required (because only
21916 the B field is actually accessed), but GNAT
21917 certainly won't do that, and we don't know of any
21918 compiler that would not handle this right, and the
21919 above code will in practice work portably across
21920 all architectures (that permit the Atomic declaration).
21922 The second issue with atomic variables has to do with
21923 the possible requirement of generating synchronization
21924 code. For more details on this, consult the sections on
21925 the pragmas Enable/Disable_Atomic_Synchronization in the
21926 GNAT Reference Manual. If performance is critical, and
21927 such synchronization code is not required, it may be
21928 useful to disable it.
21930 @node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
21931 @anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{1b5}@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{1b6}
21932 @subsubsection Passive Task Optimization
21935 @geindex Passive Task
21937 A passive task is one which is sufficiently simple that
21938 in theory a compiler could recognize it an implement it
21939 efficiently without creating a new thread. The original design
21940 of Ada 83 had in mind this kind of passive task optimization, but
21941 only a few Ada 83 compilers attempted it. The problem was that
21942 it was difficult to determine the exact conditions under which
21943 the optimization was possible. The result is a very fragile
21944 optimization where a very minor change in the program can
21945 suddenly silently make a task non-optimizable.
21947 With the revisiting of this issue in Ada 95, there was general
21948 agreement that this approach was fundamentally flawed, and the
21949 notion of protected types was introduced. When using protected
21950 types, the restrictions are well defined, and you KNOW that the
21951 operations will be optimized, and furthermore this optimized
21952 performance is fully portable.
21954 Although it would theoretically be possible for GNAT to attempt to
21955 do this optimization, but it really doesn't make sense in the
21956 context of Ada 95, and none of the Ada 95 compilers implement
21957 this optimization as far as we know. In particular GNAT never
21958 attempts to perform this optimization.
21960 In any new Ada 95 code that is written, you should always
21961 use protected types in place of tasks that might be able to
21962 be optimized in this manner.
21963 Of course this does not help if you have legacy Ada 83 code
21964 that depends on this optimization, but it is unusual to encounter
21965 a case where the performance gains from this optimization
21968 Your program should work correctly without this optimization. If
21969 you have performance problems, then the most practical
21970 approach is to figure out exactly where these performance problems
21971 arise, and update those particular tasks to be protected types. Note
21972 that typically clients of the tasks who call entries, will not have
21973 to be modified, only the task definition itself.
21975 @node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
21976 @anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{1b7}@anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{1b8}
21977 @subsection @code{Text_IO} Suggestions
21980 @geindex Text_IO and performance
21982 The @code{Ada.Text_IO} package has fairly high overheads due in part to
21983 the requirement of maintaining page and line counts. If performance
21984 is critical, a recommendation is to use @code{Stream_IO} instead of
21985 @code{Text_IO} for volume output, since this package has less overhead.
21987 If @code{Text_IO} must be used, note that by default output to the standard
21988 output and standard error files is unbuffered (this provides better
21989 behavior when output statements are used for debugging, or if the
21990 progress of a program is observed by tracking the output, e.g. by
21991 using the Unix @emph{tail -f} command to watch redirected output.
21993 If you are generating large volumes of output with @code{Text_IO} and
21994 performance is an important factor, use a designated file instead
21995 of the standard output file, or change the standard output file to
21996 be buffered using @code{Interfaces.C_Streams.setvbuf}.
21998 @node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
21999 @anchor{gnat_ugn/gnat_and_program_execution id44}@anchor{1b9}@anchor{gnat_ugn/gnat_and_program_execution reducing-size-of-executables-with-unused-subprogram-data-elimination}@anchor{1ba}
22000 @subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
22003 @geindex Uunused subprogram/data elimination
22005 This section describes how you can eliminate unused subprograms and data from
22006 your executable just by setting options at compilation time.
22009 * About unused subprogram/data elimination::
22010 * Compilation options::
22011 * Example of unused subprogram/data elimination::
22015 @node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
22016 @anchor{gnat_ugn/gnat_and_program_execution id45}@anchor{1bb}@anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{1bc}
22017 @subsubsection About unused subprogram/data elimination
22020 By default, an executable contains all code and data of its composing objects
22021 (directly linked or coming from statically linked libraries), even data or code
22022 never used by this executable.
22024 This feature will allow you to eliminate such unused code from your
22025 executable, making it smaller (in disk and in memory).
22027 This functionality is available on all Linux platforms except for the IA-64
22028 architecture and on all cross platforms using the ELF binary file format.
22029 In both cases GNU binutils version 2.16 or later are required to enable it.
22031 @node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
22032 @anchor{gnat_ugn/gnat_and_program_execution id46}@anchor{1bd}@anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{1be}
22033 @subsubsection Compilation options
22036 The operation of eliminating the unused code and data from the final executable
22037 is directly performed by the linker.
22039 @geindex -ffunction-sections (gcc)
22041 @geindex -fdata-sections (gcc)
22043 In order to do this, it has to work with objects compiled with the
22045 @code{-ffunction-sections} @code{-fdata-sections}.
22047 These options are usable with C and Ada files.
22048 They will place respectively each
22049 function or data in a separate section in the resulting object file.
22051 Once the objects and static libraries are created with these options, the
22052 linker can perform the dead code elimination. You can do this by setting
22053 the @code{-Wl,--gc-sections} option to gcc command or in the
22054 @code{-largs} section of @code{gnatmake}. This will perform a
22055 garbage collection of code and data never referenced.
22057 If the linker performs a partial link (@code{-r} linker option), then you
22058 will need to provide the entry point using the @code{-e} / @code{--entry}
22061 Note that objects compiled without the @code{-ffunction-sections} and
22062 @code{-fdata-sections} options can still be linked with the executable.
22063 However, no dead code elimination will be performed on those objects (they will
22066 The GNAT static library is now compiled with -ffunction-sections and
22067 -fdata-sections on some platforms. This allows you to eliminate the unused code
22068 and data of the GNAT library from your executable.
22070 @node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
22071 @anchor{gnat_ugn/gnat_and_program_execution id47}@anchor{1bf}@anchor{gnat_ugn/gnat_and_program_execution example-of-unused-subprogram-data-elimination}@anchor{1c0}
22072 @subsubsection Example of unused subprogram/data elimination
22075 Here is a simple example:
22088 Used_Data : Integer;
22089 Unused_Data : Integer;
22091 procedure Used (Data : Integer);
22092 procedure Unused (Data : Integer);
22095 package body Aux is
22096 procedure Used (Data : Integer) is
22101 procedure Unused (Data : Integer) is
22103 Unused_Data := Data;
22109 @code{Unused} and @code{Unused_Data} are never referenced in this code
22110 excerpt, and hence they may be safely removed from the final executable.
22117 $ nm test | grep used
22118 020015f0 T aux__unused
22119 02005d88 B aux__unused_data
22120 020015cc T aux__used
22121 02005d84 B aux__used_data
22123 $ gnatmake test -cargs -fdata-sections -ffunction-sections \\
22124 -largs -Wl,--gc-sections
22126 $ nm test | grep used
22127 02005350 T aux__used
22128 0201ffe0 B aux__used_data
22132 It can be observed that the procedure @code{Unused} and the object
22133 @code{Unused_Data} are removed by the linker when using the
22134 appropriate options.
22136 @geindex Overflow checks
22138 @geindex Checks (overflow)
22141 @node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
22142 @anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{16a}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{27}
22143 @section Overflow Check Handling in GNAT
22146 This section explains how to control the handling of overflow checks.
22150 * Management of Overflows in GNAT::
22151 * Specifying the Desired Mode::
22152 * Default Settings::
22153 * Implementation Notes::
22157 @node Background,Management of Overflows in GNAT,,Overflow Check Handling in GNAT
22158 @anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{1c1}@anchor{gnat_ugn/gnat_and_program_execution background}@anchor{1c2}
22159 @subsection Background
22162 Overflow checks are checks that the compiler may make to ensure
22163 that intermediate results are not out of range. For example:
22174 If @code{A} has the value @code{Integer'Last}, then the addition may cause
22175 overflow since the result is out of range of the type @code{Integer}.
22176 In this case @code{Constraint_Error} will be raised if checks are
22179 A trickier situation arises in examples like the following:
22190 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
22191 Now the final result of the expression on the right hand side is
22192 @code{Integer'Last} which is in range, but the question arises whether the
22193 intermediate addition of @code{(A + 1)} raises an overflow error.
22195 The (perhaps surprising) answer is that the Ada language
22196 definition does not answer this question. Instead it leaves
22197 it up to the implementation to do one of two things if overflow
22198 checks are enabled.
22204 raise an exception (@code{Constraint_Error}), or
22207 yield the correct mathematical result which is then used in
22208 subsequent operations.
22211 If the compiler chooses the first approach, then the assignment of this
22212 example will indeed raise @code{Constraint_Error} if overflow checking is
22213 enabled, or result in erroneous execution if overflow checks are suppressed.
22215 But if the compiler
22216 chooses the second approach, then it can perform both additions yielding
22217 the correct mathematical result, which is in range, so no exception
22218 will be raised, and the right result is obtained, regardless of whether
22219 overflow checks are suppressed.
22221 Note that in the first example an
22222 exception will be raised in either case, since if the compiler
22223 gives the correct mathematical result for the addition, it will
22224 be out of range of the target type of the assignment, and thus
22225 fails the range check.
22227 This lack of specified behavior in the handling of overflow for
22228 intermediate results is a source of non-portability, and can thus
22229 be problematic when programs are ported. Most typically this arises
22230 in a situation where the original compiler did not raise an exception,
22231 and then the application is moved to a compiler where the check is
22232 performed on the intermediate result and an unexpected exception is
22235 Furthermore, when using Ada 2012's preconditions and other
22236 assertion forms, another issue arises. Consider:
22241 procedure P (A, B : Integer) with
22242 Pre => A + B <= Integer'Last;
22246 One often wants to regard arithmetic in a context like this from
22247 a mathematical point of view. So for example, if the two actual parameters
22248 for a call to @code{P} are both @code{Integer'Last}, then
22249 the precondition should be regarded as False. If we are executing
22250 in a mode with run-time checks enabled for preconditions, then we would
22251 like this precondition to fail, rather than raising an exception
22252 because of the intermediate overflow.
22254 However, the language definition leaves the specification of
22255 whether the above condition fails (raising @code{Assert_Error}) or
22256 causes an intermediate overflow (raising @code{Constraint_Error})
22257 up to the implementation.
22259 The situation is worse in a case such as the following:
22264 procedure Q (A, B, C : Integer) with
22265 Pre => A + B + C <= Integer'Last;
22274 Q (A => Integer'Last, B => 1, C => -1);
22278 From a mathematical point of view the precondition
22279 is True, but at run time we may (but are not guaranteed to) get an
22280 exception raised because of the intermediate overflow (and we really
22281 would prefer this precondition to be considered True at run time).
22283 @node Management of Overflows in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
22284 @anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{1c3}@anchor{gnat_ugn/gnat_and_program_execution management-of-overflows-in-gnat}@anchor{1c4}
22285 @subsection Management of Overflows in GNAT
22288 To deal with the portability issue, and with the problem of
22289 mathematical versus run-time interpretation of the expressions in
22290 assertions, GNAT provides comprehensive control over the handling
22291 of intermediate overflow. GNAT can operate in three modes, and
22292 furthemore, permits separate selection of operating modes for
22293 the expressions within assertions (here the term 'assertions'
22294 is used in the technical sense, which includes preconditions and so forth)
22295 and for expressions appearing outside assertions.
22297 The three modes are:
22303 @emph{Use base type for intermediate operations} (@code{STRICT})
22305 In this mode, all intermediate results for predefined arithmetic
22306 operators are computed using the base type, and the result must
22307 be in range of the base type. If this is not the
22308 case then either an exception is raised (if overflow checks are
22309 enabled) or the execution is erroneous (if overflow checks are suppressed).
22310 This is the normal default mode.
22313 @emph{Most intermediate overflows avoided} (@code{MINIMIZED})
22315 In this mode, the compiler attempts to avoid intermediate overflows by
22316 using a larger integer type, typically @code{Long_Long_Integer},
22317 as the type in which arithmetic is
22318 performed for predefined arithmetic operators. This may be slightly more
22320 run time (compared to suppressing intermediate overflow checks), though
22321 the cost is negligible on modern 64-bit machines. For the examples given
22322 earlier, no intermediate overflows would have resulted in exceptions,
22323 since the intermediate results are all in the range of
22324 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
22325 of GNAT). In addition, if checks are enabled, this reduces the number of
22326 checks that must be made, so this choice may actually result in an
22327 improvement in space and time behavior.
22329 However, there are cases where @code{Long_Long_Integer} is not large
22330 enough, consider the following example:
22335 procedure R (A, B, C, D : Integer) with
22336 Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
22340 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
22341 Now the intermediate results are
22342 out of the range of @code{Long_Long_Integer} even though the final result
22343 is in range and the precondition is True (from a mathematical point
22344 of view). In such a case, operating in this mode, an overflow occurs
22345 for the intermediate computation (which is why this mode
22346 says @emph{most} intermediate overflows are avoided). In this case,
22347 an exception is raised if overflow checks are enabled, and the
22348 execution is erroneous if overflow checks are suppressed.
22351 @emph{All intermediate overflows avoided} (@code{ELIMINATED})
22353 In this mode, the compiler avoids all intermediate overflows
22354 by using arbitrary precision arithmetic as required. In this
22355 mode, the above example with @code{A**2 * B**2} would
22356 not cause intermediate overflow, because the intermediate result
22357 would be evaluated using sufficient precision, and the result
22358 of evaluating the precondition would be True.
22360 This mode has the advantage of avoiding any intermediate
22361 overflows, but at the expense of significant run-time overhead,
22362 including the use of a library (included automatically in this
22363 mode) for multiple-precision arithmetic.
22365 This mode provides cleaner semantics for assertions, since now
22366 the run-time behavior emulates true arithmetic behavior for the
22367 predefined arithmetic operators, meaning that there is never a
22368 conflict between the mathematical view of the assertion, and its
22371 Note that in this mode, the behavior is unaffected by whether or
22372 not overflow checks are suppressed, since overflow does not occur.
22373 It is possible for gigantic intermediate expressions to raise
22374 @code{Storage_Error} as a result of attempting to compute the
22375 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
22376 but overflow is impossible.
22379 Note that these modes apply only to the evaluation of predefined
22380 arithmetic, membership, and comparison operators for signed integer
22383 For fixed-point arithmetic, checks can be suppressed. But if checks
22385 then fixed-point values are always checked for overflow against the
22386 base type for intermediate expressions (that is such checks always
22387 operate in the equivalent of @code{STRICT} mode).
22389 For floating-point, on nearly all architectures, @code{Machine_Overflows}
22390 is False, and IEEE infinities are generated, so overflow exceptions
22391 are never raised. If you want to avoid infinities, and check that
22392 final results of expressions are in range, then you can declare a
22393 constrained floating-point type, and range checks will be carried
22394 out in the normal manner (with infinite values always failing all
22397 @node Specifying the Desired Mode,Default Settings,Management of Overflows in GNAT,Overflow Check Handling in GNAT
22398 @anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{f8}@anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{1c5}
22399 @subsection Specifying the Desired Mode
22402 @geindex pragma Overflow_Mode
22404 The desired mode of for handling intermediate overflow can be specified using
22405 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
22406 The pragma has the form
22411 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
22415 where @code{MODE} is one of
22421 @code{STRICT}: intermediate overflows checked (using base type)
22424 @code{MINIMIZED}: minimize intermediate overflows
22427 @code{ELIMINATED}: eliminate intermediate overflows
22430 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
22431 @code{minimized} all have the same effect.
22433 If only the @code{General} parameter is present, then the given @code{MODE} applies
22434 to expressions both within and outside assertions. If both arguments
22435 are present, then @code{General} applies to expressions outside assertions,
22436 and @code{Assertions} applies to expressions within assertions. For example:
22441 pragma Overflow_Mode
22442 (General => Minimized, Assertions => Eliminated);
22446 specifies that general expressions outside assertions be evaluated
22447 in 'minimize intermediate overflows' mode, and expressions within
22448 assertions be evaluated in 'eliminate intermediate overflows' mode.
22449 This is often a reasonable choice, avoiding excessive overhead
22450 outside assertions, but assuring a high degree of portability
22451 when importing code from another compiler, while incurring
22452 the extra overhead for assertion expressions to ensure that
22453 the behavior at run time matches the expected mathematical
22456 The @code{Overflow_Mode} pragma has the same scoping and placement
22457 rules as pragma @code{Suppress}, so it can occur either as a
22458 configuration pragma, specifying a default for the whole
22459 program, or in a declarative scope, where it applies to the
22460 remaining declarations and statements in that scope.
22462 Note that pragma @code{Overflow_Mode} does not affect whether
22463 overflow checks are enabled or suppressed. It only controls the
22464 method used to compute intermediate values. To control whether
22465 overflow checking is enabled or suppressed, use pragma @code{Suppress}
22466 or @code{Unsuppress} in the usual manner.
22468 @geindex -gnato? (gcc)
22470 @geindex -gnato?? (gcc)
22472 Additionally, a compiler switch @code{-gnato?} or @code{-gnato??}
22473 can be used to control the checking mode default (which can be subsequently
22474 overridden using pragmas).
22476 Here @code{?} is one of the digits @code{1} through @code{3}:
22481 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
22488 use base type for intermediate operations (@code{STRICT})
22496 minimize intermediate overflows (@code{MINIMIZED})
22504 eliminate intermediate overflows (@code{ELIMINATED})
22510 As with the pragma, if only one digit appears then it applies to all
22511 cases; if two digits are given, then the first applies outside
22512 assertions, and the second within assertions. Thus the equivalent
22513 of the example pragma above would be
22516 If no digits follow the @code{-gnato}, then it is equivalent to
22518 causing all intermediate operations to be computed using the base
22519 type (@code{STRICT} mode).
22521 @node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
22522 @anchor{gnat_ugn/gnat_and_program_execution id59}@anchor{1c6}@anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{1c7}
22523 @subsection Default Settings
22526 The default mode for overflow checks is
22535 which causes all computations both inside and outside assertions to use
22538 This retains compatibility with previous versions of
22539 GNAT which suppressed overflow checks by default and always
22540 used the base type for computation of intermediate results.
22542 @c Sphinx allows no emphasis within :index: role. As a workaround we
22543 @c point the index to "switch" and use emphasis for "-gnato".
22546 @geindex -gnato (gcc)
22547 switch @code{-gnato} (with no digits following)
22557 which causes overflow checking of all intermediate overflows
22558 both inside and outside assertions against the base type.
22560 The pragma @code{Suppress (Overflow_Check)} disables overflow
22561 checking, but it has no effect on the method used for computing
22562 intermediate results.
22564 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
22565 checking, but it has no effect on the method used for computing
22566 intermediate results.
22568 @node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
22569 @anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{1c8}@anchor{gnat_ugn/gnat_and_program_execution id60}@anchor{1c9}
22570 @subsection Implementation Notes
22573 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
22574 reasonably efficient, and can be generally used. It also helps
22575 to ensure compatibility with code imported from some other
22578 Setting all intermediate overflows checking (@code{CHECKED} mode)
22579 makes sense if you want to
22580 make sure that your code is compatible with any other possible
22581 Ada implementation. This may be useful in ensuring portability
22582 for code that is to be exported to some other compiler than GNAT.
22584 The Ada standard allows the reassociation of expressions at
22585 the same precedence level if no parentheses are present. For
22586 example, @code{A+B+C} parses as though it were @code{(A+B)+C}, but
22587 the compiler can reintepret this as @code{A+(B+C)}, possibly
22588 introducing or eliminating an overflow exception. The GNAT
22589 compiler never takes advantage of this freedom, and the
22590 expression @code{A+B+C} will be evaluated as @code{(A+B)+C}.
22591 If you need the other order, you can write the parentheses
22592 explicitly @code{A+(B+C)} and GNAT will respect this order.
22594 The use of @code{ELIMINATED} mode will cause the compiler to
22595 automatically include an appropriate arbitrary precision
22596 integer arithmetic package. The compiler will make calls
22597 to this package, though only in cases where it cannot be
22598 sure that @code{Long_Long_Integer} is sufficient to guard against
22599 intermediate overflows. This package does not use dynamic
22600 alllocation, but it does use the secondary stack, so an
22601 appropriate secondary stack package must be present (this
22602 is always true for standard full Ada, but may require
22603 specific steps for restricted run times such as ZFP).
22605 Although @code{ELIMINATED} mode causes expressions to use arbitrary
22606 precision arithmetic, avoiding overflow, the final result
22607 must be in an appropriate range. This is true even if the
22608 final result is of type @code{[Long_[Long_]]Integer'Base}, which
22609 still has the same bounds as its associated constrained
22612 Currently, the @code{ELIMINATED} mode is only available on target
22613 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
22616 @node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
22617 @anchor{gnat_ugn/gnat_and_program_execution id61}@anchor{16b}@anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{28}
22618 @section Performing Dimensionality Analysis in GNAT
22621 @geindex Dimensionality analysis
22623 The GNAT compiler supports dimensionality checking. The user can
22624 specify physical units for objects, and the compiler will verify that uses
22625 of these objects are compatible with their dimensions, in a fashion that is
22626 familiar to engineering practice. The dimensions of algebraic expressions
22627 (including powers with static exponents) are computed from their constituents.
22629 @geindex Dimension_System aspect
22631 @geindex Dimension aspect
22633 This feature depends on Ada 2012 aspect specifications, and is available from
22634 version 7.0.1 of GNAT onwards.
22635 The GNAT-specific aspect @code{Dimension_System}
22636 allows you to define a system of units; the aspect @code{Dimension}
22637 then allows the user to declare dimensioned quantities within a given system.
22638 (These aspects are described in the @emph{Implementation Defined Aspects}
22639 chapter of the @emph{GNAT Reference Manual}).
22641 The major advantage of this model is that it does not require the declaration of
22642 multiple operators for all possible combinations of types: it is only necessary
22643 to use the proper subtypes in object declarations.
22645 @geindex System.Dim.Mks package (GNAT library)
22647 @geindex MKS_Type type
22649 The simplest way to impose dimensionality checking on a computation is to make
22650 use of the package @code{System.Dim.Mks},
22651 which is part of the GNAT library. This
22652 package defines a floating-point type @code{MKS_Type},
22653 for which a sequence of
22654 dimension names are specified, together with their conventional abbreviations.
22655 The following should be read together with the full specification of the
22656 package, in file @code{s-dimmks.ads}.
22660 @geindex s-dimmks.ads file
22663 type Mks_Type is new Long_Long_Float
22665 Dimension_System => (
22666 (Unit_Name => Meter, Unit_Symbol => 'm', Dim_Symbol => 'L'),
22667 (Unit_Name => Kilogram, Unit_Symbol => "kg", Dim_Symbol => 'M'),
22668 (Unit_Name => Second, Unit_Symbol => 's', Dim_Symbol => 'T'),
22669 (Unit_Name => Ampere, Unit_Symbol => 'A', Dim_Symbol => 'I'),
22670 (Unit_Name => Kelvin, Unit_Symbol => 'K', Dim_Symbol => "Theta"),
22671 (Unit_Name => Mole, Unit_Symbol => "mol", Dim_Symbol => 'N'),
22672 (Unit_Name => Candela, Unit_Symbol => "cd", Dim_Symbol => 'J'));
22676 The package then defines a series of subtypes that correspond to these
22677 conventional units. For example:
22682 subtype Length is Mks_Type
22684 Dimension => (Symbol => 'm', Meter => 1, others => 0);
22688 and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
22689 @code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
22690 @code{Luminous_Intensity} (the standard set of units of the SI system).
22692 The package also defines conventional names for values of each unit, for
22698 m : constant Length := 1.0;
22699 kg : constant Mass := 1.0;
22700 s : constant Time := 1.0;
22701 A : constant Electric_Current := 1.0;
22705 as well as useful multiples of these units:
22710 cm : constant Length := 1.0E-02;
22711 g : constant Mass := 1.0E-03;
22712 min : constant Time := 60.0;
22713 day : constant Time := 60.0 * 24.0 * min;
22718 Using this package, you can then define a derived unit by
22719 providing the aspect that
22720 specifies its dimensions within the MKS system, as well as the string to
22721 be used for output of a value of that unit:
22726 subtype Acceleration is Mks_Type
22727 with Dimension => ("m/sec^2",
22734 Here is a complete example of use:
22739 with System.Dim.MKS; use System.Dim.Mks;
22740 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
22741 with Text_IO; use Text_IO;
22742 procedure Free_Fall is
22743 subtype Acceleration is Mks_Type
22744 with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
22745 G : constant acceleration := 9.81 * m / (s ** 2);
22746 T : Time := 10.0*s;
22750 Put ("Gravitational constant: ");
22751 Put (G, Aft => 2, Exp => 0); Put_Line ("");
22752 Distance := 0.5 * G * T ** 2;
22753 Put ("distance travelled in 10 seconds of free fall ");
22754 Put (Distance, Aft => 2, Exp => 0);
22760 Execution of this program yields:
22765 Gravitational constant: 9.81 m/sec^2
22766 distance travelled in 10 seconds of free fall 490.50 m
22770 However, incorrect assignments such as:
22776 Distance := 5.0 * kg;
22780 are rejected with the following diagnoses:
22786 >>> dimensions mismatch in assignment
22787 >>> left-hand side has dimension [L]
22788 >>> right-hand side is dimensionless
22790 Distance := 5.0 * kg:
22791 >>> dimensions mismatch in assignment
22792 >>> left-hand side has dimension [L]
22793 >>> right-hand side has dimension [M]
22797 The dimensions of an expression are properly displayed, even if there is
22798 no explicit subtype for it. If we add to the program:
22803 Put ("Final velocity: ");
22804 Put (G * T, Aft =>2, Exp =>0);
22809 then the output includes:
22814 Final velocity: 98.10 m.s**(-1)
22817 @geindex Dimensionable type
22819 @geindex Dimensioned subtype
22822 The type @code{Mks_Type} is said to be a @emph{dimensionable type} since it has a
22823 @code{Dimension_System} aspect, and the subtypes @code{Length}, @code{Mass}, etc.,
22824 are said to be @emph{dimensioned subtypes} since each one has a @code{Dimension}
22829 @geindex Dimension Vector (for a dimensioned subtype)
22831 @geindex Dimension aspect
22833 @geindex Dimension_System aspect
22836 The @code{Dimension} aspect of a dimensioned subtype @code{S} defines a mapping
22837 from the base type's Unit_Names to integer (or, more generally, rational)
22838 values. This mapping is the @emph{dimension vector} (also referred to as the
22839 @emph{dimensionality}) for that subtype, denoted by @code{DV(S)}, and thus for each
22840 object of that subtype. Intuitively, the value specified for each
22841 @code{Unit_Name} is the exponent associated with that unit; a zero value
22842 means that the unit is not used. For example:
22848 Acc : Acceleration;
22856 Here @code{DV(Acc)} = @code{DV(Acceleration)} =
22857 @code{(Meter=>1, Kilogram=>0, Second=>-2, Ampere=>0, Kelvin=>0, Mole=>0, Candela=>0)}.
22858 Symbolically, we can express this as @code{Meter / Second**2}.
22860 The dimension vector of an arithmetic expression is synthesized from the
22861 dimension vectors of its components, with compile-time dimensionality checks
22862 that help prevent mismatches such as using an @code{Acceleration} where a
22863 @code{Length} is required.
22865 The dimension vector of the result of an arithmetic expression @emph{expr}, or
22866 @code{DV(@emph{expr})}, is defined as follows, assuming conventional
22867 mathematical definitions for the vector operations that are used:
22873 If @emph{expr} is of the type @emph{universal_real}, or is not of a dimensioned subtype,
22874 then @emph{expr} is dimensionless; @code{DV(@emph{expr})} is the empty vector.
22877 @code{DV(@emph{op expr})}, where @emph{op} is a unary operator, is @code{DV(@emph{expr})}
22880 @code{DV(@emph{expr1 op expr2})} where @emph{op} is "+" or "-" is @code{DV(@emph{expr1})}
22881 provided that @code{DV(@emph{expr1})} = @code{DV(@emph{expr2})}.
22882 If this condition is not met then the construct is illegal.
22885 @code{DV(@emph{expr1} * @emph{expr2})} is @code{DV(@emph{expr1})} + @code{DV(@emph{expr2})},
22886 and @code{DV(@emph{expr1} / @emph{expr2})} = @code{DV(@emph{expr1})} - @code{DV(@emph{expr2})}.
22887 In this context if one of the @emph{expr}s is dimensionless then its empty
22888 dimension vector is treated as @code{(others => 0)}.
22891 @code{DV(@emph{expr} ** @emph{power})} is @emph{power} * @code{DV(@emph{expr})},
22892 provided that @emph{power} is a static rational value. If this condition is not
22893 met then the construct is illegal.
22896 Note that, by the above rules, it is illegal to use binary "+" or "-" to
22897 combine a dimensioned and dimensionless value. Thus an expression such as
22898 @code{acc-10.0} is illegal, where @code{acc} is an object of subtype
22899 @code{Acceleration}.
22901 The dimensionality checks for relationals use the same rules as
22902 for "+" and "-"; thus
22920 and is thus illegal. Analogously a conditional expression
22921 requires the same dimension vector for each branch.
22923 The dimension vector of a type conversion @code{T(@emph{expr})} is defined
22924 as follows, based on the nature of @code{T}:
22930 If @code{T} is a dimensioned subtype then @code{DV(T(@emph{expr}))} is @code{DV(T)}
22931 provided that either @emph{expr} is dimensionless or
22932 @code{DV(T)} = @code{DV(@emph{expr})}. The conversion is illegal
22933 if @emph{expr} is dimensioned and @code{DV(@emph{expr})} /= @code{DV(T)}.
22934 Note that vector equality does not require that the corresponding
22935 Unit_Names be the same.
22937 As a consequence of the above rule, it is possible to convert between
22938 different dimension systems that follow the same international system
22939 of units, with the seven physical components given in the standard order
22940 (length, mass, time, etc.). Thus a length in meters can be converted to
22941 a length in inches (with a suitable conversion factor) but cannot be
22942 converted, for example, to a mass in pounds.
22945 If @code{T} is the base type for @emph{expr} (and the dimensionless root type of
22946 the dimension system), then @code{DV(T(@emph{expr}))} is @code{DV(expr)}.
22947 Thus, if @emph{expr} is of a dimensioned subtype of @code{T}, the conversion may
22948 be regarded as a "view conversion" that preserves dimensionality.
22950 This rule makes it possible to write generic code that can be instantiated
22951 with compatible dimensioned subtypes. The generic unit will contain
22952 conversions that will consequently be present in instantiations, but
22953 conversions to the base type will preserve dimensionality and make it
22954 possible to write generic code that is correct with respect to
22958 Otherwise (i.e., @code{T} is neither a dimensioned subtype nor a dimensionable
22959 base type), @code{DV(T(@emph{expr}))} is the empty vector. Thus a dimensioned
22960 value can be explicitly converted to a non-dimensioned subtype, which
22961 of course then escapes dimensionality analysis.
22964 The dimension vector for a type qualification @code{T'(@emph{expr})} is the same
22965 as for the type conversion @code{T(@emph{expr})}.
22967 An assignment statement
22976 requires @code{DV(Source)} = @code{DV(Target)}, and analogously for parameter
22977 passing (the dimension vector for the actual parameter must be equal to the
22978 dimension vector for the formal parameter).
22980 @node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
22981 @anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{29}@anchor{gnat_ugn/gnat_and_program_execution id62}@anchor{16c}
22982 @section Stack Related Facilities
22985 This section describes some useful tools associated with stack
22986 checking and analysis. In
22987 particular, it deals with dynamic and static stack usage measurements.
22990 * Stack Overflow Checking::
22991 * Static Stack Usage Analysis::
22992 * Dynamic Stack Usage Analysis::
22996 @node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
22997 @anchor{gnat_ugn/gnat_and_program_execution id63}@anchor{1ca}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{f4}
22998 @subsection Stack Overflow Checking
23001 @geindex Stack Overflow Checking
23003 @geindex -fstack-check (gcc)
23005 For most operating systems, @code{gcc} does not perform stack overflow
23006 checking by default. This means that if the main environment task or
23007 some other task exceeds the available stack space, then unpredictable
23008 behavior will occur. Most native systems offer some level of protection by
23009 adding a guard page at the end of each task stack. This mechanism is usually
23010 not enough for dealing properly with stack overflow situations because
23011 a large local variable could "jump" above the guard page.
23012 Furthermore, when the
23013 guard page is hit, there may not be any space left on the stack for executing
23014 the exception propagation code. Enabling stack checking avoids
23017 To activate stack checking, compile all units with the @code{gcc} option
23018 @code{-fstack-check}. For example:
23023 $ gcc -c -fstack-check package1.adb
23027 Units compiled with this option will generate extra instructions to check
23028 that any use of the stack (for procedure calls or for declaring local
23029 variables in declare blocks) does not exceed the available stack space.
23030 If the space is exceeded, then a @code{Storage_Error} exception is raised.
23032 For declared tasks, the stack size is controlled by the size
23033 given in an applicable @code{Storage_Size} pragma or by the value specified
23034 at bind time with @code{-d} (@ref{11f,,Switches for gnatbind}) or is set to
23035 the default size as defined in the GNAT runtime otherwise.
23037 @geindex GNAT_STACK_LIMIT
23039 For the environment task, the stack size depends on
23040 system defaults and is unknown to the compiler. Stack checking
23041 may still work correctly if a fixed
23042 size stack is allocated, but this cannot be guaranteed.
23043 To ensure that a clean exception is signalled for stack
23044 overflow, set the environment variable
23045 @geindex GNAT_STACK_LIMIT
23046 @geindex environment variable; GNAT_STACK_LIMIT
23047 @code{GNAT_STACK_LIMIT} to indicate the maximum
23048 stack area that can be used, as in:
23053 $ SET GNAT_STACK_LIMIT 1600
23057 The limit is given in kilobytes, so the above declaration would
23058 set the stack limit of the environment task to 1.6 megabytes.
23059 Note that the only purpose of this usage is to limit the amount
23060 of stack used by the environment task. If it is necessary to
23061 increase the amount of stack for the environment task, then this
23062 is an operating systems issue, and must be addressed with the
23063 appropriate operating systems commands.
23065 @node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
23066 @anchor{gnat_ugn/gnat_and_program_execution id64}@anchor{1cb}@anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{f5}
23067 @subsection Static Stack Usage Analysis
23070 @geindex Static Stack Usage Analysis
23072 @geindex -fstack-usage
23074 A unit compiled with @code{-fstack-usage} will generate an extra file
23076 the maximum amount of stack used, on a per-function basis.
23077 The file has the same
23078 basename as the target object file with a @code{.su} extension.
23079 Each line of this file is made up of three fields:
23085 The name of the function.
23091 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
23094 The second field corresponds to the size of the known part of the function
23097 The qualifier @code{static} means that the function frame size
23099 It usually means that all local variables have a static size.
23100 In this case, the second field is a reliable measure of the function stack
23103 The qualifier @code{dynamic} means that the function frame size is not static.
23104 It happens mainly when some local variables have a dynamic size. When this
23105 qualifier appears alone, the second field is not a reliable measure
23106 of the function stack analysis. When it is qualified with @code{bounded}, it
23107 means that the second field is a reliable maximum of the function stack
23110 A unit compiled with @code{-Wstack-usage} will issue a warning for each
23111 subprogram whose stack usage might be larger than the specified amount of
23112 bytes. The wording is in keeping with the qualifier documented above.
23114 @node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
23115 @anchor{gnat_ugn/gnat_and_program_execution id65}@anchor{1cc}@anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{121}
23116 @subsection Dynamic Stack Usage Analysis
23119 It is possible to measure the maximum amount of stack used by a task, by
23120 adding a switch to @code{gnatbind}, as:
23125 $ gnatbind -u0 file
23129 With this option, at each task termination, its stack usage is output on
23131 It is not always convenient to output the stack usage when the program
23132 is still running. Hence, it is possible to delay this output until program
23133 termination. for a given number of tasks specified as the argument of the
23134 @code{-u} option. For instance:
23139 $ gnatbind -u100 file
23143 will buffer the stack usage information of the first 100 tasks to terminate and
23144 output this info at program termination. Results are displayed in four
23150 Index | Task Name | Stack Size | Stack Usage
23160 @emph{Index} is a number associated with each task.
23163 @emph{Task Name} is the name of the task analyzed.
23166 @emph{Stack Size} is the maximum size for the stack.
23169 @emph{Stack Usage} is the measure done by the stack analyzer.
23170 In order to prevent overflow, the stack
23171 is not entirely analyzed, and it's not possible to know exactly how
23172 much has actually been used.
23175 The environment task stack, e.g., the stack that contains the main unit, is
23176 only processed when the environment variable GNAT_STACK_LIMIT is set.
23178 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
23179 stack usage reports at run-time. See its body for the details.
23181 @node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
23182 @anchor{gnat_ugn/gnat_and_program_execution id66}@anchor{16d}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{2a}
23183 @section Memory Management Issues
23186 This section describes some useful memory pools provided in the GNAT library
23187 and in particular the GNAT Debug Pool facility, which can be used to detect
23188 incorrect uses of access values (including 'dangling references').
23192 * Some Useful Memory Pools::
23193 * The GNAT Debug Pool Facility::
23197 @node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
23198 @anchor{gnat_ugn/gnat_and_program_execution id67}@anchor{1cd}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{1ce}
23199 @subsection Some Useful Memory Pools
23202 @geindex Memory Pool
23207 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
23208 storage pool. Allocations use the standard system call @code{malloc} while
23209 deallocations use the standard system call @code{free}. No reclamation is
23210 performed when the pool goes out of scope. For performance reasons, the
23211 standard default Ada allocators/deallocators do not use any explicit storage
23212 pools but if they did, they could use this storage pool without any change in
23213 behavior. That is why this storage pool is used when the user
23214 manages to make the default implicit allocator explicit as in this example:
23219 type T1 is access Something;
23220 -- no Storage pool is defined for T2
23222 type T2 is access Something_Else;
23223 for T2'Storage_Pool use T1'Storage_Pool;
23224 -- the above is equivalent to
23225 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
23229 The @code{System.Pool_Local} package offers the @code{Unbounded_Reclaim_Pool} storage
23230 pool. The allocation strategy is similar to @code{Pool_Local}
23231 except that the all
23232 storage allocated with this pool is reclaimed when the pool object goes out of
23233 scope. This pool provides a explicit mechanism similar to the implicit one
23234 provided by several Ada 83 compilers for allocations performed through a local
23235 access type and whose purpose was to reclaim memory when exiting the
23236 scope of a given local access. As an example, the following program does not
23237 leak memory even though it does not perform explicit deallocation:
23242 with System.Pool_Local;
23243 procedure Pooloc1 is
23244 procedure Internal is
23245 type A is access Integer;
23246 X : System.Pool_Local.Unbounded_Reclaim_Pool;
23247 for A'Storage_Pool use X;
23250 for I in 1 .. 50 loop
23255 for I in 1 .. 100 loop
23262 The @code{System.Pool_Size} package implements the @code{Stack_Bounded_Pool} used when
23263 @code{Storage_Size} is specified for an access type.
23264 The whole storage for the pool is
23265 allocated at once, usually on the stack at the point where the access type is
23266 elaborated. It is automatically reclaimed when exiting the scope where the
23267 access type is defined. This package is not intended to be used directly by the
23268 user and it is implicitly used for each such declaration:
23273 type T1 is access Something;
23274 for T1'Storage_Size use 10_000;
23278 @node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
23279 @anchor{gnat_ugn/gnat_and_program_execution id68}@anchor{1cf}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{1d0}
23280 @subsection The GNAT Debug Pool Facility
23283 @geindex Debug Pool
23287 @geindex memory corruption
23289 The use of unchecked deallocation and unchecked conversion can easily
23290 lead to incorrect memory references. The problems generated by such
23291 references are usually difficult to tackle because the symptoms can be
23292 very remote from the origin of the problem. In such cases, it is
23293 very helpful to detect the problem as early as possible. This is the
23294 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
23296 In order to use the GNAT specific debugging pool, the user must
23297 associate a debug pool object with each of the access types that may be
23298 related to suspected memory problems. See Ada Reference Manual 13.11.
23303 type Ptr is access Some_Type;
23304 Pool : GNAT.Debug_Pools.Debug_Pool;
23305 for Ptr'Storage_Pool use Pool;
23309 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
23310 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
23311 allow the user to redefine allocation and deallocation strategies. They
23312 also provide a checkpoint for each dereference, through the use of
23313 the primitive operation @code{Dereference} which is implicitly called at
23314 each dereference of an access value.
23316 Once an access type has been associated with a debug pool, operations on
23317 values of the type may raise four distinct exceptions,
23318 which correspond to four potential kinds of memory corruption:
23324 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
23327 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
23330 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
23333 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
23336 For types associated with a Debug_Pool, dynamic allocation is performed using
23337 the standard GNAT allocation routine. References to all allocated chunks of
23338 memory are kept in an internal dictionary. Several deallocation strategies are
23339 provided, whereupon the user can choose to release the memory to the system,
23340 keep it allocated for further invalid access checks, or fill it with an easily
23341 recognizable pattern for debug sessions. The memory pattern is the old IBM
23342 hexadecimal convention: @code{16#DEADBEEF#}.
23344 See the documentation in the file g-debpoo.ads for more information on the
23345 various strategies.
23347 Upon each dereference, a check is made that the access value denotes a
23348 properly allocated memory location. Here is a complete example of use of
23349 @code{Debug_Pools}, that includes typical instances of memory corruption:
23354 with Gnat.Io; use Gnat.Io;
23355 with Unchecked_Deallocation;
23356 with Unchecked_Conversion;
23357 with GNAT.Debug_Pools;
23358 with System.Storage_Elements;
23359 with Ada.Exceptions; use Ada.Exceptions;
23360 procedure Debug_Pool_Test is
23362 type T is access Integer;
23363 type U is access all T;
23365 P : GNAT.Debug_Pools.Debug_Pool;
23366 for T'Storage_Pool use P;
23368 procedure Free is new Unchecked_Deallocation (Integer, T);
23369 function UC is new Unchecked_Conversion (U, T);
23372 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
23382 Put_Line (Integer'Image(B.all));
23384 when E : others => Put_Line ("raised: " & Exception_Name (E));
23389 when E : others => Put_Line ("raised: " & Exception_Name (E));
23393 Put_Line (Integer'Image(B.all));
23395 when E : others => Put_Line ("raised: " & Exception_Name (E));
23400 when E : others => Put_Line ("raised: " & Exception_Name (E));
23403 end Debug_Pool_Test;
23407 The debug pool mechanism provides the following precise diagnostics on the
23408 execution of this erroneous program:
23414 Total allocated bytes : 0
23415 Total deallocated bytes : 0
23416 Current Water Mark: 0
23420 Total allocated bytes : 8
23421 Total deallocated bytes : 0
23422 Current Water Mark: 8
23425 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
23426 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
23427 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
23428 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
23430 Total allocated bytes : 8
23431 Total deallocated bytes : 4
23432 Current Water Mark: 4
23438 @c -- Non-breaking space in running text
23439 @c -- E.g. Ada |nbsp| 95
23441 @node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
23442 @anchor{gnat_ugn/platform_specific_information platform-specific-information}@anchor{d}@anchor{gnat_ugn/platform_specific_information doc}@anchor{1d1}@anchor{gnat_ugn/platform_specific_information id1}@anchor{1d2}
23443 @chapter Platform-Specific Information
23446 This appendix contains information relating to the implementation
23447 of run-time libraries on various platforms and also covers
23448 topics related to the GNAT implementation on Windows and Mac OS.
23451 * Run-Time Libraries::
23452 * Specifying a Run-Time Library::
23453 * Microsoft Windows Topics::
23458 @node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
23459 @anchor{gnat_ugn/platform_specific_information id2}@anchor{1d3}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{2b}
23460 @section Run-Time Libraries
23463 @geindex Tasking and threads libraries
23465 @geindex Threads libraries and tasking
23467 @geindex Run-time libraries (platform-specific information)
23469 The GNAT run-time implementation may vary with respect to both the
23470 underlying threads library and the exception-handling scheme.
23471 For threads support, the default run-time will bind to the thread
23472 package of the underlying operating system.
23474 For exception handling, either or both of two models are supplied:
23478 @geindex Zero-Cost Exceptions
23480 @geindex ZCX (Zero-Cost Exceptions)
23487 @strong{Zero-Cost Exceptions} ("ZCX"),
23488 which uses binder-generated tables that
23489 are interrogated at run time to locate a handler.
23491 @geindex setjmp/longjmp Exception Model
23493 @geindex SJLJ (setjmp/longjmp Exception Model)
23496 @strong{setjmp / longjmp} ('SJLJ'),
23497 which uses dynamically-set data to establish
23498 the set of handlers
23501 Most programs should experience a substantial speed improvement by
23502 being compiled with a ZCX run-time.
23503 This is especially true for
23504 tasking applications or applications with many exception handlers.@}
23506 This section summarizes which combinations of threads and exception support
23507 are supplied on various GNAT platforms.
23508 It then shows how to select a particular library either
23509 permanently or temporarily,
23510 explains the properties of (and tradeoffs among) the various threads
23511 libraries, and provides some additional
23512 information about several specific platforms.
23515 * Summary of Run-Time Configurations::
23519 @node Summary of Run-Time Configurations,,,Run-Time Libraries
23520 @anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{1d4}@anchor{gnat_ugn/platform_specific_information id3}@anchor{1d5}
23521 @subsection Summary of Run-Time Configurations
23525 @multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx}
23582 native Win32 threads
23594 native Win32 threads
23619 @node Specifying a Run-Time Library,Microsoft Windows Topics,Run-Time Libraries,Platform-Specific Information
23620 @anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{1d6}@anchor{gnat_ugn/platform_specific_information id4}@anchor{1d7}
23621 @section Specifying a Run-Time Library
23624 The @code{adainclude} subdirectory containing the sources of the GNAT
23625 run-time library, and the @code{adalib} subdirectory containing the
23626 @code{ALI} files and the static and/or shared GNAT library, are located
23627 in the gcc target-dependent area:
23632 target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
23636 As indicated above, on some platforms several run-time libraries are supplied.
23637 These libraries are installed in the target dependent area and
23638 contain a complete source and binary subdirectory. The detailed description
23639 below explains the differences between the different libraries in terms of
23640 their thread support.
23642 The default run-time library (when GNAT is installed) is @emph{rts-native}.
23643 This default run-time is selected by the means of soft links.
23644 For example on x86-linux:
23647 @c -- $(target-dir)
23649 @c -- +--- adainclude----------+
23651 @c -- +--- adalib-----------+ |
23653 @c -- +--- rts-native | |
23655 @c -- | +--- adainclude <---+
23657 @c -- | +--- adalib <----+
23659 @c -- +--- rts-sjlj
23661 @c -- +--- adainclude
23669 _______/ / \ \_________________
23672 ADAINCLUDE ADALIB rts-native rts-sjlj
23677 +-------------> adainclude adalib adainclude adalib
23680 +---------------------+
23682 Run-Time Library Directory Structure
23683 (Upper-case names and dotted/dashed arrows represent soft links)
23686 If the @emph{rts-sjlj} library is to be selected on a permanent basis,
23687 these soft links can be modified with the following commands:
23693 $ rm -f adainclude adalib
23694 $ ln -s rts-sjlj/adainclude adainclude
23695 $ ln -s rts-sjlj/adalib adalib
23699 Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
23700 @code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
23701 @code{$target/ada_object_path}.
23703 @geindex --RTS option
23705 Selecting another run-time library temporarily can be
23706 achieved by using the @code{--RTS} switch, e.g., @code{--RTS=sjlj}
23707 @anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy}@anchor{1d8}
23708 @geindex SCHED_FIFO scheduling policy
23710 @geindex SCHED_RR scheduling policy
23712 @geindex SCHED_OTHER scheduling policy
23715 * Choosing the Scheduling Policy::
23719 @node Choosing the Scheduling Policy,,,Specifying a Run-Time Library
23720 @anchor{gnat_ugn/platform_specific_information id5}@anchor{1d9}
23721 @subsection Choosing the Scheduling Policy
23724 When using a POSIX threads implementation, you have a choice of several
23725 scheduling policies: @code{SCHED_FIFO}, @code{SCHED_RR} and @code{SCHED_OTHER}.
23727 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
23728 or @code{SCHED_RR} requires special (e.g., root) privileges.
23730 @geindex pragma Time_Slice
23732 @geindex -T0 option
23734 @geindex pragma Task_Dispatching_Policy
23736 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
23738 you can use one of the following:
23744 @code{pragma Time_Slice (0.0)}
23747 the corresponding binder option @code{-T0}
23750 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23753 To specify @code{SCHED_RR},
23754 you should use @code{pragma Time_Slice} with a
23755 value greater than 0.0, or else use the corresponding @code{-T}
23758 To make sure a program is running as root, you can put something like
23759 this in a library package body in your application:
23764 function geteuid return Integer;
23765 pragma Import (C, geteuid, "geteuid");
23766 Ignore : constant Boolean :=
23767 (if geteuid = 0 then True else raise Program_Error with "must be root");
23771 It gets the effective user id, and if it's not 0 (i.e. root), it raises
23776 @node Microsoft Windows Topics,Mac OS Topics,Specifying a Run-Time Library,Platform-Specific Information
23777 @anchor{gnat_ugn/platform_specific_information id6}@anchor{1da}@anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{2c}
23778 @section Microsoft Windows Topics
23781 This section describes topics that are specific to the Microsoft Windows
23789 * Using GNAT on Windows::
23790 * Using a network installation of GNAT::
23791 * CONSOLE and WINDOWS subsystems::
23792 * Temporary Files::
23793 * Disabling Command Line Argument Expansion::
23794 * Mixed-Language Programming on Windows::
23795 * Windows Specific Add-Ons::
23799 @node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
23800 @anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{1db}@anchor{gnat_ugn/platform_specific_information id7}@anchor{1dc}
23801 @subsection Using GNAT on Windows
23804 One of the strengths of the GNAT technology is that its tool set
23805 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
23806 @code{gdb} debugger, etc.) is used in the same way regardless of the
23809 On Windows this tool set is complemented by a number of Microsoft-specific
23810 tools that have been provided to facilitate interoperability with Windows
23811 when this is required. With these tools:
23817 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
23821 You can use any Dynamically Linked Library (DLL) in your Ada code (both
23822 relocatable and non-relocatable DLLs are supported).
23825 You can build Ada DLLs for use in other applications. These applications
23826 can be written in a language other than Ada (e.g., C, C++, etc). Again both
23827 relocatable and non-relocatable Ada DLLs are supported.
23830 You can include Windows resources in your Ada application.
23833 You can use or create COM/DCOM objects.
23836 Immediately below are listed all known general GNAT-for-Windows restrictions.
23837 Other restrictions about specific features like Windows Resources and DLLs
23838 are listed in separate sections below.
23844 It is not possible to use @code{GetLastError} and @code{SetLastError}
23845 when tasking, protected records, or exceptions are used. In these
23846 cases, in order to implement Ada semantics, the GNAT run-time system
23847 calls certain Win32 routines that set the last error variable to 0 upon
23848 success. It should be possible to use @code{GetLastError} and
23849 @code{SetLastError} when tasking, protected record, and exception
23850 features are not used, but it is not guaranteed to work.
23853 It is not possible to link against Microsoft C++ libraries except for
23854 import libraries. Interfacing must be done by the mean of DLLs.
23857 It is possible to link against Microsoft C libraries. Yet the preferred
23858 solution is to use C/C++ compiler that comes with GNAT, since it
23859 doesn't require having two different development environments and makes the
23860 inter-language debugging experience smoother.
23863 When the compilation environment is located on FAT32 drives, users may
23864 experience recompilations of the source files that have not changed if
23865 Daylight Saving Time (DST) state has changed since the last time files
23866 were compiled. NTFS drives do not have this problem.
23869 No components of the GNAT toolset use any entries in the Windows
23870 registry. The only entries that can be created are file associations and
23871 PATH settings, provided the user has chosen to create them at installation
23872 time, as well as some minimal book-keeping information needed to correctly
23873 uninstall or integrate different GNAT products.
23876 @node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
23877 @anchor{gnat_ugn/platform_specific_information id8}@anchor{1dd}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{1de}
23878 @subsection Using a network installation of GNAT
23881 Make sure the system on which GNAT is installed is accessible from the
23882 current machine, i.e., the install location is shared over the network.
23883 Shared resources are accessed on Windows by means of UNC paths, which
23884 have the format @code{\\\\server\\sharename\\path}
23886 In order to use such a network installation, simply add the UNC path of the
23887 @code{bin} directory of your GNAT installation in front of your PATH. For
23888 example, if GNAT is installed in @code{\GNAT} directory of a share location
23889 called @code{c-drive} on a machine @code{LOKI}, the following command will
23895 $ path \\loki\c-drive\gnat\bin;%path%`
23899 Be aware that every compilation using the network installation results in the
23900 transfer of large amounts of data across the network and will likely cause
23901 serious performance penalty.
23903 @node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
23904 @anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{1df}@anchor{gnat_ugn/platform_specific_information id9}@anchor{1e0}
23905 @subsection CONSOLE and WINDOWS subsystems
23908 @geindex CONSOLE Subsystem
23910 @geindex WINDOWS Subsystem
23914 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
23915 (which is the default subsystem) will always create a console when
23916 launching the application. This is not something desirable when the
23917 application has a Windows GUI. To get rid of this console the
23918 application must be using the @code{WINDOWS} subsystem. To do so
23919 the @code{-mwindows} linker option must be specified.
23924 $ gnatmake winprog -largs -mwindows
23928 @node Temporary Files,Disabling Command Line Argument Expansion,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
23929 @anchor{gnat_ugn/platform_specific_information id10}@anchor{1e1}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{1e2}
23930 @subsection Temporary Files
23933 @geindex Temporary files
23935 It is possible to control where temporary files gets created by setting
23938 @geindex environment variable; TMP
23939 @code{TMP} environment variable. The file will be created:
23945 Under the directory pointed to by the
23947 @geindex environment variable; TMP
23948 @code{TMP} environment variable if
23949 this directory exists.
23952 Under @code{c:\temp}, if the
23954 @geindex environment variable; TMP
23955 @code{TMP} environment variable is not
23956 set (or not pointing to a directory) and if this directory exists.
23959 Under the current working directory otherwise.
23962 This allows you to determine exactly where the temporary
23963 file will be created. This is particularly useful in networked
23964 environments where you may not have write access to some
23967 @node Disabling Command Line Argument Expansion,Mixed-Language Programming on Windows,Temporary Files,Microsoft Windows Topics
23968 @anchor{gnat_ugn/platform_specific_information disabling-command-line-argument-expansion}@anchor{1e3}
23969 @subsection Disabling Command Line Argument Expansion
23972 @geindex Command Line Argument Expansion
23974 By default, an executable compiled for the Windows platform will do
23975 the following postprocessing on the arguments passed on the command
23982 If the argument contains the characters @code{*} and/or @code{?}, then
23983 file expansion will be attempted. For example, if the current directory
23984 contains @code{a.txt} and @code{b.txt}, then when calling:
23987 $ my_ada_program *.txt
23990 The following arguments will effectively be passed to the main program
23991 (for example when using @code{Ada.Command_Line.Argument}):
23994 Ada.Command_Line.Argument (1) -> "a.txt"
23995 Ada.Command_Line.Argument (2) -> "b.txt"
23999 Filename expansion can be disabled for a given argument by using single
24000 quotes. Thus, calling:
24003 $ my_ada_program '*.txt'
24009 Ada.Command_Line.Argument (1) -> "*.txt"
24013 Note that if the program is launched from a shell such as Cygwin Bash
24014 then quote removal might be performed by the shell.
24016 In some contexts it might be useful to disable this feature (for example if
24017 the program performs its own argument expansion). In order to do this, a C
24018 symbol needs to be defined and set to @code{0}. You can do this by
24019 adding the following code fragment in one of your Ada units:
24022 Do_Argv_Expansion : Integer := 0;
24023 pragma Export (C, Do_Argv_Expansion, "__gnat_do_argv_expansion");
24026 The results of previous examples will be respectively:
24029 Ada.Command_Line.Argument (1) -> "*.txt"
24035 Ada.Command_Line.Argument (1) -> "'*.txt'"
24038 @node Mixed-Language Programming on Windows,Windows Specific Add-Ons,Disabling Command Line Argument Expansion,Microsoft Windows Topics
24039 @anchor{gnat_ugn/platform_specific_information id11}@anchor{1e4}@anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{1e5}
24040 @subsection Mixed-Language Programming on Windows
24043 Developing pure Ada applications on Windows is no different than on
24044 other GNAT-supported platforms. However, when developing or porting an
24045 application that contains a mix of Ada and C/C++, the choice of your
24046 Windows C/C++ development environment conditions your overall
24047 interoperability strategy.
24049 If you use @code{gcc} or Microsoft C to compile the non-Ada part of
24050 your application, there are no Windows-specific restrictions that
24051 affect the overall interoperability with your Ada code. If you do want
24052 to use the Microsoft tools for your C++ code, you have two choices:
24058 Encapsulate your C++ code in a DLL to be linked with your Ada
24059 application. In this case, use the Microsoft or whatever environment to
24060 build the DLL and use GNAT to build your executable
24061 (@ref{1e6,,Using DLLs with GNAT}).
24064 Or you can encapsulate your Ada code in a DLL to be linked with the
24065 other part of your application. In this case, use GNAT to build the DLL
24066 (@ref{1e7,,Building DLLs with GNAT Project files}) and use the Microsoft
24067 or whatever environment to build your executable.
24070 In addition to the description about C main in
24071 @ref{44,,Mixed Language Programming} section, if the C main uses a
24072 stand-alone library it is required on x86-windows to
24073 setup the SEH context. For this the C main must looks like this:
24079 extern void adainit (void);
24080 extern void adafinal (void);
24081 extern void __gnat_initialize(void*);
24082 extern void call_to_ada (void);
24084 int main (int argc, char *argv[])
24088 /* Initialize the SEH context */
24089 __gnat_initialize (&SEH);
24093 /* Then call Ada services in the stand-alone library */
24102 Note that this is not needed on x86_64-windows where the Windows
24103 native SEH support is used.
24106 * Windows Calling Conventions::
24107 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs.
24108 * Using DLLs with GNAT::
24109 * Building DLLs with GNAT Project files::
24110 * Building DLLs with GNAT::
24111 * Building DLLs with gnatdll::
24112 * Ada DLLs and Finalization::
24113 * Creating a Spec for Ada DLLs::
24114 * GNAT and Windows Resources::
24115 * Using GNAT DLLs from Microsoft Visual Studio Applications::
24116 * Debugging a DLL::
24117 * Setting Stack Size from gnatlink::
24118 * Setting Heap Size from gnatlink::
24122 @node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
24123 @anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{1e8}@anchor{gnat_ugn/platform_specific_information id12}@anchor{1e9}
24124 @subsubsection Windows Calling Conventions
24131 This section pertain only to Win32. On Win64 there is a single native
24132 calling convention. All convention specifiers are ignored on this
24135 When a subprogram @code{F} (caller) calls a subprogram @code{G}
24136 (callee), there are several ways to push @code{G}'s parameters on the
24137 stack and there are several possible scenarios to clean up the stack
24138 upon @code{G}'s return. A calling convention is an agreed upon software
24139 protocol whereby the responsibilities between the caller (@code{F}) and
24140 the callee (@code{G}) are clearly defined. Several calling conventions
24141 are available for Windows:
24147 @code{C} (Microsoft defined)
24150 @code{Stdcall} (Microsoft defined)
24153 @code{Win32} (GNAT specific)
24156 @code{DLL} (GNAT specific)
24160 * C Calling Convention::
24161 * Stdcall Calling Convention::
24162 * Win32 Calling Convention::
24163 * DLL Calling Convention::
24167 @node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
24168 @anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{1ea}@anchor{gnat_ugn/platform_specific_information id13}@anchor{1eb}
24169 @subsubsection @code{C} Calling Convention
24172 This is the default calling convention used when interfacing to C/C++
24173 routines compiled with either @code{gcc} or Microsoft Visual C++.
24175 In the @code{C} calling convention subprogram parameters are pushed on the
24176 stack by the caller from right to left. The caller itself is in charge of
24177 cleaning up the stack after the call. In addition, the name of a routine
24178 with @code{C} calling convention is mangled by adding a leading underscore.
24180 The name to use on the Ada side when importing (or exporting) a routine
24181 with @code{C} calling convention is the name of the routine. For
24182 instance the C function:
24187 int get_val (long);
24191 should be imported from Ada as follows:
24196 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24197 pragma Import (C, Get_Val, External_Name => "get_val");
24201 Note that in this particular case the @code{External_Name} parameter could
24202 have been omitted since, when missing, this parameter is taken to be the
24203 name of the Ada entity in lower case. When the @code{Link_Name} parameter
24204 is missing, as in the above example, this parameter is set to be the
24205 @code{External_Name} with a leading underscore.
24207 When importing a variable defined in C, you should always use the @code{C}
24208 calling convention unless the object containing the variable is part of a
24209 DLL (in which case you should use the @code{Stdcall} calling
24210 convention, @ref{1ec,,Stdcall Calling Convention}).
24212 @node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
24213 @anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{1ec}@anchor{gnat_ugn/platform_specific_information id14}@anchor{1ed}
24214 @subsubsection @code{Stdcall} Calling Convention
24217 This convention, which was the calling convention used for Pascal
24218 programs, is used by Microsoft for all the routines in the Win32 API for
24219 efficiency reasons. It must be used to import any routine for which this
24220 convention was specified.
24222 In the @code{Stdcall} calling convention subprogram parameters are pushed
24223 on the stack by the caller from right to left. The callee (and not the
24224 caller) is in charge of cleaning the stack on routine exit. In addition,
24225 the name of a routine with @code{Stdcall} calling convention is mangled by
24226 adding a leading underscore (as for the @code{C} calling convention) and a
24227 trailing @code{@@@emph{nn}}, where @code{nn} is the overall size (in
24228 bytes) of the parameters passed to the routine.
24230 The name to use on the Ada side when importing a C routine with a
24231 @code{Stdcall} calling convention is the name of the C routine. The leading
24232 underscore and trailing @code{@@@emph{nn}} are added automatically by
24233 the compiler. For instance the Win32 function:
24238 APIENTRY int get_val (long);
24242 should be imported from Ada as follows:
24247 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24248 pragma Import (Stdcall, Get_Val);
24249 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
24253 As for the @code{C} calling convention, when the @code{External_Name}
24254 parameter is missing, it is taken to be the name of the Ada entity in lower
24255 case. If instead of writing the above import pragma you write:
24260 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24261 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
24265 then the imported routine is @code{_retrieve_val@@4}. However, if instead
24266 of specifying the @code{External_Name} parameter you specify the
24267 @code{Link_Name} as in the following example:
24272 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24273 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
24277 then the imported routine is @code{retrieve_val}, that is, there is no
24278 decoration at all. No leading underscore and no Stdcall suffix
24279 @code{@@@emph{nn}}.
24281 This is especially important as in some special cases a DLL's entry
24282 point name lacks a trailing @code{@@@emph{nn}} while the exported
24283 name generated for a call has it.
24285 It is also possible to import variables defined in a DLL by using an
24286 import pragma for a variable. As an example, if a DLL contains a
24287 variable defined as:
24296 then, to access this variable from Ada you should write:
24301 My_Var : Interfaces.C.int;
24302 pragma Import (Stdcall, My_Var);
24306 Note that to ease building cross-platform bindings this convention
24307 will be handled as a @code{C} calling convention on non-Windows platforms.
24309 @node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
24310 @anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{1ee}@anchor{gnat_ugn/platform_specific_information id15}@anchor{1ef}
24311 @subsubsection @code{Win32} Calling Convention
24314 This convention, which is GNAT-specific is fully equivalent to the
24315 @code{Stdcall} calling convention described above.
24317 @node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
24318 @anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{1f0}@anchor{gnat_ugn/platform_specific_information id16}@anchor{1f1}
24319 @subsubsection @code{DLL} Calling Convention
24322 This convention, which is GNAT-specific is fully equivalent to the
24323 @code{Stdcall} calling convention described above.
24325 @node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
24326 @anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{1f2}@anchor{gnat_ugn/platform_specific_information id17}@anchor{1f3}
24327 @subsubsection Introduction to Dynamic Link Libraries (DLLs)
24332 A Dynamically Linked Library (DLL) is a library that can be shared by
24333 several applications running under Windows. A DLL can contain any number of
24334 routines and variables.
24336 One advantage of DLLs is that you can change and enhance them without
24337 forcing all the applications that depend on them to be relinked or
24338 recompiled. However, you should be aware than all calls to DLL routines are
24339 slower since, as you will understand below, such calls are indirect.
24341 To illustrate the remainder of this section, suppose that an application
24342 wants to use the services of a DLL @code{API.dll}. To use the services
24343 provided by @code{API.dll} you must statically link against the DLL or
24344 an import library which contains a jump table with an entry for each
24345 routine and variable exported by the DLL. In the Microsoft world this
24346 import library is called @code{API.lib}. When using GNAT this import
24347 library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
24348 @code{libAPI.a} or @code{libapi.a} (names are case insensitive).
24350 After you have linked your application with the DLL or the import library
24351 and you run your application, here is what happens:
24357 Your application is loaded into memory.
24360 The DLL @code{API.dll} is mapped into the address space of your
24361 application. This means that:
24367 The DLL will use the stack of the calling thread.
24370 The DLL will use the virtual address space of the calling process.
24373 The DLL will allocate memory from the virtual address space of the calling
24377 Handles (pointers) can be safely exchanged between routines in the DLL
24378 routines and routines in the application using the DLL.
24382 The entries in the jump table (from the import library @code{libAPI.dll.a}
24383 or @code{API.lib} or automatically created when linking against a DLL)
24384 which is part of your application are initialized with the addresses
24385 of the routines and variables in @code{API.dll}.
24388 If present in @code{API.dll}, routines @code{DllMain} or
24389 @code{DllMainCRTStartup} are invoked. These routines typically contain
24390 the initialization code needed for the well-being of the routines and
24391 variables exported by the DLL.
24394 There is an additional point which is worth mentioning. In the Windows
24395 world there are two kind of DLLs: relocatable and non-relocatable
24396 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
24397 in the target application address space. If the addresses of two
24398 non-relocatable DLLs overlap and these happen to be used by the same
24399 application, a conflict will occur and the application will run
24400 incorrectly. Hence, when possible, it is always preferable to use and
24401 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
24402 supported by GNAT. Note that the @code{-s} linker option (see GNU Linker
24403 User's Guide) removes the debugging symbols from the DLL but the DLL can
24404 still be relocated.
24406 As a side note, an interesting difference between Microsoft DLLs and
24407 Unix shared libraries, is the fact that on most Unix systems all public
24408 routines are exported by default in a Unix shared library, while under
24409 Windows it is possible (but not required) to list exported routines in
24410 a definition file (see @ref{1f4,,The Definition File}).
24412 @node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
24413 @anchor{gnat_ugn/platform_specific_information id18}@anchor{1f5}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{1e6}
24414 @subsubsection Using DLLs with GNAT
24417 To use the services of a DLL, say @code{API.dll}, in your Ada application
24424 The Ada spec for the routines and/or variables you want to access in
24425 @code{API.dll}. If not available this Ada spec must be built from the C/C++
24426 header files provided with the DLL.
24429 The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
24430 mentioned an import library is a statically linked library containing the
24431 import table which will be filled at load time to point to the actual
24432 @code{API.dll} routines. Sometimes you don't have an import library for the
24433 DLL you want to use. The following sections will explain how to build
24434 one. Note that this is optional.
24437 The actual DLL, @code{API.dll}.
24440 Once you have all the above, to compile an Ada application that uses the
24441 services of @code{API.dll} and whose main subprogram is @code{My_Ada_App},
24442 you simply issue the command
24447 $ gnatmake my_ada_app -largs -lAPI
24451 The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
24452 tells the GNAT linker to look for an import library. The linker will
24453 look for a library name in this specific order:
24459 @code{libAPI.dll.a}
24477 The first three are the GNU style import libraries. The third is the
24478 Microsoft style import libraries. The last two are the actual DLL names.
24480 Note that if the Ada package spec for @code{API.dll} contains the
24486 pragma Linker_Options ("-lAPI");
24490 you do not have to add @code{-largs -lAPI} at the end of the
24491 @code{gnatmake} command.
24493 If any one of the items above is missing you will have to create it
24494 yourself. The following sections explain how to do so using as an
24495 example a fictitious DLL called @code{API.dll}.
24498 * Creating an Ada Spec for the DLL Services::
24499 * Creating an Import Library::
24503 @node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
24504 @anchor{gnat_ugn/platform_specific_information creating-an-ada-spec-for-the-dll-services}@anchor{1f6}@anchor{gnat_ugn/platform_specific_information id19}@anchor{1f7}
24505 @subsubsection Creating an Ada Spec for the DLL Services
24508 A DLL typically comes with a C/C++ header file which provides the
24509 definitions of the routines and variables exported by the DLL. The Ada
24510 equivalent of this header file is a package spec that contains definitions
24511 for the imported entities. If the DLL you intend to use does not come with
24512 an Ada spec you have to generate one such spec yourself. For example if
24513 the header file of @code{API.dll} is a file @code{api.h} containing the
24514 following two definitions:
24524 then the equivalent Ada spec could be:
24529 with Interfaces.C.Strings;
24534 function Get (Str : C.Strings.Chars_Ptr) return C.int;
24537 pragma Import (C, Get);
24538 pragma Import (DLL, Some_Var);
24543 @node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
24544 @anchor{gnat_ugn/platform_specific_information id20}@anchor{1f8}@anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{1f9}
24545 @subsubsection Creating an Import Library
24548 @geindex Import library
24550 If a Microsoft-style import library @code{API.lib} or a GNAT-style
24551 import library @code{libAPI.dll.a} or @code{libAPI.a} is available
24552 with @code{API.dll} you can skip this section. You can also skip this
24553 section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
24554 as in this case it is possible to link directly against the
24555 DLL. Otherwise read on.
24557 @geindex Definition file
24558 @anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{1f4}
24559 @subsubheading The Definition File
24562 As previously mentioned, and unlike Unix systems, the list of symbols
24563 that are exported from a DLL must be provided explicitly in Windows.
24564 The main goal of a definition file is precisely that: list the symbols
24565 exported by a DLL. A definition file (usually a file with a @code{.def}
24566 suffix) has the following structure:
24571 [LIBRARY `@w{`}name`@w{`}]
24572 [DESCRIPTION `@w{`}string`@w{`}]
24574 `@w{`}symbol1`@w{`}
24575 `@w{`}symbol2`@w{`}
24583 @item @emph{LIBRARY name}
24585 This section, which is optional, gives the name of the DLL.
24587 @item @emph{DESCRIPTION string}
24589 This section, which is optional, gives a description string that will be
24590 embedded in the import library.
24592 @item @emph{EXPORTS}
24594 This section gives the list of exported symbols (procedures, functions or
24595 variables). For instance in the case of @code{API.dll} the @code{EXPORTS}
24596 section of @code{API.def} looks like:
24605 Note that you must specify the correct suffix (@code{@@@emph{nn}})
24606 (see @ref{1e8,,Windows Calling Conventions}) for a Stdcall
24607 calling convention function in the exported symbols list.
24609 There can actually be other sections in a definition file, but these
24610 sections are not relevant to the discussion at hand.
24611 @anchor{gnat_ugn/platform_specific_information create-def-file-automatically}@anchor{1fa}
24612 @subsubheading Creating a Definition File Automatically
24615 You can automatically create the definition file @code{API.def}
24616 (see @ref{1f4,,The Definition File}) from a DLL.
24617 For that use the @code{dlltool} program as follows:
24622 $ dlltool API.dll -z API.def --export-all-symbols
24625 Note that if some routines in the DLL have the @code{Stdcall} convention
24626 (@ref{1e8,,Windows Calling Conventions}) with stripped @code{@@@emph{nn}}
24627 suffix then you'll have to edit @code{api.def} to add it, and specify
24628 @code{-k} to @code{gnatdll} when creating the import library.
24630 Here are some hints to find the right @code{@@@emph{nn}} suffix.
24636 If you have the Microsoft import library (.lib), it is possible to get
24637 the right symbols by using Microsoft @code{dumpbin} tool (see the
24638 corresponding Microsoft documentation for further details).
24641 $ dumpbin /exports api.lib
24645 If you have a message about a missing symbol at link time the compiler
24646 tells you what symbol is expected. You just have to go back to the
24647 definition file and add the right suffix.
24650 @anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{1fb}
24651 @subsubheading GNAT-Style Import Library
24654 To create a static import library from @code{API.dll} with the GNAT tools
24655 you should create the .def file, then use @code{gnatdll} tool
24656 (see @ref{1fc,,Using gnatdll}) as follows:
24661 $ gnatdll -e API.def -d API.dll
24664 @code{gnatdll} takes as input a definition file @code{API.def} and the
24665 name of the DLL containing the services listed in the definition file
24666 @code{API.dll}. The name of the static import library generated is
24667 computed from the name of the definition file as follows: if the
24668 definition file name is @code{xyz.def}, the import library name will
24669 be @code{libxyz.a}. Note that in the previous example option
24670 @code{-e} could have been removed because the name of the definition
24671 file (before the @code{.def} suffix) is the same as the name of the
24672 DLL (@ref{1fc,,Using gnatdll} for more information about @code{gnatdll}).
24674 @anchor{gnat_ugn/platform_specific_information msvs-style-import-library}@anchor{1fd}
24675 @subsubheading Microsoft-Style Import Library
24678 A Microsoft import library is needed only if you plan to make an
24679 Ada DLL available to applications developed with Microsoft
24680 tools (@ref{1e5,,Mixed-Language Programming on Windows}).
24682 To create a Microsoft-style import library for @code{API.dll} you
24683 should create the .def file, then build the actual import library using
24684 Microsoft's @code{lib} utility:
24689 $ lib -machine:IX86 -def:API.def -out:API.lib
24692 If you use the above command the definition file @code{API.def} must
24693 contain a line giving the name of the DLL:
24699 See the Microsoft documentation for further details about the usage of
24703 @node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
24704 @anchor{gnat_ugn/platform_specific_information id21}@anchor{1fe}@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{1e7}
24705 @subsubsection Building DLLs with GNAT Project files
24711 There is nothing specific to Windows in the build process.
24712 See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24713 chapter of the @emph{GPRbuild User's Guide}.
24715 Due to a system limitation, it is not possible under Windows to create threads
24716 when inside the @code{DllMain} routine which is used for auto-initialization
24717 of shared libraries, so it is not possible to have library level tasks in SALs.
24719 @node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
24720 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{1ff}@anchor{gnat_ugn/platform_specific_information id22}@anchor{200}
24721 @subsubsection Building DLLs with GNAT
24727 This section explain how to build DLLs using the GNAT built-in DLL
24728 support. With the following procedure it is straight forward to build
24729 and use DLLs with GNAT.
24735 Building object files.
24736 The first step is to build all objects files that are to be included
24737 into the DLL. This is done by using the standard @code{gnatmake} tool.
24741 To build the DLL you must use the @code{gcc} @code{-shared} and
24742 @code{-shared-libgcc} options. It is quite simple to use this method:
24745 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
24748 It is important to note that in this case all symbols found in the
24749 object files are automatically exported. It is possible to restrict
24750 the set of symbols to export by passing to @code{gcc} a definition
24751 file (see @ref{1f4,,The Definition File}).
24755 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
24758 If you use a definition file you must export the elaboration procedures
24759 for every package that required one. Elaboration procedures are named
24760 using the package name followed by "_E".
24763 Preparing DLL to be used.
24764 For the DLL to be used by client programs the bodies must be hidden
24765 from it and the .ali set with read-only attribute. This is very important
24766 otherwise GNAT will recompile all packages and will not actually use
24767 the code in the DLL. For example:
24771 $ copy *.ads *.ali api.dll apilib
24772 $ attrib +R apilib\\*.ali
24776 At this point it is possible to use the DLL by directly linking
24777 against it. Note that you must use the GNAT shared runtime when using
24778 GNAT shared libraries. This is achieved by using the @code{-shared} binder
24784 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
24788 @node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
24789 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{201}@anchor{gnat_ugn/platform_specific_information id23}@anchor{202}
24790 @subsubsection Building DLLs with gnatdll
24796 Note that it is preferred to use GNAT Project files
24797 (@ref{1e7,,Building DLLs with GNAT Project files}) or the built-in GNAT
24798 DLL support (@ref{1ff,,Building DLLs with GNAT}) or to build DLLs.
24800 This section explains how to build DLLs containing Ada code using
24801 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
24802 remainder of this section.
24804 The steps required to build an Ada DLL that is to be used by Ada as well as
24805 non-Ada applications are as follows:
24811 You need to mark each Ada entity exported by the DLL with a @code{C} or
24812 @code{Stdcall} calling convention to avoid any Ada name mangling for the
24813 entities exported by the DLL
24814 (see @ref{203,,Exporting Ada Entities}). You can
24815 skip this step if you plan to use the Ada DLL only from Ada applications.
24818 Your Ada code must export an initialization routine which calls the routine
24819 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
24820 the Ada code in the DLL (@ref{204,,Ada DLLs and Elaboration}). The initialization
24821 routine exported by the Ada DLL must be invoked by the clients of the DLL
24822 to initialize the DLL.
24825 When useful, the DLL should also export a finalization routine which calls
24826 routine @code{adafinal} generated by @code{gnatbind} to perform the
24827 finalization of the Ada code in the DLL (@ref{205,,Ada DLLs and Finalization}).
24828 The finalization routine exported by the Ada DLL must be invoked by the
24829 clients of the DLL when the DLL services are no further needed.
24832 You must provide a spec for the services exported by the Ada DLL in each
24833 of the programming languages to which you plan to make the DLL available.
24836 You must provide a definition file listing the exported entities
24837 (@ref{1f4,,The Definition File}).
24840 Finally you must use @code{gnatdll} to produce the DLL and the import
24841 library (@ref{1fc,,Using gnatdll}).
24844 Note that a relocatable DLL stripped using the @code{strip}
24845 binutils tool will not be relocatable anymore. To build a DLL without
24846 debug information pass @code{-largs -s} to @code{gnatdll}. This
24847 restriction does not apply to a DLL built using a Library Project.
24848 See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24849 chapter of the @emph{GPRbuild User's Guide}.
24851 @c Limitations_When_Using_Ada_DLLs_from Ada:
24854 * Limitations When Using Ada DLLs from Ada::
24855 * Exporting Ada Entities::
24856 * Ada DLLs and Elaboration::
24860 @node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
24861 @anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{206}
24862 @subsubsection Limitations When Using Ada DLLs from Ada
24865 When using Ada DLLs from Ada applications there is a limitation users
24866 should be aware of. Because on Windows the GNAT run-time is not in a DLL of
24867 its own, each Ada DLL includes a part of the GNAT run-time. Specifically,
24868 each Ada DLL includes the services of the GNAT run-time that are necessary
24869 to the Ada code inside the DLL. As a result, when an Ada program uses an
24870 Ada DLL there are two independent GNAT run-times: one in the Ada DLL and
24871 one in the main program.
24873 It is therefore not possible to exchange GNAT run-time objects between the
24874 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
24875 handles (e.g., @code{Text_IO.File_Type}), tasks types, protected objects
24878 It is completely safe to exchange plain elementary, array or record types,
24879 Windows object handles, etc.
24881 @node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
24882 @anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{203}@anchor{gnat_ugn/platform_specific_information id24}@anchor{207}
24883 @subsubsection Exporting Ada Entities
24886 @geindex Export table
24888 Building a DLL is a way to encapsulate a set of services usable from any
24889 application. As a result, the Ada entities exported by a DLL should be
24890 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
24891 any Ada name mangling. As an example here is an Ada package
24892 @code{API}, spec and body, exporting two procedures, a function, and a
24898 with Interfaces.C; use Interfaces;
24900 Count : C.int := 0;
24901 function Factorial (Val : C.int) return C.int;
24903 procedure Initialize_API;
24904 procedure Finalize_API;
24905 -- Initialization & Finalization routines. More in the next section.
24907 pragma Export (C, Initialize_API);
24908 pragma Export (C, Finalize_API);
24909 pragma Export (C, Count);
24910 pragma Export (C, Factorial);
24915 package body API is
24916 function Factorial (Val : C.int) return C.int is
24919 Count := Count + 1;
24920 for K in 1 .. Val loop
24926 procedure Initialize_API is
24928 pragma Import (C, Adainit);
24931 end Initialize_API;
24933 procedure Finalize_API is
24934 procedure Adafinal;
24935 pragma Import (C, Adafinal);
24943 If the Ada DLL you are building will only be used by Ada applications
24944 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
24945 convention. As an example, the previous package could be written as
24952 Count : Integer := 0;
24953 function Factorial (Val : Integer) return Integer;
24955 procedure Initialize_API;
24956 procedure Finalize_API;
24957 -- Initialization and Finalization routines.
24962 package body API is
24963 function Factorial (Val : Integer) return Integer is
24964 Fact : Integer := 1;
24966 Count := Count + 1;
24967 for K in 1 .. Val loop
24974 -- The remainder of this package body is unchanged.
24979 Note that if you do not export the Ada entities with a @code{C} or
24980 @code{Stdcall} convention you will have to provide the mangled Ada names
24981 in the definition file of the Ada DLL
24982 (@ref{208,,Creating the Definition File}).
24984 @node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
24985 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{204}@anchor{gnat_ugn/platform_specific_information id25}@anchor{209}
24986 @subsubsection Ada DLLs and Elaboration
24989 @geindex DLLs and elaboration
24991 The DLL that you are building contains your Ada code as well as all the
24992 routines in the Ada library that are needed by it. The first thing a
24993 user of your DLL must do is elaborate the Ada code
24994 (@ref{f,,Elaboration Order Handling in GNAT}).
24996 To achieve this you must export an initialization routine
24997 (@code{Initialize_API} in the previous example), which must be invoked
24998 before using any of the DLL services. This elaboration routine must call
24999 the Ada elaboration routine @code{adainit} generated by the GNAT binder
25000 (@ref{b4,,Binding with Non-Ada Main Programs}). See the body of
25001 @code{Initialize_Api} for an example. Note that the GNAT binder is
25002 automatically invoked during the DLL build process by the @code{gnatdll}
25003 tool (@ref{1fc,,Using gnatdll}).
25005 When a DLL is loaded, Windows systematically invokes a routine called
25006 @code{DllMain}. It would therefore be possible to call @code{adainit}
25007 directly from @code{DllMain} without having to provide an explicit
25008 initialization routine. Unfortunately, it is not possible to call
25009 @code{adainit} from the @code{DllMain} if your program has library level
25010 tasks because access to the @code{DllMain} entry point is serialized by
25011 the system (that is, only a single thread can execute 'through' it at a
25012 time), which means that the GNAT run-time will deadlock waiting for the
25013 newly created task to complete its initialization.
25015 @node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
25016 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{205}@anchor{gnat_ugn/platform_specific_information id26}@anchor{20a}
25017 @subsubsection Ada DLLs and Finalization
25020 @geindex DLLs and finalization
25022 When the services of an Ada DLL are no longer needed, the client code should
25023 invoke the DLL finalization routine, if available. The DLL finalization
25024 routine is in charge of releasing all resources acquired by the DLL. In the
25025 case of the Ada code contained in the DLL, this is achieved by calling
25026 routine @code{adafinal} generated by the GNAT binder
25027 (@ref{b4,,Binding with Non-Ada Main Programs}).
25028 See the body of @code{Finalize_Api} for an
25029 example. As already pointed out the GNAT binder is automatically invoked
25030 during the DLL build process by the @code{gnatdll} tool
25031 (@ref{1fc,,Using gnatdll}).
25033 @node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
25034 @anchor{gnat_ugn/platform_specific_information id27}@anchor{20b}@anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{20c}
25035 @subsubsection Creating a Spec for Ada DLLs
25038 To use the services exported by the Ada DLL from another programming
25039 language (e.g., C), you have to translate the specs of the exported Ada
25040 entities in that language. For instance in the case of @code{API.dll},
25041 the corresponding C header file could look like:
25046 extern int *_imp__count;
25047 #define count (*_imp__count)
25048 int factorial (int);
25052 It is important to understand that when building an Ada DLL to be used by
25053 other Ada applications, you need two different specs for the packages
25054 contained in the DLL: one for building the DLL and the other for using
25055 the DLL. This is because the @code{DLL} calling convention is needed to
25056 use a variable defined in a DLL, but when building the DLL, the variable
25057 must have either the @code{Ada} or @code{C} calling convention. As an
25058 example consider a DLL comprising the following package @code{API}:
25064 Count : Integer := 0;
25066 -- Remainder of the package omitted.
25071 After producing a DLL containing package @code{API}, the spec that
25072 must be used to import @code{API.Count} from Ada code outside of the
25080 pragma Import (DLL, Count);
25086 * Creating the Definition File::
25091 @node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
25092 @anchor{gnat_ugn/platform_specific_information id28}@anchor{20d}@anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{208}
25093 @subsubsection Creating the Definition File
25096 The definition file is the last file needed to build the DLL. It lists
25097 the exported symbols. As an example, the definition file for a DLL
25098 containing only package @code{API} (where all the entities are exported
25099 with a @code{C} calling convention) is:
25112 If the @code{C} calling convention is missing from package @code{API},
25113 then the definition file contains the mangled Ada names of the above
25114 entities, which in this case are:
25123 api__initialize_api
25127 @node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
25128 @anchor{gnat_ugn/platform_specific_information id29}@anchor{20e}@anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{1fc}
25129 @subsubsection Using @code{gnatdll}
25134 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
25135 and non-Ada sources that make up your DLL have been compiled.
25136 @code{gnatdll} is actually in charge of two distinct tasks: build the
25137 static import library for the DLL and the actual DLL. The form of the
25138 @code{gnatdll} command is
25143 $ gnatdll [ switches ] list-of-files [ -largs opts ]
25147 where @code{list-of-files} is a list of ALI and object files. The object
25148 file list must be the exact list of objects corresponding to the non-Ada
25149 sources whose services are to be included in the DLL. The ALI file list
25150 must be the exact list of ALI files for the corresponding Ada sources
25151 whose services are to be included in the DLL. If @code{list-of-files} is
25152 missing, only the static import library is generated.
25154 You may specify any of the following switches to @code{gnatdll}:
25158 @geindex -a (gnatdll)
25164 @item @code{-a[@emph{address}]}
25166 Build a non-relocatable DLL at @code{address}. If @code{address} is not
25167 specified the default address @code{0x11000000} will be used. By default,
25168 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
25169 advise the reader to build relocatable DLL.
25171 @geindex -b (gnatdll)
25173 @item @code{-b @emph{address}}
25175 Set the relocatable DLL base address. By default the address is
25178 @geindex -bargs (gnatdll)
25180 @item @code{-bargs @emph{opts}}
25182 Binder options. Pass @code{opts} to the binder.
25184 @geindex -d (gnatdll)
25186 @item @code{-d @emph{dllfile}}
25188 @code{dllfile} is the name of the DLL. This switch must be present for
25189 @code{gnatdll} to do anything. The name of the generated import library is
25190 obtained algorithmically from @code{dllfile} as shown in the following
25191 example: if @code{dllfile} is @code{xyz.dll}, the import library name is
25192 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
25193 by option @code{-e}) is obtained algorithmically from @code{dllfile}
25194 as shown in the following example:
25195 if @code{dllfile} is @code{xyz.dll}, the definition
25196 file used is @code{xyz.def}.
25198 @geindex -e (gnatdll)
25200 @item @code{-e @emph{deffile}}
25202 @code{deffile} is the name of the definition file.
25204 @geindex -g (gnatdll)
25208 Generate debugging information. This information is stored in the object
25209 file and copied from there to the final DLL file by the linker,
25210 where it can be read by the debugger. You must use the
25211 @code{-g} switch if you plan on using the debugger or the symbolic
25214 @geindex -h (gnatdll)
25218 Help mode. Displays @code{gnatdll} switch usage information.
25220 @geindex -I (gnatdll)
25222 @item @code{-I@emph{dir}}
25224 Direct @code{gnatdll} to search the @code{dir} directory for source and
25225 object files needed to build the DLL.
25226 (@ref{89,,Search Paths and the Run-Time Library (RTL)}).
25228 @geindex -k (gnatdll)
25232 Removes the @code{@@@emph{nn}} suffix from the import library's exported
25233 names, but keeps them for the link names. You must specify this
25234 option if you want to use a @code{Stdcall} function in a DLL for which
25235 the @code{@@@emph{nn}} suffix has been removed. This is the case for most
25236 of the Windows NT DLL for example. This option has no effect when
25237 @code{-n} option is specified.
25239 @geindex -l (gnatdll)
25241 @item @code{-l @emph{file}}
25243 The list of ALI and object files used to build the DLL are listed in
25244 @code{file}, instead of being given in the command line. Each line in
25245 @code{file} contains the name of an ALI or object file.
25247 @geindex -n (gnatdll)
25251 No Import. Do not create the import library.
25253 @geindex -q (gnatdll)
25257 Quiet mode. Do not display unnecessary messages.
25259 @geindex -v (gnatdll)
25263 Verbose mode. Display extra information.
25265 @geindex -largs (gnatdll)
25267 @item @code{-largs @emph{opts}}
25269 Linker options. Pass @code{opts} to the linker.
25272 @subsubheading @code{gnatdll} Example
25275 As an example the command to build a relocatable DLL from @code{api.adb}
25276 once @code{api.adb} has been compiled and @code{api.def} created is
25281 $ gnatdll -d api.dll api.ali
25285 The above command creates two files: @code{libapi.dll.a} (the import
25286 library) and @code{api.dll} (the actual DLL). If you want to create
25287 only the DLL, just type:
25292 $ gnatdll -d api.dll -n api.ali
25296 Alternatively if you want to create just the import library, type:
25301 $ gnatdll -d api.dll
25305 @subsubheading @code{gnatdll} behind the Scenes
25308 This section details the steps involved in creating a DLL. @code{gnatdll}
25309 does these steps for you. Unless you are interested in understanding what
25310 goes on behind the scenes, you should skip this section.
25312 We use the previous example of a DLL containing the Ada package @code{API},
25313 to illustrate the steps necessary to build a DLL. The starting point is a
25314 set of objects that will make up the DLL and the corresponding ALI
25315 files. In the case of this example this means that @code{api.o} and
25316 @code{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
25323 @code{gnatdll} builds the base file (@code{api.base}). A base file gives
25324 the information necessary to generate relocation information for the
25329 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
25332 In addition to the base file, the @code{gnatlink} command generates an
25333 output file @code{api.jnk} which can be discarded. The @code{-mdll} switch
25334 asks @code{gnatlink} to generate the routines @code{DllMain} and
25335 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
25336 is loaded into memory.
25339 @code{gnatdll} uses @code{dlltool} (see @ref{20f,,Using dlltool}) to build the
25340 export table (@code{api.exp}). The export table contains the relocation
25341 information in a form which can be used during the final link to ensure
25342 that the Windows loader is able to place the DLL anywhere in memory.
25345 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
25346 --output-exp api.exp
25350 @code{gnatdll} builds the base file using the new export table. Note that
25351 @code{gnatbind} must be called once again since the binder generated file
25352 has been deleted during the previous call to @code{gnatlink}.
25356 $ gnatlink api -o api.jnk api.exp -mdll
25357 -Wl,--base-file,api.base
25361 @code{gnatdll} builds the new export table using the new base file and
25362 generates the DLL import library @code{libAPI.dll.a}.
25365 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
25366 --output-exp api.exp --output-lib libAPI.a
25370 Finally @code{gnatdll} builds the relocatable DLL using the final export
25375 $ gnatlink api api.exp -o api.dll -mdll
25378 @anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{20f}
25379 @subsubheading Using @code{dlltool}
25382 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
25383 DLLs and static import libraries. This section summarizes the most
25384 common @code{dlltool} switches. The form of the @code{dlltool} command
25390 $ dlltool [`switches`]
25394 @code{dlltool} switches include:
25396 @geindex --base-file (dlltool)
25401 @item @code{--base-file @emph{basefile}}
25403 Read the base file @code{basefile} generated by the linker. This switch
25404 is used to create a relocatable DLL.
25407 @geindex --def (dlltool)
25412 @item @code{--def @emph{deffile}}
25414 Read the definition file.
25417 @geindex --dllname (dlltool)
25422 @item @code{--dllname @emph{name}}
25424 Gives the name of the DLL. This switch is used to embed the name of the
25425 DLL in the static import library generated by @code{dlltool} with switch
25426 @code{--output-lib}.
25429 @geindex -k (dlltool)
25436 Kill @code{@@@emph{nn}} from exported names
25437 (@ref{1e8,,Windows Calling Conventions}
25438 for a discussion about @code{Stdcall}-style symbols.
25441 @geindex --help (dlltool)
25446 @item @code{--help}
25448 Prints the @code{dlltool} switches with a concise description.
25451 @geindex --output-exp (dlltool)
25456 @item @code{--output-exp @emph{exportfile}}
25458 Generate an export file @code{exportfile}. The export file contains the
25459 export table (list of symbols in the DLL) and is used to create the DLL.
25462 @geindex --output-lib (dlltool)
25467 @item @code{--output-lib @emph{libfile}}
25469 Generate a static import library @code{libfile}.
25472 @geindex -v (dlltool)
25482 @geindex --as (dlltool)
25487 @item @code{--as @emph{assembler-name}}
25489 Use @code{assembler-name} as the assembler. The default is @code{as}.
25492 @node GNAT and Windows Resources,Using GNAT DLLs from Microsoft Visual Studio Applications,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
25493 @anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{210}@anchor{gnat_ugn/platform_specific_information id30}@anchor{211}
25494 @subsubsection GNAT and Windows Resources
25500 Resources are an easy way to add Windows specific objects to your
25501 application. The objects that can be added as resources include:
25531 version information
25534 For example, a version information resource can be defined as follow and
25535 embedded into an executable or DLL:
25537 A version information resource can be used to embed information into an
25538 executable or a DLL. These information can be viewed using the file properties
25539 from the Windows Explorer. Here is an example of a version information
25546 FILEVERSION 1,0,0,0
25547 PRODUCTVERSION 1,0,0,0
25549 BLOCK "StringFileInfo"
25553 VALUE "CompanyName", "My Company Name"
25554 VALUE "FileDescription", "My application"
25555 VALUE "FileVersion", "1.0"
25556 VALUE "InternalName", "my_app"
25557 VALUE "LegalCopyright", "My Name"
25558 VALUE "OriginalFilename", "my_app.exe"
25559 VALUE "ProductName", "My App"
25560 VALUE "ProductVersion", "1.0"
25564 BLOCK "VarFileInfo"
25566 VALUE "Translation", 0x809, 1252
25572 The value @code{0809} (langID) is for the U.K English language and
25573 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
25576 This section explains how to build, compile and use resources. Note that this
25577 section does not cover all resource objects, for a complete description see
25578 the corresponding Microsoft documentation.
25581 * Building Resources::
25582 * Compiling Resources::
25583 * Using Resources::
25587 @node Building Resources,Compiling Resources,,GNAT and Windows Resources
25588 @anchor{gnat_ugn/platform_specific_information building-resources}@anchor{212}@anchor{gnat_ugn/platform_specific_information id31}@anchor{213}
25589 @subsubsection Building Resources
25595 A resource file is an ASCII file. By convention resource files have an
25596 @code{.rc} extension.
25597 The easiest way to build a resource file is to use Microsoft tools
25598 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
25599 @code{dlgedit.exe} to build dialogs.
25600 It is always possible to build an @code{.rc} file yourself by writing a
25603 It is not our objective to explain how to write a resource file. A
25604 complete description of the resource script language can be found in the
25605 Microsoft documentation.
25607 @node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
25608 @anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{214}@anchor{gnat_ugn/platform_specific_information id32}@anchor{215}
25609 @subsubsection Compiling Resources
25619 This section describes how to build a GNAT-compatible (COFF) object file
25620 containing the resources. This is done using the Resource Compiler
25621 @code{windres} as follows:
25626 $ windres -i myres.rc -o myres.o
25630 By default @code{windres} will run @code{gcc} to preprocess the @code{.rc}
25631 file. You can specify an alternate preprocessor (usually named
25632 @code{cpp.exe}) using the @code{windres} @code{--preprocessor}
25633 parameter. A list of all possible options may be obtained by entering
25634 the command @code{windres} @code{--help}.
25636 It is also possible to use the Microsoft resource compiler @code{rc.exe}
25637 to produce a @code{.res} file (binary resource file). See the
25638 corresponding Microsoft documentation for further details. In this case
25639 you need to use @code{windres} to translate the @code{.res} file to a
25640 GNAT-compatible object file as follows:
25645 $ windres -i myres.res -o myres.o
25649 @node Using Resources,,Compiling Resources,GNAT and Windows Resources
25650 @anchor{gnat_ugn/platform_specific_information using-resources}@anchor{216}@anchor{gnat_ugn/platform_specific_information id33}@anchor{217}
25651 @subsubsection Using Resources
25657 To include the resource file in your program just add the
25658 GNAT-compatible object file for the resource(s) to the linker
25659 arguments. With @code{gnatmake} this is done by using the @code{-largs}
25665 $ gnatmake myprog -largs myres.o
25669 @node Using GNAT DLLs from Microsoft Visual Studio Applications,Debugging a DLL,GNAT and Windows Resources,Mixed-Language Programming on Windows
25670 @anchor{gnat_ugn/platform_specific_information using-gnat-dll-from-msvs}@anchor{218}@anchor{gnat_ugn/platform_specific_information using-gnat-dlls-from-microsoft-visual-studio-applications}@anchor{219}
25671 @subsubsection Using GNAT DLLs from Microsoft Visual Studio Applications
25674 @geindex Microsoft Visual Studio
25675 @geindex use with GNAT DLLs
25677 This section describes a common case of mixed GNAT/Microsoft Visual Studio
25678 application development, where the main program is developed using MSVS, and
25679 is linked with a DLL developed using GNAT. Such a mixed application should
25680 be developed following the general guidelines outlined above; below is the
25681 cookbook-style sequence of steps to follow:
25687 First develop and build the GNAT shared library using a library project
25688 (let's assume the project is @code{mylib.gpr}, producing the library @code{libmylib.dll}):
25694 $ gprbuild -p mylib.gpr
25702 Produce a .def file for the symbols you need to interface with, either by
25703 hand or automatically with possibly some manual adjustments
25704 (see @ref{1fa,,Creating Definition File Automatically}):
25710 $ dlltool libmylib.dll -z libmylib.def --export-all-symbols
25718 Make sure that MSVS command-line tools are accessible on the path.
25721 Create the Microsoft-style import library (see @ref{1fd,,MSVS-Style Import Library}):
25727 $ lib -machine:IX86 -def:libmylib.def -out:libmylib.lib
25731 If you are using a 64-bit toolchain, the above becomes...
25736 $ lib -machine:X64 -def:libmylib.def -out:libmylib.lib
25750 $ cl /O2 /MD main.c libmylib.lib
25758 Before running the executable, make sure you have set the PATH to the DLL,
25759 or copy the DLL into into the directory containing the .exe.
25762 @node Debugging a DLL,Setting Stack Size from gnatlink,Using GNAT DLLs from Microsoft Visual Studio Applications,Mixed-Language Programming on Windows
25763 @anchor{gnat_ugn/platform_specific_information id34}@anchor{21a}@anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{21b}
25764 @subsubsection Debugging a DLL
25767 @geindex DLL debugging
25769 Debugging a DLL is similar to debugging a standard program. But
25770 we have to deal with two different executable parts: the DLL and the
25771 program that uses it. We have the following four possibilities:
25777 The program and the DLL are built with GCC/GNAT.
25780 The program is built with foreign tools and the DLL is built with
25784 The program is built with GCC/GNAT and the DLL is built with
25788 In this section we address only cases one and two above.
25789 There is no point in trying to debug
25790 a DLL with GNU/GDB, if there is no GDB-compatible debugging
25791 information in it. To do so you must use a debugger compatible with the
25792 tools suite used to build the DLL.
25795 * Program and DLL Both Built with GCC/GNAT::
25796 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
25800 @node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
25801 @anchor{gnat_ugn/platform_specific_information program-and-dll-both-built-with-gcc-gnat}@anchor{21c}@anchor{gnat_ugn/platform_specific_information id35}@anchor{21d}
25802 @subsubsection Program and DLL Both Built with GCC/GNAT
25805 This is the simplest case. Both the DLL and the program have @code{GDB}
25806 compatible debugging information. It is then possible to break anywhere in
25807 the process. Let's suppose here that the main procedure is named
25808 @code{ada_main} and that in the DLL there is an entry point named
25811 The DLL (@ref{1f2,,Introduction to Dynamic Link Libraries (DLLs)}) and
25812 program must have been built with the debugging information (see GNAT -g
25813 switch). Here are the step-by-step instructions for debugging it:
25819 Launch @code{GDB} on the main program.
25826 Start the program and stop at the beginning of the main procedure
25832 This step is required to be able to set a breakpoint inside the DLL. As long
25833 as the program is not run, the DLL is not loaded. This has the
25834 consequence that the DLL debugging information is also not loaded, so it is not
25835 possible to set a breakpoint in the DLL.
25838 Set a breakpoint inside the DLL
25841 (gdb) break ada_dll
25846 At this stage a breakpoint is set inside the DLL. From there on
25847 you can use the standard approach to debug the whole program
25848 (@ref{24,,Running and Debugging Ada Programs}).
25850 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
25851 @anchor{gnat_ugn/platform_specific_information id36}@anchor{21e}@anchor{gnat_ugn/platform_specific_information program-built-with-foreign-tools-and-dll-built-with-gcc-gnat}@anchor{21f}
25852 @subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
25855 In this case things are slightly more complex because it is not possible to
25856 start the main program and then break at the beginning to load the DLL and the
25857 associated DLL debugging information. It is not possible to break at the
25858 beginning of the program because there is no @code{GDB} debugging information,
25859 and therefore there is no direct way of getting initial control. This
25860 section addresses this issue by describing some methods that can be used
25861 to break somewhere in the DLL to debug it.
25863 First suppose that the main procedure is named @code{main} (this is for
25864 example some C code built with Microsoft Visual C) and that there is a
25865 DLL named @code{test.dll} containing an Ada entry point named
25868 The DLL (see @ref{1f2,,Introduction to Dynamic Link Libraries (DLLs)}) must have
25869 been built with debugging information (see the GNAT @code{-g} option).
25871 @subsubheading Debugging the DLL Directly
25878 Find out the executable starting address
25881 $ objdump --file-header main.exe
25884 The starting address is reported on the last line. For example:
25887 main.exe: file format pei-i386
25888 architecture: i386, flags 0x0000010a:
25889 EXEC_P, HAS_DEBUG, D_PAGED
25890 start address 0x00401010
25894 Launch the debugger on the executable.
25901 Set a breakpoint at the starting address, and launch the program.
25904 $ (gdb) break *0x00401010
25908 The program will stop at the given address.
25911 Set a breakpoint on a DLL subroutine.
25914 (gdb) break ada_dll.adb:45
25917 Or if you want to break using a symbol on the DLL, you need first to
25918 select the Ada language (language used by the DLL).
25921 (gdb) set language ada
25922 (gdb) break ada_dll
25926 Continue the program.
25932 This will run the program until it reaches the breakpoint that has been
25933 set. From that point you can use the standard way to debug a program
25934 as described in (@ref{24,,Running and Debugging Ada Programs}).
25937 It is also possible to debug the DLL by attaching to a running process.
25939 @subsubheading Attaching to a Running Process
25942 @geindex DLL debugging
25943 @geindex attach to process
25945 With @code{GDB} it is always possible to debug a running process by
25946 attaching to it. It is possible to debug a DLL this way. The limitation
25947 of this approach is that the DLL must run long enough to perform the
25948 attach operation. It may be useful for instance to insert a time wasting
25949 loop in the code of the DLL to meet this criterion.
25955 Launch the main program @code{main.exe}.
25962 Use the Windows @emph{Task Manager} to find the process ID. Let's say
25963 that the process PID for @code{main.exe} is 208.
25973 Attach to the running process to be debugged.
25980 Load the process debugging information.
25983 (gdb) symbol-file main.exe
25987 Break somewhere in the DLL.
25990 (gdb) break ada_dll
25994 Continue process execution.
26001 This last step will resume the process execution, and stop at
26002 the breakpoint we have set. From there you can use the standard
26003 approach to debug a program as described in
26004 @ref{24,,Running and Debugging Ada Programs}.
26006 @node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
26007 @anchor{gnat_ugn/platform_specific_information id37}@anchor{220}@anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{136}
26008 @subsubsection Setting Stack Size from @code{gnatlink}
26011 It is possible to specify the program stack size at link time. On modern
26012 versions of Windows, starting with XP, this is mostly useful to set the size of
26013 the main stack (environment task). The other task stacks are set with pragma
26014 Storage_Size or with the @emph{gnatbind -d} command.
26016 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
26017 reserve size of individual tasks, the link-time stack size applies to all
26018 tasks, and pragma Storage_Size has no effect.
26019 In particular, Stack Overflow checks are made against this
26020 link-time specified size.
26022 This setting can be done with @code{gnatlink} using either of the following:
26028 @code{-Xlinker} linker option
26031 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
26034 This sets the stack reserve size to 0x10000 bytes and the stack commit
26035 size to 0x1000 bytes.
26038 @code{-Wl} linker option
26041 $ gnatlink hello -Wl,--stack=0x1000000
26044 This sets the stack reserve size to 0x1000000 bytes. Note that with
26045 @code{-Wl} option it is not possible to set the stack commit size
26046 because the comma is a separator for this option.
26049 @node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
26050 @anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{137}@anchor{gnat_ugn/platform_specific_information id38}@anchor{221}
26051 @subsubsection Setting Heap Size from @code{gnatlink}
26054 Under Windows systems, it is possible to specify the program heap size from
26055 @code{gnatlink} using either of the following:
26061 @code{-Xlinker} linker option
26064 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
26067 This sets the heap reserve size to 0x10000 bytes and the heap commit
26068 size to 0x1000 bytes.
26071 @code{-Wl} linker option
26074 $ gnatlink hello -Wl,--heap=0x1000000
26077 This sets the heap reserve size to 0x1000000 bytes. Note that with
26078 @code{-Wl} option it is not possible to set the heap commit size
26079 because the comma is a separator for this option.
26082 @node Windows Specific Add-Ons,,Mixed-Language Programming on Windows,Microsoft Windows Topics
26083 @anchor{gnat_ugn/platform_specific_information windows-specific-add-ons}@anchor{222}@anchor{gnat_ugn/platform_specific_information win32-specific-addons}@anchor{223}
26084 @subsection Windows Specific Add-Ons
26087 This section describes the Windows specific add-ons.
26095 @node Win32Ada,wPOSIX,,Windows Specific Add-Ons
26096 @anchor{gnat_ugn/platform_specific_information win32ada}@anchor{224}@anchor{gnat_ugn/platform_specific_information id39}@anchor{225}
26097 @subsubsection Win32Ada
26100 Win32Ada is a binding for the Microsoft Win32 API. This binding can be
26101 easily installed from the provided installer. To use the Win32Ada
26102 binding you need to use a project file, and adding a single with_clause
26103 will give you full access to the Win32Ada binding sources and ensure
26104 that the proper libraries are passed to the linker.
26111 for Sources use ...;
26116 To build the application you just need to call gprbuild for the
26117 application's project, here p.gpr:
26126 @node wPOSIX,,Win32Ada,Windows Specific Add-Ons
26127 @anchor{gnat_ugn/platform_specific_information wposix}@anchor{226}@anchor{gnat_ugn/platform_specific_information id40}@anchor{227}
26128 @subsubsection wPOSIX
26131 wPOSIX is a minimal POSIX binding whose goal is to help with building
26132 cross-platforms applications. This binding is not complete though, as
26133 the Win32 API does not provide the necessary support for all POSIX APIs.
26135 To use the wPOSIX binding you need to use a project file, and adding
26136 a single with_clause will give you full access to the wPOSIX binding
26137 sources and ensure that the proper libraries are passed to the linker.
26144 for Sources use ...;
26149 To build the application you just need to call gprbuild for the
26150 application's project, here p.gpr:
26159 @node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
26160 @anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{2d}@anchor{gnat_ugn/platform_specific_information id41}@anchor{228}
26161 @section Mac OS Topics
26166 This section describes topics that are specific to Apple's OS X
26170 * Codesigning the Debugger::
26174 @node Codesigning the Debugger,,,Mac OS Topics
26175 @anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{229}
26176 @subsection Codesigning the Debugger
26179 The Darwin Kernel requires the debugger to have special permissions
26180 before it is allowed to control other processes. These permissions
26181 are granted by codesigning the GDB executable. Without these
26182 permissions, the debugger will report error messages such as:
26185 Starting program: /x/y/foo
26186 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
26187 (please check gdb is codesigned - see taskgated(8))
26190 Codesigning requires a certificate. The following procedure explains
26197 Start the Keychain Access application (in
26198 /Applications/Utilities/Keychain Access.app)
26201 Select the Keychain Access -> Certificate Assistant ->
26202 Create a Certificate... menu
26211 Choose a name for the new certificate (this procedure will use
26212 "gdb-cert" as an example)
26215 Set "Identity Type" to "Self Signed Root"
26218 Set "Certificate Type" to "Code Signing"
26221 Activate the "Let me override defaults" option
26225 Click several times on "Continue" until the "Specify a Location
26226 For The Certificate" screen appears, then set "Keychain" to "System"
26229 Click on "Continue" until the certificate is created
26232 Finally, in the view, double-click on the new certificate,
26233 and set "When using this certificate" to "Always Trust"
26236 Exit the Keychain Access application and restart the computer
26237 (this is unfortunately required)
26240 Once a certificate has been created, the debugger can be codesigned
26241 as follow. In a Terminal, run the following command:
26246 $ codesign -f -s "gdb-cert" <gnat_install_prefix>/bin/gdb
26250 where "gdb-cert" should be replaced by the actual certificate
26251 name chosen above, and <gnat_install_prefix> should be replaced by
26252 the location where you installed GNAT. Also, be sure that users are
26253 in the Unix group @code{_developer}.
26255 @node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
26256 @anchor{gnat_ugn/example_of_binder_output example-of-binder-output-file}@anchor{e}@anchor{gnat_ugn/example_of_binder_output doc}@anchor{22a}@anchor{gnat_ugn/example_of_binder_output id1}@anchor{22b}
26257 @chapter Example of Binder Output File
26260 @geindex Binder output (example)
26262 This Appendix displays the source code for the output file
26263 generated by @emph{gnatbind} for a simple 'Hello World' program.
26264 Comments have been added for clarification purposes.
26267 -- The package is called Ada_Main unless this name is actually used
26268 -- as a unit name in the partition, in which case some other unique
26273 package ada_main is
26274 pragma Warnings (Off);
26276 -- The main program saves the parameters (argument count,
26277 -- argument values, environment pointer) in global variables
26278 -- for later access by other units including
26279 -- Ada.Command_Line.
26281 gnat_argc : Integer;
26282 gnat_argv : System.Address;
26283 gnat_envp : System.Address;
26285 -- The actual variables are stored in a library routine. This
26286 -- is useful for some shared library situations, where there
26287 -- are problems if variables are not in the library.
26289 pragma Import (C, gnat_argc);
26290 pragma Import (C, gnat_argv);
26291 pragma Import (C, gnat_envp);
26293 -- The exit status is similarly an external location
26295 gnat_exit_status : Integer;
26296 pragma Import (C, gnat_exit_status);
26298 GNAT_Version : constant String :=
26299 "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
26300 pragma Export (C, GNAT_Version, "__gnat_version");
26302 Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
26303 pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
26305 -- This is the generated adainit routine that performs
26306 -- initialization at the start of execution. In the case
26307 -- where Ada is the main program, this main program makes
26308 -- a call to adainit at program startup.
26311 pragma Export (C, adainit, "adainit");
26313 -- This is the generated adafinal routine that performs
26314 -- finalization at the end of execution. In the case where
26315 -- Ada is the main program, this main program makes a call
26316 -- to adafinal at program termination.
26318 procedure adafinal;
26319 pragma Export (C, adafinal, "adafinal");
26321 -- This routine is called at the start of execution. It is
26322 -- a dummy routine that is used by the debugger to breakpoint
26323 -- at the start of execution.
26325 -- This is the actual generated main program (it would be
26326 -- suppressed if the no main program switch were used). As
26327 -- required by standard system conventions, this program has
26328 -- the external name main.
26332 argv : System.Address;
26333 envp : System.Address)
26335 pragma Export (C, main, "main");
26337 -- The following set of constants give the version
26338 -- identification values for every unit in the bound
26339 -- partition. This identification is computed from all
26340 -- dependent semantic units, and corresponds to the
26341 -- string that would be returned by use of the
26342 -- Body_Version or Version attributes.
26344 -- The following Export pragmas export the version numbers
26345 -- with symbolic names ending in B (for body) or S
26346 -- (for spec) so that they can be located in a link. The
26347 -- information provided here is sufficient to track down
26348 -- the exact versions of units used in a given build.
26350 type Version_32 is mod 2 ** 32;
26351 u00001 : constant Version_32 := 16#8ad6e54a#;
26352 pragma Export (C, u00001, "helloB");
26353 u00002 : constant Version_32 := 16#fbff4c67#;
26354 pragma Export (C, u00002, "system__standard_libraryB");
26355 u00003 : constant Version_32 := 16#1ec6fd90#;
26356 pragma Export (C, u00003, "system__standard_libraryS");
26357 u00004 : constant Version_32 := 16#3ffc8e18#;
26358 pragma Export (C, u00004, "adaS");
26359 u00005 : constant Version_32 := 16#28f088c2#;
26360 pragma Export (C, u00005, "ada__text_ioB");
26361 u00006 : constant Version_32 := 16#f372c8ac#;
26362 pragma Export (C, u00006, "ada__text_ioS");
26363 u00007 : constant Version_32 := 16#2c143749#;
26364 pragma Export (C, u00007, "ada__exceptionsB");
26365 u00008 : constant Version_32 := 16#f4f0cce8#;
26366 pragma Export (C, u00008, "ada__exceptionsS");
26367 u00009 : constant Version_32 := 16#a46739c0#;
26368 pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
26369 u00010 : constant Version_32 := 16#3aac8c92#;
26370 pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
26371 u00011 : constant Version_32 := 16#1d274481#;
26372 pragma Export (C, u00011, "systemS");
26373 u00012 : constant Version_32 := 16#a207fefe#;
26374 pragma Export (C, u00012, "system__soft_linksB");
26375 u00013 : constant Version_32 := 16#467d9556#;
26376 pragma Export (C, u00013, "system__soft_linksS");
26377 u00014 : constant Version_32 := 16#b01dad17#;
26378 pragma Export (C, u00014, "system__parametersB");
26379 u00015 : constant Version_32 := 16#630d49fe#;
26380 pragma Export (C, u00015, "system__parametersS");
26381 u00016 : constant Version_32 := 16#b19b6653#;
26382 pragma Export (C, u00016, "system__secondary_stackB");
26383 u00017 : constant Version_32 := 16#b6468be8#;
26384 pragma Export (C, u00017, "system__secondary_stackS");
26385 u00018 : constant Version_32 := 16#39a03df9#;
26386 pragma Export (C, u00018, "system__storage_elementsB");
26387 u00019 : constant Version_32 := 16#30e40e85#;
26388 pragma Export (C, u00019, "system__storage_elementsS");
26389 u00020 : constant Version_32 := 16#41837d1e#;
26390 pragma Export (C, u00020, "system__stack_checkingB");
26391 u00021 : constant Version_32 := 16#93982f69#;
26392 pragma Export (C, u00021, "system__stack_checkingS");
26393 u00022 : constant Version_32 := 16#393398c1#;
26394 pragma Export (C, u00022, "system__exception_tableB");
26395 u00023 : constant Version_32 := 16#b33e2294#;
26396 pragma Export (C, u00023, "system__exception_tableS");
26397 u00024 : constant Version_32 := 16#ce4af020#;
26398 pragma Export (C, u00024, "system__exceptionsB");
26399 u00025 : constant Version_32 := 16#75442977#;
26400 pragma Export (C, u00025, "system__exceptionsS");
26401 u00026 : constant Version_32 := 16#37d758f1#;
26402 pragma Export (C, u00026, "system__exceptions__machineS");
26403 u00027 : constant Version_32 := 16#b895431d#;
26404 pragma Export (C, u00027, "system__exceptions_debugB");
26405 u00028 : constant Version_32 := 16#aec55d3f#;
26406 pragma Export (C, u00028, "system__exceptions_debugS");
26407 u00029 : constant Version_32 := 16#570325c8#;
26408 pragma Export (C, u00029, "system__img_intB");
26409 u00030 : constant Version_32 := 16#1ffca443#;
26410 pragma Export (C, u00030, "system__img_intS");
26411 u00031 : constant Version_32 := 16#b98c3e16#;
26412 pragma Export (C, u00031, "system__tracebackB");
26413 u00032 : constant Version_32 := 16#831a9d5a#;
26414 pragma Export (C, u00032, "system__tracebackS");
26415 u00033 : constant Version_32 := 16#9ed49525#;
26416 pragma Export (C, u00033, "system__traceback_entriesB");
26417 u00034 : constant Version_32 := 16#1d7cb2f1#;
26418 pragma Export (C, u00034, "system__traceback_entriesS");
26419 u00035 : constant Version_32 := 16#8c33a517#;
26420 pragma Export (C, u00035, "system__wch_conB");
26421 u00036 : constant Version_32 := 16#065a6653#;
26422 pragma Export (C, u00036, "system__wch_conS");
26423 u00037 : constant Version_32 := 16#9721e840#;
26424 pragma Export (C, u00037, "system__wch_stwB");
26425 u00038 : constant Version_32 := 16#2b4b4a52#;
26426 pragma Export (C, u00038, "system__wch_stwS");
26427 u00039 : constant Version_32 := 16#92b797cb#;
26428 pragma Export (C, u00039, "system__wch_cnvB");
26429 u00040 : constant Version_32 := 16#09eddca0#;
26430 pragma Export (C, u00040, "system__wch_cnvS");
26431 u00041 : constant Version_32 := 16#6033a23f#;
26432 pragma Export (C, u00041, "interfacesS");
26433 u00042 : constant Version_32 := 16#ece6fdb6#;
26434 pragma Export (C, u00042, "system__wch_jisB");
26435 u00043 : constant Version_32 := 16#899dc581#;
26436 pragma Export (C, u00043, "system__wch_jisS");
26437 u00044 : constant Version_32 := 16#10558b11#;
26438 pragma Export (C, u00044, "ada__streamsB");
26439 u00045 : constant Version_32 := 16#2e6701ab#;
26440 pragma Export (C, u00045, "ada__streamsS");
26441 u00046 : constant Version_32 := 16#db5c917c#;
26442 pragma Export (C, u00046, "ada__io_exceptionsS");
26443 u00047 : constant Version_32 := 16#12c8cd7d#;
26444 pragma Export (C, u00047, "ada__tagsB");
26445 u00048 : constant Version_32 := 16#ce72c228#;
26446 pragma Export (C, u00048, "ada__tagsS");
26447 u00049 : constant Version_32 := 16#c3335bfd#;
26448 pragma Export (C, u00049, "system__htableB");
26449 u00050 : constant Version_32 := 16#99e5f76b#;
26450 pragma Export (C, u00050, "system__htableS");
26451 u00051 : constant Version_32 := 16#089f5cd0#;
26452 pragma Export (C, u00051, "system__string_hashB");
26453 u00052 : constant Version_32 := 16#3bbb9c15#;
26454 pragma Export (C, u00052, "system__string_hashS");
26455 u00053 : constant Version_32 := 16#807fe041#;
26456 pragma Export (C, u00053, "system__unsigned_typesS");
26457 u00054 : constant Version_32 := 16#d27be59e#;
26458 pragma Export (C, u00054, "system__val_lluB");
26459 u00055 : constant Version_32 := 16#fa8db733#;
26460 pragma Export (C, u00055, "system__val_lluS");
26461 u00056 : constant Version_32 := 16#27b600b2#;
26462 pragma Export (C, u00056, "system__val_utilB");
26463 u00057 : constant Version_32 := 16#b187f27f#;
26464 pragma Export (C, u00057, "system__val_utilS");
26465 u00058 : constant Version_32 := 16#d1060688#;
26466 pragma Export (C, u00058, "system__case_utilB");
26467 u00059 : constant Version_32 := 16#392e2d56#;
26468 pragma Export (C, u00059, "system__case_utilS");
26469 u00060 : constant Version_32 := 16#84a27f0d#;
26470 pragma Export (C, u00060, "interfaces__c_streamsB");
26471 u00061 : constant Version_32 := 16#8bb5f2c0#;
26472 pragma Export (C, u00061, "interfaces__c_streamsS");
26473 u00062 : constant Version_32 := 16#6db6928f#;
26474 pragma Export (C, u00062, "system__crtlS");
26475 u00063 : constant Version_32 := 16#4e6a342b#;
26476 pragma Export (C, u00063, "system__file_ioB");
26477 u00064 : constant Version_32 := 16#ba56a5e4#;
26478 pragma Export (C, u00064, "system__file_ioS");
26479 u00065 : constant Version_32 := 16#b7ab275c#;
26480 pragma Export (C, u00065, "ada__finalizationB");
26481 u00066 : constant Version_32 := 16#19f764ca#;
26482 pragma Export (C, u00066, "ada__finalizationS");
26483 u00067 : constant Version_32 := 16#95817ed8#;
26484 pragma Export (C, u00067, "system__finalization_rootB");
26485 u00068 : constant Version_32 := 16#52d53711#;
26486 pragma Export (C, u00068, "system__finalization_rootS");
26487 u00069 : constant Version_32 := 16#769e25e6#;
26488 pragma Export (C, u00069, "interfaces__cB");
26489 u00070 : constant Version_32 := 16#4a38bedb#;
26490 pragma Export (C, u00070, "interfaces__cS");
26491 u00071 : constant Version_32 := 16#07e6ee66#;
26492 pragma Export (C, u00071, "system__os_libB");
26493 u00072 : constant Version_32 := 16#d7b69782#;
26494 pragma Export (C, u00072, "system__os_libS");
26495 u00073 : constant Version_32 := 16#1a817b8e#;
26496 pragma Export (C, u00073, "system__stringsB");
26497 u00074 : constant Version_32 := 16#639855e7#;
26498 pragma Export (C, u00074, "system__stringsS");
26499 u00075 : constant Version_32 := 16#e0b8de29#;
26500 pragma Export (C, u00075, "system__file_control_blockS");
26501 u00076 : constant Version_32 := 16#b5b2aca1#;
26502 pragma Export (C, u00076, "system__finalization_mastersB");
26503 u00077 : constant Version_32 := 16#69316dc1#;
26504 pragma Export (C, u00077, "system__finalization_mastersS");
26505 u00078 : constant Version_32 := 16#57a37a42#;
26506 pragma Export (C, u00078, "system__address_imageB");
26507 u00079 : constant Version_32 := 16#bccbd9bb#;
26508 pragma Export (C, u00079, "system__address_imageS");
26509 u00080 : constant Version_32 := 16#7268f812#;
26510 pragma Export (C, u00080, "system__img_boolB");
26511 u00081 : constant Version_32 := 16#e8fe356a#;
26512 pragma Export (C, u00081, "system__img_boolS");
26513 u00082 : constant Version_32 := 16#d7aac20c#;
26514 pragma Export (C, u00082, "system__ioB");
26515 u00083 : constant Version_32 := 16#8365b3ce#;
26516 pragma Export (C, u00083, "system__ioS");
26517 u00084 : constant Version_32 := 16#6d4d969a#;
26518 pragma Export (C, u00084, "system__storage_poolsB");
26519 u00085 : constant Version_32 := 16#e87cc305#;
26520 pragma Export (C, u00085, "system__storage_poolsS");
26521 u00086 : constant Version_32 := 16#e34550ca#;
26522 pragma Export (C, u00086, "system__pool_globalB");
26523 u00087 : constant Version_32 := 16#c88d2d16#;
26524 pragma Export (C, u00087, "system__pool_globalS");
26525 u00088 : constant Version_32 := 16#9d39c675#;
26526 pragma Export (C, u00088, "system__memoryB");
26527 u00089 : constant Version_32 := 16#445a22b5#;
26528 pragma Export (C, u00089, "system__memoryS");
26529 u00090 : constant Version_32 := 16#6a859064#;
26530 pragma Export (C, u00090, "system__storage_pools__subpoolsB");
26531 u00091 : constant Version_32 := 16#e3b008dc#;
26532 pragma Export (C, u00091, "system__storage_pools__subpoolsS");
26533 u00092 : constant Version_32 := 16#63f11652#;
26534 pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
26535 u00093 : constant Version_32 := 16#fe2f4b3a#;
26536 pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
26538 -- BEGIN ELABORATION ORDER
26542 -- system.case_util%s
26543 -- system.case_util%b
26545 -- system.img_bool%s
26546 -- system.img_bool%b
26547 -- system.img_int%s
26548 -- system.img_int%b
26551 -- system.parameters%s
26552 -- system.parameters%b
26554 -- interfaces.c_streams%s
26555 -- interfaces.c_streams%b
26556 -- system.standard_library%s
26557 -- system.exceptions_debug%s
26558 -- system.exceptions_debug%b
26559 -- system.storage_elements%s
26560 -- system.storage_elements%b
26561 -- system.stack_checking%s
26562 -- system.stack_checking%b
26563 -- system.string_hash%s
26564 -- system.string_hash%b
26566 -- system.strings%s
26567 -- system.strings%b
26569 -- system.traceback_entries%s
26570 -- system.traceback_entries%b
26571 -- ada.exceptions%s
26572 -- system.soft_links%s
26573 -- system.unsigned_types%s
26574 -- system.val_llu%s
26575 -- system.val_util%s
26576 -- system.val_util%b
26577 -- system.val_llu%b
26578 -- system.wch_con%s
26579 -- system.wch_con%b
26580 -- system.wch_cnv%s
26581 -- system.wch_jis%s
26582 -- system.wch_jis%b
26583 -- system.wch_cnv%b
26584 -- system.wch_stw%s
26585 -- system.wch_stw%b
26586 -- ada.exceptions.last_chance_handler%s
26587 -- ada.exceptions.last_chance_handler%b
26588 -- system.address_image%s
26589 -- system.exception_table%s
26590 -- system.exception_table%b
26591 -- ada.io_exceptions%s
26596 -- system.exceptions%s
26597 -- system.exceptions%b
26598 -- system.exceptions.machine%s
26599 -- system.finalization_root%s
26600 -- system.finalization_root%b
26601 -- ada.finalization%s
26602 -- ada.finalization%b
26603 -- system.storage_pools%s
26604 -- system.storage_pools%b
26605 -- system.finalization_masters%s
26606 -- system.storage_pools.subpools%s
26607 -- system.storage_pools.subpools.finalization%s
26608 -- system.storage_pools.subpools.finalization%b
26611 -- system.standard_library%b
26612 -- system.pool_global%s
26613 -- system.pool_global%b
26614 -- system.file_control_block%s
26615 -- system.file_io%s
26616 -- system.secondary_stack%s
26617 -- system.file_io%b
26618 -- system.storage_pools.subpools%b
26619 -- system.finalization_masters%b
26622 -- system.soft_links%b
26624 -- system.secondary_stack%b
26625 -- system.address_image%b
26626 -- system.traceback%s
26627 -- ada.exceptions%b
26628 -- system.traceback%b
26632 -- END ELABORATION ORDER
26639 -- The following source file name pragmas allow the generated file
26640 -- names to be unique for different main programs. They are needed
26641 -- since the package name will always be Ada_Main.
26643 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26644 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26646 pragma Suppress (Overflow_Check);
26647 with Ada.Exceptions;
26649 -- Generated package body for Ada_Main starts here
26651 package body ada_main is
26652 pragma Warnings (Off);
26654 -- These values are reference counter associated to units which have
26655 -- been elaborated. It is also used to avoid elaborating the
26656 -- same unit twice.
26658 E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
26659 E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
26660 E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
26661 E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
26662 E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
26663 E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
26664 E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
26665 E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
26666 E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
26667 E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
26668 E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
26669 E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
26670 E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
26671 E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
26672 E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
26673 E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
26674 E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
26675 E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
26677 Local_Priority_Specific_Dispatching : constant String := "";
26678 Local_Interrupt_States : constant String := "";
26680 Is_Elaborated : Boolean := False;
26682 procedure finalize_library is
26687 pragma Import (Ada, F1, "ada__text_io__finalize_spec");
26695 pragma Import (Ada, F2, "system__file_io__finalize_body");
26702 pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
26710 pragma Import (Ada, F4, "system__pool_global__finalize_spec");
26716 pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
26722 pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
26727 procedure Reraise_Library_Exception_If_Any;
26728 pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
26730 Reraise_Library_Exception_If_Any;
26732 end finalize_library;
26738 procedure adainit is
26740 Main_Priority : Integer;
26741 pragma Import (C, Main_Priority, "__gl_main_priority");
26742 Time_Slice_Value : Integer;
26743 pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
26744 WC_Encoding : Character;
26745 pragma Import (C, WC_Encoding, "__gl_wc_encoding");
26746 Locking_Policy : Character;
26747 pragma Import (C, Locking_Policy, "__gl_locking_policy");
26748 Queuing_Policy : Character;
26749 pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
26750 Task_Dispatching_Policy : Character;
26751 pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
26752 Priority_Specific_Dispatching : System.Address;
26753 pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
26754 Num_Specific_Dispatching : Integer;
26755 pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
26756 Main_CPU : Integer;
26757 pragma Import (C, Main_CPU, "__gl_main_cpu");
26758 Interrupt_States : System.Address;
26759 pragma Import (C, Interrupt_States, "__gl_interrupt_states");
26760 Num_Interrupt_States : Integer;
26761 pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
26762 Unreserve_All_Interrupts : Integer;
26763 pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
26764 Detect_Blocking : Integer;
26765 pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
26766 Default_Stack_Size : Integer;
26767 pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
26768 Leap_Seconds_Support : Integer;
26769 pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
26771 procedure Runtime_Initialize;
26772 pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
26774 Finalize_Library_Objects : No_Param_Proc;
26775 pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
26777 -- Start of processing for adainit
26781 -- Record various information for this partition. The values
26782 -- are derived by the binder from information stored in the ali
26783 -- files by the compiler.
26785 if Is_Elaborated then
26788 Is_Elaborated := True;
26789 Main_Priority := -1;
26790 Time_Slice_Value := -1;
26791 WC_Encoding := 'b';
26792 Locking_Policy := ' ';
26793 Queuing_Policy := ' ';
26794 Task_Dispatching_Policy := ' ';
26795 Priority_Specific_Dispatching :=
26796 Local_Priority_Specific_Dispatching'Address;
26797 Num_Specific_Dispatching := 0;
26799 Interrupt_States := Local_Interrupt_States'Address;
26800 Num_Interrupt_States := 0;
26801 Unreserve_All_Interrupts := 0;
26802 Detect_Blocking := 0;
26803 Default_Stack_Size := -1;
26804 Leap_Seconds_Support := 0;
26806 Runtime_Initialize;
26808 Finalize_Library_Objects := finalize_library'access;
26810 -- Now we have the elaboration calls for all units in the partition.
26811 -- The Elab_Spec and Elab_Body attributes generate references to the
26812 -- implicit elaboration procedures generated by the compiler for
26813 -- each unit that requires elaboration. Increment a counter of
26814 -- reference for each unit.
26816 System.Soft_Links'Elab_Spec;
26817 System.Exception_Table'Elab_Body;
26819 Ada.Io_Exceptions'Elab_Spec;
26821 Ada.Tags'Elab_Spec;
26822 Ada.Streams'Elab_Spec;
26824 Interfaces.C'Elab_Spec;
26825 System.Exceptions'Elab_Spec;
26827 System.Finalization_Root'Elab_Spec;
26829 Ada.Finalization'Elab_Spec;
26831 System.Storage_Pools'Elab_Spec;
26833 System.Finalization_Masters'Elab_Spec;
26834 System.Storage_Pools.Subpools'Elab_Spec;
26835 System.Pool_Global'Elab_Spec;
26837 System.File_Control_Block'Elab_Spec;
26839 System.File_Io'Elab_Body;
26842 System.Finalization_Masters'Elab_Body;
26845 Ada.Tags'Elab_Body;
26847 System.Soft_Links'Elab_Body;
26849 System.Os_Lib'Elab_Body;
26851 System.Secondary_Stack'Elab_Body;
26853 Ada.Text_Io'Elab_Spec;
26854 Ada.Text_Io'Elab_Body;
26862 procedure adafinal is
26863 procedure s_stalib_adafinal;
26864 pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
26866 procedure Runtime_Finalize;
26867 pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
26870 if not Is_Elaborated then
26873 Is_Elaborated := False;
26878 -- We get to the main program of the partition by using
26879 -- pragma Import because if we try to with the unit and
26880 -- call it Ada style, then not only do we waste time
26881 -- recompiling it, but also, we don't really know the right
26882 -- switches (e.g.@@: identifier character set) to be used
26885 procedure Ada_Main_Program;
26886 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26892 -- main is actually a function, as in the ANSI C standard,
26893 -- defined to return the exit status. The three parameters
26894 -- are the argument count, argument values and environment
26899 argv : System.Address;
26900 envp : System.Address)
26903 -- The initialize routine performs low level system
26904 -- initialization using a standard library routine which
26905 -- sets up signal handling and performs any other
26906 -- required setup. The routine can be found in file
26909 procedure initialize;
26910 pragma Import (C, initialize, "__gnat_initialize");
26912 -- The finalize routine performs low level system
26913 -- finalization using a standard library routine. The
26914 -- routine is found in file a-final.c and in the standard
26915 -- distribution is a dummy routine that does nothing, so
26916 -- really this is a hook for special user finalization.
26918 procedure finalize;
26919 pragma Import (C, finalize, "__gnat_finalize");
26921 -- The following is to initialize the SEH exceptions
26923 SEH : aliased array (1 .. 2) of Integer;
26925 Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
26926 pragma Volatile (Ensure_Reference);
26928 -- Start of processing for main
26931 -- Save global variables
26937 -- Call low level system initialization
26939 Initialize (SEH'Address);
26941 -- Call our generated Ada initialization routine
26945 -- Now we call the main program of the partition
26949 -- Perform Ada finalization
26953 -- Perform low level system finalization
26957 -- Return the proper exit status
26958 return (gnat_exit_status);
26961 -- This section is entirely comments, so it has no effect on the
26962 -- compilation of the Ada_Main package. It provides the list of
26963 -- object files and linker options, as well as some standard
26964 -- libraries needed for the link. The gnatlink utility parses
26965 -- this b~hello.adb file to read these comment lines to generate
26966 -- the appropriate command line arguments for the call to the
26967 -- system linker. The BEGIN/END lines are used for sentinels for
26968 -- this parsing operation.
26970 -- The exact file names will of course depend on the environment,
26971 -- host/target and location of files on the host system.
26973 -- BEGIN Object file/option list
26976 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
26977 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
26978 -- END Object file/option list
26983 The Ada code in the above example is exactly what is generated by the
26984 binder. We have added comments to more clearly indicate the function
26985 of each part of the generated @code{Ada_Main} package.
26987 The code is standard Ada in all respects, and can be processed by any
26988 tools that handle Ada. In particular, it is possible to use the debugger
26989 in Ada mode to debug the generated @code{Ada_Main} package. For example,
26990 suppose that for reasons that you do not understand, your program is crashing
26991 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
26992 you can place a breakpoint on the call:
26997 Ada.Text_Io'Elab_Body;
27001 and trace the elaboration routine for this package to find out where
27002 the problem might be (more usually of course you would be debugging
27003 elaboration code in your own application).
27005 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
27007 @node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
27008 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order-handling-in-gnat}@anchor{f}@anchor{gnat_ugn/elaboration_order_handling_in_gnat doc}@anchor{22c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id1}@anchor{22d}
27009 @chapter Elaboration Order Handling in GNAT
27012 @geindex Order of elaboration
27014 @geindex Elaboration control
27016 This appendix describes the handling of elaboration code in Ada and
27017 in GNAT, and discusses how the order of elaboration of program units can
27018 be controlled in GNAT, either automatically or with explicit programming
27022 * Elaboration Code::
27023 * Checking the Elaboration Order::
27024 * Controlling the Elaboration Order::
27025 * Controlling Elaboration in GNAT - Internal Calls::
27026 * Controlling Elaboration in GNAT - External Calls::
27027 * Default Behavior in GNAT - Ensuring Safety::
27028 * Treatment of Pragma Elaborate::
27029 * Elaboration Issues for Library Tasks::
27030 * Mixing Elaboration Models::
27031 * What to Do If the Default Elaboration Behavior Fails::
27032 * Elaboration for Indirect Calls::
27033 * Summary of Procedures for Elaboration Control::
27034 * Other Elaboration Order Considerations::
27035 * Determining the Chosen Elaboration Order::
27039 @node Elaboration Code,Checking the Elaboration Order,,Elaboration Order Handling in GNAT
27040 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{22e}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{22f}
27041 @section Elaboration Code
27044 Ada provides rather general mechanisms for executing code at elaboration
27045 time, that is to say before the main program starts executing. Such code arises
27052 @emph{Initializers for variables}
27054 Variables declared at the library level, in package specs or bodies, can
27055 require initialization that is performed at elaboration time, as in:
27058 Sqrt_Half : Float := Sqrt (0.5);
27062 @emph{Package initialization code}
27064 Code in a @code{begin} ... `@w{`} end`@w{`} section at the outer level of a package body is
27065 executed as part of the package body elaboration code.
27068 @emph{Library level task allocators}
27070 Tasks that are declared using task allocators at the library level
27071 start executing immediately and hence can execute at elaboration time.
27074 Subprogram calls are possible in any of these contexts, which means that
27075 any arbitrary part of the program may be executed as part of the elaboration
27076 code. It is even possible to write a program which does all its work at
27077 elaboration time, with a null main program, although stylistically this
27078 would usually be considered an inappropriate way to structure
27081 An important concern arises in the context of elaboration code:
27082 we have to be sure that it is executed in an appropriate order. What we
27083 have is a series of elaboration code sections, potentially one section
27084 for each unit in the program. It is important that these execute
27085 in the correct order. Correctness here means that, taking the above
27086 example of the declaration of @code{Sqrt_Half},
27087 if some other piece of
27088 elaboration code references @code{Sqrt_Half},
27089 then it must run after the
27090 section of elaboration code that contains the declaration of
27093 There would never be any order of elaboration problem if we made a rule
27094 that whenever you @emph{with} a unit, you must elaborate both the spec and body
27095 of that unit before elaborating the unit doing the @emph{with}ing:
27099 package Unit_2 is ...
27102 would require that both the body and spec of @code{Unit_1} be elaborated
27103 before the spec of @code{Unit_2}. However, a rule like that would be far too
27104 restrictive. In particular, it would make it impossible to have routines
27105 in separate packages that were mutually recursive.
27107 You might think that a clever enough compiler could look at the actual
27108 elaboration code and determine an appropriate correct order of elaboration,
27109 but in the general case, this is not possible. Consider the following
27112 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
27114 the variable @code{Sqrt_1}, which is declared in the elaboration code
27115 of the body of @code{Unit_1}:
27118 Sqrt_1 : Float := Sqrt (0.1);
27121 The elaboration code of the body of @code{Unit_1} also contains:
27124 if expression_1 = 1 then
27125 Q := Unit_2.Func_2;
27129 @code{Unit_2} is exactly parallel,
27130 it has a procedure @code{Func_2} that references
27131 the variable @code{Sqrt_2}, which is declared in the elaboration code of
27132 the body @code{Unit_2}:
27135 Sqrt_2 : Float := Sqrt (0.1);
27138 The elaboration code of the body of @code{Unit_2} also contains:
27141 if expression_2 = 2 then
27142 Q := Unit_1.Func_1;
27146 Now the question is, which of the following orders of elaboration is
27165 If you carefully analyze the flow here, you will see that you cannot tell
27166 at compile time the answer to this question.
27167 If @code{expression_1} is not equal to 1,
27168 and @code{expression_2} is not equal to 2,
27169 then either order is acceptable, because neither of the function calls is
27170 executed. If both tests evaluate to true, then neither order is acceptable
27171 and in fact there is no correct order.
27173 If one of the two expressions is true, and the other is false, then one
27174 of the above orders is correct, and the other is incorrect. For example,
27175 if @code{expression_1} /= 1 and @code{expression_2} = 2,
27176 then the call to @code{Func_1}
27177 will occur, but not the call to @code{Func_2.}
27178 This means that it is essential
27179 to elaborate the body of @code{Unit_1} before
27180 the body of @code{Unit_2}, so the first
27181 order of elaboration is correct and the second is wrong.
27183 By making @code{expression_1} and @code{expression_2}
27184 depend on input data, or perhaps
27185 the time of day, we can make it impossible for the compiler or binder
27186 to figure out which of these expressions will be true, and hence it
27187 is impossible to guarantee a safe order of elaboration at run time.
27189 @node Checking the Elaboration Order,Controlling the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
27190 @anchor{gnat_ugn/elaboration_order_handling_in_gnat checking-the-elaboration-order}@anchor{230}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{231}
27191 @section Checking the Elaboration Order
27194 In some languages that involve the same kind of elaboration problems,
27195 e.g., Java and C++, the programmer needs to take these
27196 ordering problems into account, and it is common to
27197 write a program in which an incorrect elaboration order gives
27198 surprising results, because it references variables before they
27200 Ada is designed to be a safe language, and a programmer-beware approach is
27201 clearly not sufficient. Consequently, the language provides three lines
27208 @emph{Standard rules}
27210 Some standard rules restrict the possible choice of elaboration
27211 order. In particular, if you @emph{with} a unit, then its spec is always
27212 elaborated before the unit doing the @emph{with}. Similarly, a parent
27213 spec is always elaborated before the child spec, and finally
27214 a spec is always elaborated before its corresponding body.
27217 @geindex Elaboration checks
27220 @geindex elaboration
27226 @emph{Dynamic elaboration checks}
27228 Dynamic checks are made at run time, so that if some entity is accessed
27229 before it is elaborated (typically by means of a subprogram call)
27230 then the exception (@code{Program_Error}) is raised.
27233 @emph{Elaboration control}
27235 Facilities are provided for the programmer to specify the desired order
27239 Let's look at these facilities in more detail. First, the rules for
27240 dynamic checking. One possible rule would be simply to say that the
27241 exception is raised if you access a variable which has not yet been
27242 elaborated. The trouble with this approach is that it could require
27243 expensive checks on every variable reference. Instead Ada has two
27244 rules which are a little more restrictive, but easier to check, and
27251 @emph{Restrictions on calls}
27253 A subprogram can only be called at elaboration time if its body
27254 has been elaborated. The rules for elaboration given above guarantee
27255 that the spec of the subprogram has been elaborated before the
27256 call, but not the body. If this rule is violated, then the
27257 exception @code{Program_Error} is raised.
27260 @emph{Restrictions on instantiations}
27262 A generic unit can only be instantiated if the body of the generic
27263 unit has been elaborated. Again, the rules for elaboration given above
27264 guarantee that the spec of the generic unit has been elaborated
27265 before the instantiation, but not the body. If this rule is
27266 violated, then the exception @code{Program_Error} is raised.
27269 The idea is that if the body has been elaborated, then any variables
27270 it references must have been elaborated; by checking for the body being
27271 elaborated we guarantee that none of its references causes any
27272 trouble. As we noted above, this is a little too restrictive, because a
27273 subprogram that has no non-local references in its body may in fact be safe
27274 to call. However, it really would be unsafe to rely on this, because
27275 it would mean that the caller was aware of details of the implementation
27276 in the body. This goes against the basic tenets of Ada.
27278 A plausible implementation can be described as follows.
27279 A Boolean variable is associated with each subprogram
27280 and each generic unit. This variable is initialized to False, and is set to
27281 True at the point body is elaborated. Every call or instantiation checks the
27282 variable, and raises @code{Program_Error} if the variable is False.
27284 Note that one might think that it would be good enough to have one Boolean
27285 variable for each package, but that would not deal with cases of trying
27286 to call a body in the same package as the call
27287 that has not been elaborated yet.
27288 Of course a compiler may be able to do enough analysis to optimize away
27289 some of the Boolean variables as unnecessary, and GNAT indeed
27290 does such optimizations, but still the easiest conceptual model is to
27291 think of there being one variable per subprogram.
27293 @node Controlling the Elaboration Order,Controlling Elaboration in GNAT - Internal Calls,Checking the Elaboration Order,Elaboration Order Handling in GNAT
27294 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id4}@anchor{232}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order}@anchor{233}
27295 @section Controlling the Elaboration Order
27298 In the previous section we discussed the rules in Ada which ensure
27299 that @code{Program_Error} is raised if an incorrect elaboration order is
27300 chosen. This prevents erroneous executions, but we need mechanisms to
27301 specify a correct execution and avoid the exception altogether.
27302 To achieve this, Ada provides a number of features for controlling
27303 the order of elaboration. We discuss these features in this section.
27305 First, there are several ways of indicating to the compiler that a given
27306 unit has no elaboration problems:
27312 @emph{packages that do not require a body}
27314 A library package that does not require a body does not permit
27315 a body (this rule was introduced in Ada 95).
27316 Thus if we have a such a package, as in:
27319 package Definitions is
27321 type m is new integer;
27323 type a is array (1 .. 10) of m;
27324 type b is array (1 .. 20) of m;
27329 A package that @emph{with}s @code{Definitions} may safely instantiate
27330 @code{Definitions.Subp} because the compiler can determine that there
27331 definitely is no package body to worry about in this case
27334 @geindex pragma Pure
27342 This pragma places sufficient restrictions on a unit to guarantee that
27343 no call to any subprogram in the unit can result in an
27344 elaboration problem. This means that the compiler does not need
27345 to worry about the point of elaboration of such units, and in
27346 particular, does not need to check any calls to any subprograms
27350 @geindex pragma Preelaborate
27356 @emph{pragma Preelaborate}
27358 This pragma places slightly less stringent restrictions on a unit than
27360 but these restrictions are still sufficient to ensure that there
27361 are no elaboration problems with any calls to the unit.
27364 @geindex pragma Elaborate_Body
27370 @emph{pragma Elaborate_Body}
27372 This pragma requires that the body of a unit be elaborated immediately
27373 after its spec. Suppose a unit @code{A} has such a pragma,
27374 and unit @code{B} does
27375 a @emph{with} of unit @code{A}. Recall that the standard rules require
27376 the spec of unit @code{A}
27377 to be elaborated before the @emph{with}ing unit; given the pragma in
27378 @code{A}, we also know that the body of @code{A}
27379 will be elaborated before @code{B}, so
27380 that calls to @code{A} are safe and do not need a check.
27382 Note that, unlike pragma @code{Pure} and pragma @code{Preelaborate},
27383 the use of @code{Elaborate_Body} does not guarantee that the program is
27384 free of elaboration problems, because it may not be possible
27385 to satisfy the requested elaboration order.
27386 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
27387 If a programmer marks @code{Unit_1} as @code{Elaborate_Body},
27388 and not @code{Unit_2,} then the order of
27389 elaboration will be:
27398 Now that means that the call to @code{Func_1} in @code{Unit_2}
27399 need not be checked,
27400 it must be safe. But the call to @code{Func_2} in
27401 @code{Unit_1} may still fail if
27402 @code{Expression_1} is equal to 1,
27403 and the programmer must still take
27404 responsibility for this not being the case.
27406 If all units carry a pragma @code{Elaborate_Body}, then all problems are
27407 eliminated, except for calls entirely within a body, which are
27408 in any case fully under programmer control. However, using the pragma
27409 everywhere is not always possible.
27410 In particular, for our @code{Unit_1}/@cite{Unit_2} example, if
27411 we marked both of them as having pragma @code{Elaborate_Body}, then
27412 clearly there would be no possible elaboration order.
27415 The above pragmas allow a server to guarantee safe use by clients, and
27416 clearly this is the preferable approach. Consequently a good rule
27417 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
27418 and if this is not possible,
27419 mark them as @code{Elaborate_Body} if possible.
27420 As we have seen, there are situations where neither of these
27421 three pragmas can be used.
27422 So we also provide methods for clients to control the
27423 order of elaboration of the servers on which they depend:
27425 @geindex pragma Elaborate
27431 @emph{pragma Elaborate (unit)}
27433 This pragma is placed in the context clause, after a @emph{with} clause,
27434 and it requires that the body of the named unit be elaborated before
27435 the unit in which the pragma occurs. The idea is to use this pragma
27436 if the current unit calls at elaboration time, directly or indirectly,
27437 some subprogram in the named unit.
27440 @geindex pragma Elaborate_All
27446 @emph{pragma Elaborate_All (unit)}
27448 This is a stronger version of the Elaborate pragma. Consider the
27452 Unit A |withs| unit B and calls B.Func in elab code
27453 Unit B |withs| unit C, and B.Func calls C.Func
27456 Now if we put a pragma @code{Elaborate (B)}
27457 in unit @code{A}, this ensures that the
27458 body of @code{B} is elaborated before the call, but not the
27459 body of @code{C}, so
27460 the call to @code{C.Func} could still cause @code{Program_Error} to
27463 The effect of a pragma @code{Elaborate_All} is stronger, it requires
27464 not only that the body of the named unit be elaborated before the
27465 unit doing the @emph{with}, but also the bodies of all units that the
27466 named unit uses, following @emph{with} links transitively. For example,
27467 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
27468 then it requires not only that the body of @code{B} be elaborated before @code{A},
27469 but also the body of @code{C}, because @code{B} @emph{with}s @code{C}.
27472 We are now in a position to give a usage rule in Ada for avoiding
27473 elaboration problems, at least if dynamic dispatching and access to
27474 subprogram values are not used. We will handle these cases separately
27477 The rule is simple:
27479 @emph{If a unit has elaboration code that can directly or
27480 indirectly make a call to a subprogram in a |withed| unit, or instantiate
27481 a generic package in a |withed| unit,
27482 then if the |withed| unit does not have
27483 pragma `@w{`}Pure`@w{`} or `@w{`}Preelaborate`@w{`}, then the client should have
27484 a pragma `@w{`}Elaborate_All`@w{`}for the |withed| unit.*}
27486 By following this rule a client is
27487 assured that calls can be made without risk of an exception.
27489 For generic subprogram instantiations, the rule can be relaxed to
27490 require only a pragma @code{Elaborate} since elaborating the body
27491 of a subprogram cannot cause any transitive elaboration (we are
27492 not calling the subprogram in this case, just elaborating its
27495 If this rule is not followed, then a program may be in one of four
27502 @emph{No order exists}
27504 No order of elaboration exists which follows the rules, taking into
27505 account any @code{Elaborate}, @code{Elaborate_All},
27506 or @code{Elaborate_Body} pragmas. In
27507 this case, an Ada compiler must diagnose the situation at bind
27508 time, and refuse to build an executable program.
27511 @emph{One or more orders exist, all incorrect}
27513 One or more acceptable elaboration orders exist, and all of them
27514 generate an elaboration order problem. In this case, the binder
27515 can build an executable program, but @code{Program_Error} will be raised
27516 when the program is run.
27519 @emph{Several orders exist, some right, some incorrect}
27521 One or more acceptable elaboration orders exists, and some of them
27522 work, and some do not. The programmer has not controlled
27523 the order of elaboration, so the binder may or may not pick one of
27524 the correct orders, and the program may or may not raise an
27525 exception when it is run. This is the worst case, because it means
27526 that the program may fail when moved to another compiler, or even
27527 another version of the same compiler.
27530 @emph{One or more orders exists, all correct}
27532 One ore more acceptable elaboration orders exist, and all of them
27533 work. In this case the program runs successfully. This state of
27534 affairs can be guaranteed by following the rule we gave above, but
27535 may be true even if the rule is not followed.
27538 Note that one additional advantage of following our rules on the use
27539 of @code{Elaborate} and @code{Elaborate_All}
27540 is that the program continues to stay in the ideal (all orders OK) state
27541 even if maintenance
27542 changes some bodies of some units. Conversely, if a program that does
27543 not follow this rule happens to be safe at some point, this state of affairs
27544 may deteriorate silently as a result of maintenance changes.
27546 You may have noticed that the above discussion did not mention
27547 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
27548 @emph{with} an @code{Elaborate_Body} unit, it still may be the case that
27549 code in the body makes calls to some other unit, so it is still necessary
27550 to use @code{Elaborate_All} on such units.
27552 @node Controlling Elaboration in GNAT - Internal Calls,Controlling Elaboration in GNAT - External Calls,Controlling the Elaboration Order,Elaboration Order Handling in GNAT
27553 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id5}@anchor{234}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-elaboration-in-gnat-internal-calls}@anchor{235}
27554 @section Controlling Elaboration in GNAT - Internal Calls
27557 In the case of internal calls, i.e., calls within a single package, the
27558 programmer has full control over the order of elaboration, and it is up
27559 to the programmer to elaborate declarations in an appropriate order. For
27563 function One return Float;
27567 function One return Float is
27573 will obviously raise @code{Program_Error} at run time, because function
27574 One will be called before its body is elaborated. In this case GNAT will
27575 generate a warning that the call will raise @code{Program_Error}:
27579 2. function One return Float;
27581 4. Q : Float := One;
27583 >>> warning: cannot call "One" before body is elaborated
27584 >>> warning: Program_Error will be raised at run time
27587 6. function One return Float is
27597 Note that in this particular case, it is likely that the call is safe, because
27598 the function @code{One} does not access any global variables.
27599 Nevertheless in Ada, we do not want the validity of the check to depend on
27600 the contents of the body (think about the separate compilation case), so this
27601 is still wrong, as we discussed in the previous sections.
27603 The error is easily corrected by rearranging the declarations so that the
27604 body of @code{One} appears before the declaration containing the call
27605 (note that in Ada 95 as well as later versions of the Ada standard,
27606 declarations can appear in any order, so there is no restriction that
27607 would prevent this reordering, and if we write:
27610 function One return Float;
27612 function One return Float is
27620 then all is well, no warning is generated, and no
27621 @code{Program_Error} exception
27623 Things are more complicated when a chain of subprograms is executed:
27626 function A return Integer;
27627 function B return Integer;
27628 function C return Integer;
27630 function B return Integer is begin return A; end;
27631 function C return Integer is begin return B; end;
27635 function A return Integer is begin return 1; end;
27638 Now the call to @code{C}
27639 at elaboration time in the declaration of @code{X} is correct, because
27640 the body of @code{C} is already elaborated,
27641 and the call to @code{B} within the body of
27642 @code{C} is correct, but the call
27643 to @code{A} within the body of @code{B} is incorrect, because the body
27644 of @code{A} has not been elaborated, so @code{Program_Error}
27645 will be raised on the call to @code{A}.
27646 In this case GNAT will generate a
27647 warning that @code{Program_Error} may be
27648 raised at the point of the call. Let's look at the warning:
27652 2. function A return Integer;
27653 3. function B return Integer;
27654 4. function C return Integer;
27656 6. function B return Integer is begin return A; end;
27658 >>> warning: call to "A" before body is elaborated may
27659 raise Program_Error
27660 >>> warning: "B" called at line 7
27661 >>> warning: "C" called at line 9
27663 7. function C return Integer is begin return B; end;
27665 9. X : Integer := C;
27667 11. function A return Integer is begin return 1; end;
27674 Note that the message here says 'may raise', instead of the direct case,
27675 where the message says 'will be raised'. That's because whether
27677 actually called depends in general on run-time flow of control.
27678 For example, if the body of @code{B} said
27681 function B return Integer is
27683 if some-condition-depending-on-input-data then
27691 then we could not know until run time whether the incorrect call to A would
27692 actually occur, so @code{Program_Error} might
27693 or might not be raised. It is possible for a compiler to
27694 do a better job of analyzing bodies, to
27695 determine whether or not @code{Program_Error}
27696 might be raised, but it certainly
27697 couldn't do a perfect job (that would require solving the halting problem
27698 and is provably impossible), and because this is a warning anyway, it does
27699 not seem worth the effort to do the analysis. Cases in which it
27700 would be relevant are rare.
27702 In practice, warnings of either of the forms given
27703 above will usually correspond to
27704 real errors, and should be examined carefully and eliminated.
27705 In the rare case where a warning is bogus, it can be suppressed by any of
27706 the following methods:
27712 Compile with the @code{-gnatws} switch set
27715 Suppress @code{Elaboration_Check} for the called subprogram
27718 Use pragma @code{Warnings_Off} to turn warnings off for the call
27721 For the internal elaboration check case,
27722 GNAT by default generates the
27723 necessary run-time checks to ensure
27724 that @code{Program_Error} is raised if any
27725 call fails an elaboration check. Of course this can only happen if a
27726 warning has been issued as described above. The use of pragma
27727 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
27728 some of these checks, meaning that it may be possible (but is not
27729 guaranteed) for a program to be able to call a subprogram whose body
27730 is not yet elaborated, without raising a @code{Program_Error} exception.
27732 @node Controlling Elaboration in GNAT - External Calls,Default Behavior in GNAT - Ensuring Safety,Controlling Elaboration in GNAT - Internal Calls,Elaboration Order Handling in GNAT
27733 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id6}@anchor{236}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-elaboration-in-gnat-external-calls}@anchor{237}
27734 @section Controlling Elaboration in GNAT - External Calls
27737 The previous section discussed the case in which the execution of a
27738 particular thread of elaboration code occurred entirely within a
27739 single unit. This is the easy case to handle, because a programmer
27740 has direct and total control over the order of elaboration, and
27741 furthermore, checks need only be generated in cases which are rare
27742 and which the compiler can easily detect.
27743 The situation is more complex when separate compilation is taken into account.
27744 Consider the following:
27748 function Sqrt (Arg : Float) return Float;
27751 package body Math is
27752 function Sqrt (Arg : Float) return Float is
27760 X : Float := Math.Sqrt (0.5);
27770 where @code{Main} is the main program. When this program is executed, the
27771 elaboration code must first be executed, and one of the jobs of the
27772 binder is to determine the order in which the units of a program are
27773 to be elaborated. In this case we have four units: the spec and body
27775 the spec of @code{Stuff} and the body of @code{Main}).
27776 In what order should the four separate sections of elaboration code
27779 There are some restrictions in the order of elaboration that the binder
27780 can choose. In particular, if unit U has a @emph{with}
27781 for a package @code{X}, then you
27782 are assured that the spec of @code{X}
27783 is elaborated before U , but you are
27784 not assured that the body of @code{X}
27785 is elaborated before U.
27786 This means that in the above case, the binder is allowed to choose the
27796 but that's not good, because now the call to @code{Math.Sqrt}
27797 that happens during
27798 the elaboration of the @code{Stuff}
27799 spec happens before the body of @code{Math.Sqrt} is
27800 elaborated, and hence causes @code{Program_Error} exception to be raised.
27801 At first glance, one might say that the binder is misbehaving, because
27802 obviously you want to elaborate the body of something you @emph{with} first, but
27803 that is not a general rule that can be followed in all cases. Consider
27811 package body Y is ...
27814 package body X is ...
27817 This is a common arrangement, and, apart from the order of elaboration
27818 problems that might arise in connection with elaboration code, this works fine.
27819 A rule that says that you must first elaborate the body of anything you
27820 @emph{with} cannot work in this case:
27821 the body of @code{X} @emph{with}s @code{Y},
27822 which means you would have to
27823 elaborate the body of @code{Y} first, but that @emph{with}s @code{X},
27825 you have to elaborate the body of @code{X} first, but ... and we have a
27826 loop that cannot be broken.
27828 It is true that the binder can in many cases guess an order of elaboration
27829 that is unlikely to cause a @code{Program_Error}
27830 exception to be raised, and it tries to do so (in the
27831 above example of @code{Math/Stuff/Spec}, the GNAT binder will
27833 elaborate the body of @code{Math} right after its spec, so all will be well).
27835 However, a program that blindly relies on the binder to be helpful can
27836 get into trouble, as we discussed in the previous sections, so GNAT
27837 provides a number of facilities for assisting the programmer in
27838 developing programs that are robust with respect to elaboration order.
27840 @node Default Behavior in GNAT - Ensuring Safety,Treatment of Pragma Elaborate,Controlling Elaboration in GNAT - External Calls,Elaboration Order Handling in GNAT
27841 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{238}@anchor{gnat_ugn/elaboration_order_handling_in_gnat default-behavior-in-gnat-ensuring-safety}@anchor{239}
27842 @section Default Behavior in GNAT - Ensuring Safety
27845 The default behavior in GNAT ensures elaboration safety. In its
27846 default mode GNAT implements the
27847 rule we previously described as the right approach. Let's restate it:
27849 @emph{If a unit has elaboration code that can directly or indirectly make a
27850 call to a subprogram in a |withed| unit, or instantiate a generic
27851 package in a |withed| unit, then if the |withed| unit
27852 does not have pragma `@w{`}Pure`@w{`} or `@w{`}Preelaborate`@w{`}, then the client should have an
27853 `@w{`}Elaborate_All`@w{`} pragma for the |withed| unit.}
27855 @emph{In the case of instantiating a generic subprogram, it is always
27856 sufficient to have only an `@w{`}Elaborate`@w{`} pragma for the
27859 By following this rule a client is assured that calls and instantiations
27860 can be made without risk of an exception.
27862 In this mode GNAT traces all calls that are potentially made from
27863 elaboration code, and puts in any missing implicit @code{Elaborate}
27864 and @code{Elaborate_All} pragmas.
27865 The advantage of this approach is that no elaboration problems
27866 are possible if the binder can find an elaboration order that is
27867 consistent with these implicit @code{Elaborate} and
27868 @code{Elaborate_All} pragmas. The
27869 disadvantage of this approach is that no such order may exist.
27871 If the binder does not generate any diagnostics, then it means that it has
27872 found an elaboration order that is guaranteed to be safe. However, the binder
27873 may still be relying on implicitly generated @code{Elaborate} and
27874 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
27877 If it is important to guarantee portability, then the compilations should
27878 use the @code{-gnatel}
27879 (info messages for elaboration pragmas) switch. This will cause info messages
27880 to be generated indicating the missing @code{Elaborate} and
27881 @code{Elaborate_All} pragmas.
27882 Consider the following source program:
27887 m : integer := k.r;
27891 where it is clear that there
27892 should be a pragma @code{Elaborate_All}
27893 for unit @code{k}. An implicit pragma will be generated, and it is
27894 likely that the binder will be able to honor it. However, if you want
27895 to port this program to some other Ada compiler than GNAT.
27896 it is safer to include the pragma explicitly in the source. If this
27897 unit is compiled with the @code{-gnatel}
27898 switch, then the compiler outputs an information message:
27903 3. m : integer := k.r;
27905 >>> info: call to "r" may raise Program_Error
27906 >>> info: missing pragma Elaborate_All for "k"
27911 and these messages can be used as a guide for supplying manually
27912 the missing pragmas. It is usually a bad idea to use this
27913 option during development. That's because it will tell you when
27914 you need to put in a pragma, but cannot tell you when it is time
27915 to take it out. So the use of pragma @code{Elaborate_All} may lead to
27916 unnecessary dependencies and even false circularities.
27918 This default mode is more restrictive than the Ada Reference
27919 Manual, and it is possible to construct programs which will compile
27920 using the dynamic model described there, but will run into a
27921 circularity using the safer static model we have described.
27923 Of course any Ada compiler must be able to operate in a mode
27924 consistent with the requirements of the Ada Reference Manual,
27925 and in particular must have the capability of implementing the
27926 standard dynamic model of elaboration with run-time checks.
27928 In GNAT, this standard mode can be achieved either by the use of
27929 the @code{-gnatE} switch on the compiler (@code{gcc} or
27930 @code{gnatmake}) command, or by the use of the configuration pragma:
27933 pragma Elaboration_Checks (DYNAMIC);
27936 Either approach will cause the unit affected to be compiled using the
27937 standard dynamic run-time elaboration checks described in the Ada
27938 Reference Manual. The static model is generally preferable, since it
27939 is clearly safer to rely on compile and link time checks rather than
27940 run-time checks. However, in the case of legacy code, it may be
27941 difficult to meet the requirements of the static model. This
27942 issue is further discussed in
27943 @ref{23a,,What to Do If the Default Elaboration Behavior Fails}.
27945 Note that the static model provides a strict subset of the allowed
27946 behavior and programs of the Ada Reference Manual, so if you do
27947 adhere to the static model and no circularities exist,
27948 then you are assured that your program will
27949 work using the dynamic model, providing that you remove any
27950 pragma Elaborate statements from the source.
27952 @node Treatment of Pragma Elaborate,Elaboration Issues for Library Tasks,Default Behavior in GNAT - Ensuring Safety,Elaboration Order Handling in GNAT
27953 @anchor{gnat_ugn/elaboration_order_handling_in_gnat treatment-of-pragma-elaborate}@anchor{23b}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{23c}
27954 @section Treatment of Pragma Elaborate
27957 @geindex Pragma Elaborate
27959 The use of @code{pragma Elaborate}
27960 should generally be avoided in Ada 95 and Ada 2005 programs,
27961 since there is no guarantee that transitive calls
27962 will be properly handled. Indeed at one point, this pragma was placed
27963 in Annex J (Obsolescent Features), on the grounds that it is never useful.
27965 Now that's a bit restrictive. In practice, the case in which
27966 @code{pragma Elaborate} is useful is when the caller knows that there
27967 are no transitive calls, or that the called unit contains all necessary
27968 transitive @code{pragma Elaborate} statements, and legacy code often
27969 contains such uses.
27971 Strictly speaking the static mode in GNAT should ignore such pragmas,
27972 since there is no assurance at compile time that the necessary safety
27973 conditions are met. In practice, this would cause GNAT to be incompatible
27974 with correctly written Ada 83 code that had all necessary
27975 @code{pragma Elaborate} statements in place. Consequently, we made the
27976 decision that GNAT in its default mode will believe that if it encounters
27977 a @code{pragma Elaborate} then the programmer knows what they are doing,
27978 and it will trust that no elaboration errors can occur.
27980 The result of this decision is two-fold. First to be safe using the
27981 static mode, you should remove all @code{pragma Elaborate} statements.
27982 Second, when fixing circularities in existing code, you can selectively
27983 use @code{pragma Elaborate} statements to convince the static mode of
27984 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
27987 When using the static mode with @code{-gnatwl}, any use of
27988 @code{pragma Elaborate} will generate a warning about possible
27991 @node Elaboration Issues for Library Tasks,Mixing Elaboration Models,Treatment of Pragma Elaborate,Elaboration Order Handling in GNAT
27992 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-issues-for-library-tasks}@anchor{23d}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{23e}
27993 @section Elaboration Issues for Library Tasks
27996 @geindex Library tasks
27997 @geindex elaboration issues
27999 @geindex Elaboration of library tasks
28001 In this section we examine special elaboration issues that arise for
28002 programs that declare library level tasks.
28004 Generally the model of execution of an Ada program is that all units are
28005 elaborated, and then execution of the program starts. However, the
28006 declaration of library tasks definitely does not fit this model. The
28007 reason for this is that library tasks start as soon as they are declared
28008 (more precisely, as soon as the statement part of the enclosing package
28009 body is reached), that is to say before elaboration
28010 of the program is complete. This means that if such a task calls a
28011 subprogram, or an entry in another task, the callee may or may not be
28012 elaborated yet, and in the standard
28013 Reference Manual model of dynamic elaboration checks, you can even
28014 get timing dependent Program_Error exceptions, since there can be
28015 a race between the elaboration code and the task code.
28017 The static model of elaboration in GNAT seeks to avoid all such
28018 dynamic behavior, by being conservative, and the conservative
28019 approach in this particular case is to assume that all the code
28020 in a task body is potentially executed at elaboration time if
28021 a task is declared at the library level.
28023 This can definitely result in unexpected circularities. Consider
28024 the following example
28032 type My_Int is new Integer;
28034 function Ident (M : My_Int) return My_Int;
28038 package body Decls is
28039 task body Lib_Task is
28045 function Ident (M : My_Int) return My_Int is
28053 procedure Put_Val (Arg : Decls.My_Int);
28057 package body Utils is
28058 procedure Put_Val (Arg : Decls.My_Int) is
28060 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28067 Decls.Lib_Task.Start;
28071 If the above example is compiled in the default static elaboration
28072 mode, then a circularity occurs. The circularity comes from the call
28073 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
28074 this call occurs in elaboration code, we need an implicit pragma
28075 @code{Elaborate_All} for @code{Utils}. This means that not only must
28076 the spec and body of @code{Utils} be elaborated before the body
28077 of @code{Decls}, but also the spec and body of any unit that is
28078 @emph{with}ed by the body of @code{Utils} must also be elaborated before
28079 the body of @code{Decls}. This is the transitive implication of
28080 pragma @code{Elaborate_All} and it makes sense, because in general
28081 the body of @code{Put_Val} might have a call to something in a
28082 @emph{with}ed unit.
28084 In this case, the body of Utils (actually its spec) @emph{with}s
28085 @code{Decls}. Unfortunately this means that the body of @code{Decls}
28086 must be elaborated before itself, in case there is a call from the
28087 body of @code{Utils}.
28089 Here is the exact chain of events we are worrying about:
28095 In the body of @code{Decls} a call is made from within the body of a library
28096 task to a subprogram in the package @code{Utils}. Since this call may
28097 occur at elaboration time (given that the task is activated at elaboration
28098 time), we have to assume the worst, i.e., that the
28099 call does happen at elaboration time.
28102 This means that the body and spec of @code{Util} must be elaborated before
28103 the body of @code{Decls} so that this call does not cause an access before
28107 Within the body of @code{Util}, specifically within the body of
28108 @code{Util.Put_Val} there may be calls to any unit @emph{with}ed
28112 One such @emph{with}ed package is package @code{Decls}, so there
28113 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
28114 In fact there is such a call in this example, but we would have to
28115 assume that there was such a call even if it were not there, since
28116 we are not supposed to write the body of @code{Decls} knowing what
28117 is in the body of @code{Utils}; certainly in the case of the
28118 static elaboration model, the compiler does not know what is in
28119 other bodies and must assume the worst.
28122 This means that the spec and body of @code{Decls} must also be
28123 elaborated before we elaborate the unit containing the call, but
28124 that unit is @code{Decls}! This means that the body of @code{Decls}
28125 must be elaborated before itself, and that's a circularity.
28128 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
28129 the body of @code{Decls} you will get a true Ada Reference Manual
28130 circularity that makes the program illegal.
28132 In practice, we have found that problems with the static model of
28133 elaboration in existing code often arise from library tasks, so
28134 we must address this particular situation.
28136 Note that if we compile and run the program above, using the dynamic model of
28137 elaboration (that is to say use the @code{-gnatE} switch),
28138 then it compiles, binds,
28139 links, and runs, printing the expected result of 2. Therefore in some sense
28140 the circularity here is only apparent, and we need to capture
28141 the properties of this program that distinguish it from other library-level
28142 tasks that have real elaboration problems.
28144 We have four possible answers to this question:
28150 Use the dynamic model of elaboration.
28152 If we use the @code{-gnatE} switch, then as noted above, the program works.
28153 Why is this? If we examine the task body, it is apparent that the task cannot
28155 @code{accept} statement until after elaboration has been completed, because
28156 the corresponding entry call comes from the main program, not earlier.
28157 This is why the dynamic model works here. But that's really giving
28158 up on a precise analysis, and we prefer to take this approach only if we cannot
28160 problem in any other manner. So let us examine two ways to reorganize
28161 the program to avoid the potential elaboration problem.
28164 Split library tasks into separate packages.
28166 Write separate packages, so that library tasks are isolated from
28167 other declarations as much as possible. Let us look at a variation on
28178 package body Decls1 is
28179 task body Lib_Task is
28187 type My_Int is new Integer;
28188 function Ident (M : My_Int) return My_Int;
28192 package body Decls2 is
28193 function Ident (M : My_Int) return My_Int is
28201 procedure Put_Val (Arg : Decls2.My_Int);
28205 package body Utils is
28206 procedure Put_Val (Arg : Decls2.My_Int) is
28208 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
28215 Decls1.Lib_Task.Start;
28219 All we have done is to split @code{Decls} into two packages, one
28220 containing the library task, and one containing everything else. Now
28221 there is no cycle, and the program compiles, binds, links and executes
28222 using the default static model of elaboration.
28225 Declare separate task types.
28227 A significant part of the problem arises because of the use of the
28228 single task declaration form. This means that the elaboration of
28229 the task type, and the elaboration of the task itself (i.e., the
28230 creation of the task) happen at the same time. A good rule
28231 of style in Ada is to always create explicit task types. By
28232 following the additional step of placing task objects in separate
28233 packages from the task type declaration, many elaboration problems
28234 are avoided. Here is another modified example of the example program:
28238 task type Lib_Task_Type is
28242 type My_Int is new Integer;
28244 function Ident (M : My_Int) return My_Int;
28248 package body Decls is
28249 task body Lib_Task_Type is
28255 function Ident (M : My_Int) return My_Int is
28263 procedure Put_Val (Arg : Decls.My_Int);
28267 package body Utils is
28268 procedure Put_Val (Arg : Decls.My_Int) is
28270 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28276 Lib_Task : Decls.Lib_Task_Type;
28282 Declst.Lib_Task.Start;
28286 What we have done here is to replace the @code{task} declaration in
28287 package @code{Decls} with a @code{task type} declaration. Then we
28288 introduce a separate package @code{Declst} to contain the actual
28289 task object. This separates the elaboration issues for
28290 the @code{task type}
28291 declaration, which causes no trouble, from the elaboration issues
28292 of the task object, which is also unproblematic, since it is now independent
28293 of the elaboration of @code{Utils}.
28294 This separation of concerns also corresponds to
28295 a generally sound engineering principle of separating declarations
28296 from instances. This version of the program also compiles, binds, links,
28297 and executes, generating the expected output.
28300 @geindex No_Entry_Calls_In_Elaboration_Code restriction
28306 Use No_Entry_Calls_In_Elaboration_Code restriction.
28308 The previous two approaches described how a program can be restructured
28309 to avoid the special problems caused by library task bodies. in practice,
28310 however, such restructuring may be difficult to apply to existing legacy code,
28311 so we must consider solutions that do not require massive rewriting.
28313 Let us consider more carefully why our original sample program works
28314 under the dynamic model of elaboration. The reason is that the code
28315 in the task body blocks immediately on the @code{accept}
28316 statement. Now of course there is nothing to prohibit elaboration
28317 code from making entry calls (for example from another library level task),
28318 so we cannot tell in isolation that
28319 the task will not execute the accept statement during elaboration.
28321 However, in practice it is very unusual to see elaboration code
28322 make any entry calls, and the pattern of tasks starting
28323 at elaboration time and then immediately blocking on @code{accept} or
28324 @code{select} statements is very common. What this means is that
28325 the compiler is being too pessimistic when it analyzes the
28326 whole package body as though it might be executed at elaboration
28329 If we know that the elaboration code contains no entry calls, (a very safe
28330 assumption most of the time, that could almost be made the default
28331 behavior), then we can compile all units of the program under control
28332 of the following configuration pragma:
28335 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28338 This pragma can be placed in the @code{gnat.adc} file in the usual
28339 manner. If we take our original unmodified program and compile it
28340 in the presence of a @code{gnat.adc} containing the above pragma,
28341 then once again, we can compile, bind, link, and execute, obtaining
28342 the expected result. In the presence of this pragma, the compiler does
28343 not trace calls in a task body, that appear after the first @code{accept}
28344 or @code{select} statement, and therefore does not report a potential
28345 circularity in the original program.
28347 The compiler will check to the extent it can that the above
28348 restriction is not violated, but it is not always possible to do a
28349 complete check at compile time, so it is important to use this
28350 pragma only if the stated restriction is in fact met, that is to say
28351 no task receives an entry call before elaboration of all units is completed.
28354 @node Mixing Elaboration Models,What to Do If the Default Elaboration Behavior Fails,Elaboration Issues for Library Tasks,Elaboration Order Handling in GNAT
28355 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{23f}@anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{240}
28356 @section Mixing Elaboration Models
28359 So far, we have assumed that the entire program is either compiled
28360 using the dynamic model or static model, ensuring consistency. It
28361 is possible to mix the two models, but rules have to be followed
28362 if this mixing is done to ensure that elaboration checks are not
28365 The basic rule is that
28366 @strong{a unit compiled with the static model cannot
28367 be |withed| by a unit compiled with the dynamic model}.
28368 The reason for this is that in the static model, a unit assumes that
28369 its clients guarantee to use (the equivalent of) pragma
28370 @code{Elaborate_All} so that no elaboration checks are required
28371 in inner subprograms, and this assumption is violated if the
28372 client is compiled with dynamic checks.
28374 The precise rule is as follows. A unit that is compiled with dynamic
28375 checks can only @emph{with} a unit that meets at least one of the
28376 following criteria:
28382 The @emph{with}ed unit is itself compiled with dynamic elaboration
28383 checks (that is with the @code{-gnatE} switch.
28386 The @emph{with}ed unit is an internal GNAT implementation unit from
28387 the System, Interfaces, Ada, or GNAT hierarchies.
28390 The @emph{with}ed unit has pragma Preelaborate or pragma Pure.
28393 The @emph{with}ing unit (that is the client) has an explicit pragma
28394 @code{Elaborate_All} for the @emph{with}ed unit.
28397 If this rule is violated, that is if a unit with dynamic elaboration
28398 checks @emph{with}s a unit that does not meet one of the above four
28399 criteria, then the binder (@code{gnatbind}) will issue a warning
28400 similar to that in the following example:
28403 warning: "x.ads" has dynamic elaboration checks and with's
28404 warning: "y.ads" which has static elaboration checks
28407 These warnings indicate that the rule has been violated, and that as a result
28408 elaboration checks may be missed in the resulting executable file.
28409 This warning may be suppressed using the @code{-ws} binder switch
28410 in the usual manner.
28412 One useful application of this mixing rule is in the case of a subsystem
28413 which does not itself @emph{with} units from the remainder of the
28414 application. In this case, the entire subsystem can be compiled with
28415 dynamic checks to resolve a circularity in the subsystem, while
28416 allowing the main application that uses this subsystem to be compiled
28417 using the more reliable default static model.
28419 @node What to Do If the Default Elaboration Behavior Fails,Elaboration for Indirect Calls,Mixing Elaboration Models,Elaboration Order Handling in GNAT
28420 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{241}@anchor{gnat_ugn/elaboration_order_handling_in_gnat what-to-do-if-the-default-elaboration-behavior-fails}@anchor{23a}
28421 @section What to Do If the Default Elaboration Behavior Fails
28424 If the binder cannot find an acceptable order, it outputs detailed
28425 diagnostics. For example:
28428 error: elaboration circularity detected
28429 info: "proc (body)" must be elaborated before "pack (body)"
28430 info: reason: Elaborate_All probably needed in unit "pack (body)"
28431 info: recompile "pack (body)" with -gnatel
28432 info: for full details
28433 info: "proc (body)"
28434 info: is needed by its spec:
28435 info: "proc (spec)"
28436 info: which is withed by:
28437 info: "pack (body)"
28438 info: "pack (body)" must be elaborated before "proc (body)"
28439 info: reason: pragma Elaborate in unit "proc (body)"
28442 In this case we have a cycle that the binder cannot break. On the one
28443 hand, there is an explicit pragma Elaborate in @code{proc} for
28444 @code{pack}. This means that the body of @code{pack} must be elaborated
28445 before the body of @code{proc}. On the other hand, there is elaboration
28446 code in @code{pack} that calls a subprogram in @code{proc}. This means
28447 that for maximum safety, there should really be a pragma
28448 Elaborate_All in @code{pack} for @code{proc} which would require that
28449 the body of @code{proc} be elaborated before the body of
28450 @code{pack}. Clearly both requirements cannot be satisfied.
28451 Faced with a circularity of this kind, you have three different options.
28457 @emph{Fix the program}
28459 The most desirable option from the point of view of long-term maintenance
28460 is to rearrange the program so that the elaboration problems are avoided.
28461 One useful technique is to place the elaboration code into separate
28462 child packages. Another is to move some of the initialization code to
28463 explicitly called subprograms, where the program controls the order
28464 of initialization explicitly. Although this is the most desirable option,
28465 it may be impractical and involve too much modification, especially in
28466 the case of complex legacy code.
28469 @emph{Perform dynamic checks}
28471 If the compilations are done using the @code{-gnatE}
28472 (dynamic elaboration check) switch, then GNAT behaves in a quite different
28473 manner. Dynamic checks are generated for all calls that could possibly result
28474 in raising an exception. With this switch, the compiler does not generate
28475 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
28476 exactly as specified in the @cite{Ada Reference Manual}.
28477 The binder will generate
28478 an executable program that may or may not raise @code{Program_Error}, and then
28479 it is the programmer's job to ensure that it does not raise an exception. Note
28480 that it is important to compile all units with the switch, it cannot be used
28484 @emph{Suppress checks}
28486 The drawback of dynamic checks is that they generate a
28487 significant overhead at run time, both in space and time. If you
28488 are absolutely sure that your program cannot raise any elaboration
28489 exceptions, and you still want to use the dynamic elaboration model,
28490 then you can use the configuration pragma
28491 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
28492 example this pragma could be placed in the @code{gnat.adc} file.
28495 @emph{Suppress checks selectively}
28497 When you know that certain calls or instantiations in elaboration code cannot
28498 possibly lead to an elaboration error, and the binder nevertheless complains
28499 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
28500 elaboration circularities, it is possible to remove those warnings locally and
28501 obtain a program that will bind. Clearly this can be unsafe, and it is the
28502 responsibility of the programmer to make sure that the resulting program has no
28503 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
28504 used with different granularity to suppress warnings and break elaboration
28511 Place the pragma that names the called subprogram in the declarative part
28512 that contains the call.
28515 Place the pragma in the declarative part, without naming an entity. This
28516 disables warnings on all calls in the corresponding declarative region.
28519 Place the pragma in the package spec that declares the called subprogram,
28520 and name the subprogram. This disables warnings on all elaboration calls to
28524 Place the pragma in the package spec that declares the called subprogram,
28525 without naming any entity. This disables warnings on all elaboration calls to
28526 all subprograms declared in this spec.
28529 Use Pragma Elaborate.
28531 As previously described in section @ref{23b,,Treatment of Pragma Elaborate},
28532 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
28533 that no elaboration checks are required on calls to the designated unit.
28534 There may be cases in which the caller knows that no transitive calls
28535 can occur, so that a @code{pragma Elaborate} will be sufficient in a
28536 case where @code{pragma Elaborate_All} would cause a circularity.
28539 These five cases are listed in order of decreasing safety, and therefore
28540 require increasing programmer care in their application. Consider the
28545 function F1 return Integer;
28550 function F2 return Integer;
28551 function Pure (x : integer) return integer;
28552 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
28553 -- pragma Suppress (Elaboration_Check); -- (4)
28557 package body Pack1 is
28558 function F1 return Integer is
28562 Val : integer := Pack2.Pure (11); -- Elab. call (1)
28565 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
28566 -- pragma Suppress(Elaboration_Check); -- (2)
28568 X1 := Pack2.F2 + 1; -- Elab. call (2)
28573 package body Pack2 is
28574 function F2 return Integer is
28578 function Pure (x : integer) return integer is
28580 return x ** 3 - 3 * x;
28584 with Pack1, Ada.Text_IO;
28587 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
28591 In the absence of any pragmas, an attempt to bind this program produces
28592 the following diagnostics:
28595 error: elaboration circularity detected
28596 info: "pack1 (body)" must be elaborated before "pack1 (body)"
28597 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
28598 info: recompile "pack1 (body)" with -gnatel for full details
28599 info: "pack1 (body)"
28600 info: must be elaborated along with its spec:
28601 info: "pack1 (spec)"
28602 info: which is withed by:
28603 info: "pack2 (body)"
28604 info: which must be elaborated along with its spec:
28605 info: "pack2 (spec)"
28606 info: which is withed by:
28607 info: "pack1 (body)"
28610 The sources of the circularity are the two calls to @code{Pack2.Pure} and
28611 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
28612 F2 is safe, even though F2 calls F1, because the call appears after the
28613 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
28614 remove the warning on the call. It is also possible to use pragma (2)
28615 because there are no other potentially unsafe calls in the block.
28617 The call to @code{Pure} is safe because this function does not depend on the
28618 state of @code{Pack2}. Therefore any call to this function is safe, and it
28619 is correct to place pragma (3) in the corresponding package spec.
28621 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
28622 warnings on all calls to functions declared therein. Note that this is not
28623 necessarily safe, and requires more detailed examination of the subprogram
28624 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
28625 be already elaborated.
28628 It is hard to generalize on which of these four approaches should be
28629 taken. Obviously if it is possible to fix the program so that the default
28630 treatment works, this is preferable, but this may not always be practical.
28631 It is certainly simple enough to use @code{-gnatE}
28632 but the danger in this case is that, even if the GNAT binder
28633 finds a correct elaboration order, it may not always do so,
28634 and certainly a binder from another Ada compiler might not. A
28635 combination of testing and analysis (for which the
28636 information messages generated with the @code{-gnatel}
28637 switch can be useful) must be used to ensure that the program is free
28638 of errors. One switch that is useful in this testing is the
28639 @code{-p} (pessimistic elaboration order) switch for @code{gnatbind}.
28640 Normally the binder tries to find an order that has the best chance
28641 of avoiding elaboration problems. However, if this switch is used, the binder
28642 plays a devil's advocate role, and tries to choose the order that
28643 has the best chance of failing. If your program works even with this
28644 switch, then it has a better chance of being error free, but this is still
28647 For an example of this approach in action, consider the C-tests (executable
28648 tests) from the ACATS suite. If these are compiled and run with the default
28649 treatment, then all but one of them succeed without generating any error
28650 diagnostics from the binder. However, there is one test that fails, and
28651 this is not surprising, because the whole point of this test is to ensure
28652 that the compiler can handle cases where it is impossible to determine
28653 a correct order statically, and it checks that an exception is indeed
28654 raised at run time.
28656 This one test must be compiled and run using the @code{-gnatE}
28657 switch, and then it passes. Alternatively, the entire suite can
28658 be run using this switch. It is never wrong to run with the dynamic
28659 elaboration switch if your code is correct, and we assume that the
28660 C-tests are indeed correct (it is less efficient, but efficiency is
28661 not a factor in running the ACATS tests.)
28663 @node Elaboration for Indirect Calls,Summary of Procedures for Elaboration Control,What to Do If the Default Elaboration Behavior Fails,Elaboration Order Handling in GNAT
28664 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id12}@anchor{242}@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-for-indirect-calls}@anchor{243}
28665 @section Elaboration for Indirect Calls
28668 @geindex Dispatching calls
28670 @geindex Indirect calls
28672 In rare cases, the static elaboration model fails to prevent
28673 dispatching calls to not-yet-elaborated subprograms. In such cases, we
28674 fall back to run-time checks; premature calls to any primitive
28675 operation of a tagged type before the body of the operation has been
28676 elaborated will raise @code{Program_Error}.
28678 Access-to-subprogram types, however, are handled conservatively in many
28679 cases. This was not true in earlier versions of the compiler; you can use
28680 the @code{-gnatd.U} debug switch to revert to the old behavior if the new
28681 conservative behavior causes elaboration cycles. Here, 'conservative' means
28682 that if you do @code{P'Access} during elaboration, the compiler will normally
28683 assume that you might call @code{P} indirectly during elaboration, so it adds an
28684 implicit @code{pragma Elaborate_All} on the library unit containing @code{P}. The
28685 @code{-gnatd.U} switch is safe if you know there are no such calls. If the
28686 program worked before, it will continue to work with @code{-gnatd.U}. But beware
28687 that code modifications such as adding an indirect call can cause erroneous
28688 behavior in the presence of @code{-gnatd.U}.
28690 These implicit Elaborate_All pragmas are not added in all cases, because
28691 they cause elaboration cycles in certain common code patterns. If you want
28692 even more conservative handling of P'Access, you can use the @code{-gnatd.o}
28695 See @code{debug.adb} for documentation on the @code{-gnatd...} debug switches.
28697 @node Summary of Procedures for Elaboration Control,Other Elaboration Order Considerations,Elaboration for Indirect Calls,Elaboration Order Handling in GNAT
28698 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id13}@anchor{244}@anchor{gnat_ugn/elaboration_order_handling_in_gnat summary-of-procedures-for-elaboration-control}@anchor{245}
28699 @section Summary of Procedures for Elaboration Control
28702 @geindex Elaboration control
28704 First, compile your program with the default options, using none of
28705 the special elaboration-control switches. If the binder successfully
28706 binds your program, then you can be confident that, apart from issues
28707 raised by the use of access-to-subprogram types and dynamic dispatching,
28708 the program is free of elaboration errors. If it is important that the
28709 program be portable to other compilers than GNAT, then use the
28711 switch to generate messages about missing @code{Elaborate} or
28712 @code{Elaborate_All} pragmas, and supply the missing pragmas.
28714 If the program fails to bind using the default static elaboration
28715 handling, then you can fix the program to eliminate the binder
28716 message, or recompile the entire program with the
28717 @code{-gnatE} switch to generate dynamic elaboration checks,
28718 and, if you are sure there really are no elaboration problems,
28719 use a global pragma @code{Suppress (Elaboration_Check)}.
28721 @node Other Elaboration Order Considerations,Determining the Chosen Elaboration Order,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
28722 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id14}@anchor{246}@anchor{gnat_ugn/elaboration_order_handling_in_gnat other-elaboration-order-considerations}@anchor{247}
28723 @section Other Elaboration Order Considerations
28726 This section has been entirely concerned with the issue of finding a valid
28727 elaboration order, as defined by the Ada Reference Manual. In a case
28728 where several elaboration orders are valid, the task is to find one
28729 of the possible valid elaboration orders (and the static model in GNAT
28730 will ensure that this is achieved).
28732 The purpose of the elaboration rules in the Ada Reference Manual is to
28733 make sure that no entity is accessed before it has been elaborated. For
28734 a subprogram, this means that the spec and body must have been elaborated
28735 before the subprogram is called. For an object, this means that the object
28736 must have been elaborated before its value is read or written. A violation
28737 of either of these two requirements is an access before elaboration order,
28738 and this section has been all about avoiding such errors.
28740 In the case where more than one order of elaboration is possible, in the
28741 sense that access before elaboration errors are avoided, then any one of
28742 the orders is 'correct' in the sense that it meets the requirements of
28743 the Ada Reference Manual, and no such error occurs.
28745 However, it may be the case for a given program, that there are
28746 constraints on the order of elaboration that come not from consideration
28747 of avoiding elaboration errors, but rather from extra-lingual logic
28748 requirements. Consider this example:
28751 with Init_Constants;
28752 package Constants is
28757 package Init_Constants is
28758 procedure P; --* require a body*
28759 end Init_Constants;
28762 package body Init_Constants is
28763 procedure P is begin null; end;
28767 end Init_Constants;
28771 Z : Integer := Constants.X + Constants.Y;
28775 with Text_IO; use Text_IO;
28778 Put_Line (Calc.Z'Img);
28782 In this example, there is more than one valid order of elaboration. For
28783 example both the following are correct orders:
28786 Init_Constants spec
28789 Init_Constants body
28796 Init_Constants spec
28798 Init_Constants body
28803 There is no language rule to prefer one or the other, both are correct
28804 from an order of elaboration point of view. But the programmatic effects
28805 of the two orders are very different. In the first, the elaboration routine
28806 of @code{Calc} initializes @code{Z} to zero, and then the main program
28807 runs with this value of zero. But in the second order, the elaboration
28808 routine of @code{Calc} runs after the body of Init_Constants has set
28809 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main} runs.
28811 One could perhaps by applying pretty clever non-artificial intelligence
28812 to the situation guess that it is more likely that the second order of
28813 elaboration is the one desired, but there is no formal linguistic reason
28814 to prefer one over the other. In fact in this particular case, GNAT will
28815 prefer the second order, because of the rule that bodies are elaborated
28816 as soon as possible, but it's just luck that this is what was wanted
28817 (if indeed the second order was preferred).
28819 If the program cares about the order of elaboration routines in a case like
28820 this, it is important to specify the order required. In this particular
28821 case, that could have been achieved by adding to the spec of Calc:
28824 pragma Elaborate_All (Constants);
28827 which requires that the body (if any) and spec of @code{Constants},
28828 as well as the body and spec of any unit @emph{with}ed by
28829 @code{Constants} be elaborated before @code{Calc} is elaborated.
28831 Clearly no automatic method can always guess which alternative you require,
28832 and if you are working with legacy code that had constraints of this kind
28833 which were not properly specified by adding @code{Elaborate} or
28834 @code{Elaborate_All} pragmas, then indeed it is possible that two different
28835 compilers can choose different orders.
28837 However, GNAT does attempt to diagnose the common situation where there
28838 are uninitialized variables in the visible part of a package spec, and the
28839 corresponding package body has an elaboration block that directly or
28840 indirectly initializes one or more of these variables. This is the situation
28841 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
28842 a warning that suggests this addition if it detects this situation.
28844 The @code{gnatbind` :switch:`-p` switch may be useful in smoking
28845 out problems. This switch causes bodies to be elaborated as late as possible
28846 instead of as early as possible. In the example above, it would have forced
28847 the choice of the first elaboration order. If you get different results
28848 when using this switch, and particularly if one set of results is right,
28849 and one is wrong as far as you are concerned, it shows that you have some
28850 missing `@w{`}Elaborate} pragmas. For the example above, we have the
28854 $ gnatmake -f -q main
28857 $ gnatmake -f -q main -bargs -p
28862 It is of course quite unlikely that both these results are correct, so
28863 it is up to you in a case like this to investigate the source of the
28864 difference, by looking at the two elaboration orders that are chosen,
28865 and figuring out which is correct, and then adding the necessary
28866 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
28868 @node Determining the Chosen Elaboration Order,,Other Elaboration Order Considerations,Elaboration Order Handling in GNAT
28869 @anchor{gnat_ugn/elaboration_order_handling_in_gnat determining-the-chosen-elaboration-order}@anchor{248}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id15}@anchor{249}
28870 @section Determining the Chosen Elaboration Order
28873 To see the elaboration order that the binder chooses, you can look at
28874 the last part of the file:@cite{b~xxx.adb} binder output file. Here is an example:
28877 System.Soft_Links'Elab_Body;
28879 System.Secondary_Stack'Elab_Body;
28881 System.Exception_Table'Elab_Body;
28883 Ada.Io_Exceptions'Elab_Spec;
28885 Ada.Tags'Elab_Spec;
28886 Ada.Streams'Elab_Spec;
28888 Interfaces.C'Elab_Spec;
28890 System.Finalization_Root'Elab_Spec;
28892 System.Os_Lib'Elab_Body;
28894 System.Finalization_Implementation'Elab_Spec;
28895 System.Finalization_Implementation'Elab_Body;
28897 Ada.Finalization'Elab_Spec;
28899 Ada.Finalization.List_Controller'Elab_Spec;
28901 System.File_Control_Block'Elab_Spec;
28903 System.File_Io'Elab_Body;
28905 Ada.Tags'Elab_Body;
28907 Ada.Text_Io'Elab_Spec;
28908 Ada.Text_Io'Elab_Body;
28912 Here Elab_Spec elaborates the spec
28913 and Elab_Body elaborates the body. The assignments to the @code{E@emph{xx}} flags
28914 flag that the corresponding body is now elaborated.
28916 You can also ask the binder to generate a more
28917 readable list of the elaboration order using the
28918 @code{-l} switch when invoking the binder. Here is
28919 an example of the output generated by this switch:
28925 system.case_util (spec)
28926 system.case_util (body)
28927 system.concat_2 (spec)
28928 system.concat_2 (body)
28929 system.concat_3 (spec)
28930 system.concat_3 (body)
28931 system.htable (spec)
28932 system.parameters (spec)
28933 system.parameters (body)
28935 interfaces.c_streams (spec)
28936 interfaces.c_streams (body)
28937 system.restrictions (spec)
28938 system.restrictions (body)
28939 system.standard_library (spec)
28940 system.exceptions (spec)
28941 system.exceptions (body)
28942 system.storage_elements (spec)
28943 system.storage_elements (body)
28944 system.secondary_stack (spec)
28945 system.stack_checking (spec)
28946 system.stack_checking (body)
28947 system.string_hash (spec)
28948 system.string_hash (body)
28949 system.htable (body)
28950 system.strings (spec)
28951 system.strings (body)
28952 system.traceback (spec)
28953 system.traceback (body)
28954 system.traceback_entries (spec)
28955 system.traceback_entries (body)
28956 ada.exceptions (spec)
28957 ada.exceptions.last_chance_handler (spec)
28958 system.soft_links (spec)
28959 system.soft_links (body)
28960 ada.exceptions.last_chance_handler (body)
28961 system.secondary_stack (body)
28962 system.exception_table (spec)
28963 system.exception_table (body)
28964 ada.io_exceptions (spec)
28967 interfaces.c (spec)
28968 interfaces.c (body)
28969 system.finalization_root (spec)
28970 system.finalization_root (body)
28971 system.memory (spec)
28972 system.memory (body)
28973 system.standard_library (body)
28974 system.os_lib (spec)
28975 system.os_lib (body)
28976 system.unsigned_types (spec)
28977 system.stream_attributes (spec)
28978 system.stream_attributes (body)
28979 system.finalization_implementation (spec)
28980 system.finalization_implementation (body)
28981 ada.finalization (spec)
28982 ada.finalization (body)
28983 ada.finalization.list_controller (spec)
28984 ada.finalization.list_controller (body)
28985 system.file_control_block (spec)
28986 system.file_io (spec)
28987 system.file_io (body)
28988 system.val_uns (spec)
28989 system.val_util (spec)
28990 system.val_util (body)
28991 system.val_uns (body)
28992 system.wch_con (spec)
28993 system.wch_con (body)
28994 system.wch_cnv (spec)
28995 system.wch_jis (spec)
28996 system.wch_jis (body)
28997 system.wch_cnv (body)
28998 system.wch_stw (spec)
28999 system.wch_stw (body)
29001 ada.exceptions (body)
29008 @node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
29009 @anchor{gnat_ugn/inline_assembler inline-assembler}@anchor{10}@anchor{gnat_ugn/inline_assembler doc}@anchor{24a}@anchor{gnat_ugn/inline_assembler id1}@anchor{24b}
29010 @chapter Inline Assembler
29013 @geindex Inline Assembler
29015 If you need to write low-level software that interacts directly
29016 with the hardware, Ada provides two ways to incorporate assembly
29017 language code into your program. First, you can import and invoke
29018 external routines written in assembly language, an Ada feature fully
29019 supported by GNAT. However, for small sections of code it may be simpler
29020 or more efficient to include assembly language statements directly
29021 in your Ada source program, using the facilities of the implementation-defined
29022 package @code{System.Machine_Code}, which incorporates the gcc
29023 Inline Assembler. The Inline Assembler approach offers a number of advantages,
29024 including the following:
29030 No need to use non-Ada tools
29033 Consistent interface over different targets
29036 Automatic usage of the proper calling conventions
29039 Access to Ada constants and variables
29042 Definition of intrinsic routines
29045 Possibility of inlining a subprogram comprising assembler code
29048 Code optimizer can take Inline Assembler code into account
29051 This appendix presents a series of examples to show you how to use
29052 the Inline Assembler. Although it focuses on the Intel x86,
29053 the general approach applies also to other processors.
29054 It is assumed that you are familiar with Ada
29055 and with assembly language programming.
29058 * Basic Assembler Syntax::
29059 * A Simple Example of Inline Assembler::
29060 * Output Variables in Inline Assembler::
29061 * Input Variables in Inline Assembler::
29062 * Inlining Inline Assembler Code::
29063 * Other Asm Functionality::
29067 @node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
29068 @anchor{gnat_ugn/inline_assembler id2}@anchor{24c}@anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{24d}
29069 @section Basic Assembler Syntax
29072 The assembler used by GNAT and gcc is based not on the Intel assembly
29073 language, but rather on a language that descends from the AT&T Unix
29074 assembler @code{as} (and which is often referred to as 'AT&T syntax').
29075 The following table summarizes the main features of @code{as} syntax
29076 and points out the differences from the Intel conventions.
29077 See the gcc @code{as} and @code{gas} (an @code{as} macro
29078 pre-processor) documentation for further information.
29082 @emph{Register names}@w{ }
29084 gcc / @code{as}: Prefix with '%'; for example @code{%eax}@w{ }
29085 Intel: No extra punctuation; for example @code{eax}@w{ }
29093 @emph{Immediate operand}@w{ }
29095 gcc / @code{as}: Prefix with '$'; for example @code{$4}@w{ }
29096 Intel: No extra punctuation; for example @code{4}@w{ }
29104 @emph{Address}@w{ }
29106 gcc / @code{as}: Prefix with '$'; for example @code{$loc}@w{ }
29107 Intel: No extra punctuation; for example @code{loc}@w{ }
29115 @emph{Memory contents}@w{ }
29117 gcc / @code{as}: No extra punctuation; for example @code{loc}@w{ }
29118 Intel: Square brackets; for example @code{[loc]}@w{ }
29126 @emph{Register contents}@w{ }
29128 gcc / @code{as}: Parentheses; for example @code{(%eax)}@w{ }
29129 Intel: Square brackets; for example @code{[eax]}@w{ }
29137 @emph{Hexadecimal numbers}@w{ }
29139 gcc / @code{as}: Leading '0x' (C language syntax); for example @code{0xA0}@w{ }
29140 Intel: Trailing 'h'; for example @code{A0h}@w{ }
29148 @emph{Operand size}@w{ }
29150 gcc / @code{as}: Explicit in op code; for example @code{movw} to move a 16-bit word@w{ }
29151 Intel: Implicit, deduced by assembler; for example @code{mov}@w{ }
29159 @emph{Instruction repetition}@w{ }
29161 gcc / @code{as}: Split into two lines; for example@w{ }
29166 Intel: Keep on one line; for example @code{rep stosl}@w{ }
29174 @emph{Order of operands}@w{ }
29176 gcc / @code{as}: Source first; for example @code{movw $4, %eax}@w{ }
29177 Intel: Destination first; for example @code{mov eax, 4}@w{ }
29183 @node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
29184 @anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{24e}@anchor{gnat_ugn/inline_assembler id3}@anchor{24f}
29185 @section A Simple Example of Inline Assembler
29188 The following example will generate a single assembly language statement,
29189 @code{nop}, which does nothing. Despite its lack of run-time effect,
29190 the example will be useful in illustrating the basics of
29191 the Inline Assembler facility.
29196 with System.Machine_Code; use System.Machine_Code;
29197 procedure Nothing is
29204 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
29205 here it takes one parameter, a @emph{template string} that must be a static
29206 expression and that will form the generated instruction.
29207 @code{Asm} may be regarded as a compile-time procedure that parses
29208 the template string and additional parameters (none here),
29209 from which it generates a sequence of assembly language instructions.
29211 The examples in this chapter will illustrate several of the forms
29212 for invoking @code{Asm}; a complete specification of the syntax
29213 is found in the @code{Machine_Code_Insertions} section of the
29214 @cite{GNAT Reference Manual}.
29216 Under the standard GNAT conventions, the @code{Nothing} procedure
29217 should be in a file named @code{nothing.adb}.
29218 You can build the executable in the usual way:
29227 However, the interesting aspect of this example is not its run-time behavior
29228 but rather the generated assembly code.
29229 To see this output, invoke the compiler as follows:
29234 $ gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
29238 where the options are:
29249 compile only (no bind or link)
29258 generate assembler listing
29265 @item @code{-fomit-frame-pointer}
29267 do not set up separate stack frames
29274 @item @code{-gnatp}
29276 do not add runtime checks
29280 This gives a human-readable assembler version of the code. The resulting
29281 file will have the same name as the Ada source file, but with a @code{.s}
29282 extension. In our example, the file @code{nothing.s} has the following
29288 .file "nothing.adb"
29290 ___gnu_compiled_ada:
29293 .globl __ada_nothing
29305 The assembly code you included is clearly indicated by
29306 the compiler, between the @code{#APP} and @code{#NO_APP}
29307 delimiters. The character before the 'APP' and 'NOAPP'
29308 can differ on different targets. For example, GNU/Linux uses '#APP' while
29309 on NT you will see '/APP'.
29311 If you make a mistake in your assembler code (such as using the
29312 wrong size modifier, or using a wrong operand for the instruction) GNAT
29313 will report this error in a temporary file, which will be deleted when
29314 the compilation is finished. Generating an assembler file will help
29315 in such cases, since you can assemble this file separately using the
29316 @code{as} assembler that comes with gcc.
29318 Assembling the file using the command
29327 will give you error messages whose lines correspond to the assembler
29328 input file, so you can easily find and correct any mistakes you made.
29329 If there are no errors, @code{as} will generate an object file
29330 @code{nothing.out}.
29332 @node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
29333 @anchor{gnat_ugn/inline_assembler id4}@anchor{250}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{251}
29334 @section Output Variables in Inline Assembler
29337 The examples in this section, showing how to access the processor flags,
29338 illustrate how to specify the destination operands for assembly language
29344 with Interfaces; use Interfaces;
29345 with Ada.Text_IO; use Ada.Text_IO;
29346 with System.Machine_Code; use System.Machine_Code;
29347 procedure Get_Flags is
29348 Flags : Unsigned_32;
29351 Asm ("pushfl" & LF & HT & -- push flags on stack
29352 "popl %%eax" & LF & HT & -- load eax with flags
29353 "movl %%eax, %0", -- store flags in variable
29354 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29355 Put_Line ("Flags register:" & Flags'Img);
29360 In order to have a nicely aligned assembly listing, we have separated
29361 multiple assembler statements in the Asm template string with linefeed
29362 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
29363 The resulting section of the assembly output file is:
29371 movl %eax, -40(%ebp)
29376 It would have been legal to write the Asm invocation as:
29381 Asm ("pushfl popl %%eax movl %%eax, %0")
29385 but in the generated assembler file, this would come out as:
29391 pushfl popl %eax movl %eax, -40(%ebp)
29396 which is not so convenient for the human reader.
29398 We use Ada comments
29399 at the end of each line to explain what the assembler instructions
29400 actually do. This is a useful convention.
29402 When writing Inline Assembler instructions, you need to precede each register
29403 and variable name with a percent sign. Since the assembler already requires
29404 a percent sign at the beginning of a register name, you need two consecutive
29405 percent signs for such names in the Asm template string, thus @code{%%eax}.
29406 In the generated assembly code, one of the percent signs will be stripped off.
29408 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
29409 variables: operands you later define using @code{Input} or @code{Output}
29410 parameters to @code{Asm}.
29411 An output variable is illustrated in
29412 the third statement in the Asm template string:
29421 The intent is to store the contents of the eax register in a variable that can
29422 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
29423 necessarily work, since the compiler might optimize by using a register
29424 to hold Flags, and the expansion of the @code{movl} instruction would not be
29425 aware of this optimization. The solution is not to store the result directly
29426 but rather to advise the compiler to choose the correct operand form;
29427 that is the purpose of the @code{%0} output variable.
29429 Information about the output variable is supplied in the @code{Outputs}
29430 parameter to @code{Asm}:
29435 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29439 The output is defined by the @code{Asm_Output} attribute of the target type;
29440 the general format is
29445 Type'Asm_Output (constraint_string, variable_name)
29449 The constraint string directs the compiler how
29450 to store/access the associated variable. In the example
29455 Unsigned_32'Asm_Output ("=m", Flags);
29459 the @code{"m"} (memory) constraint tells the compiler that the variable
29460 @code{Flags} should be stored in a memory variable, thus preventing
29461 the optimizer from keeping it in a register. In contrast,
29466 Unsigned_32'Asm_Output ("=r", Flags);
29470 uses the @code{"r"} (register) constraint, telling the compiler to
29471 store the variable in a register.
29473 If the constraint is preceded by the equal character '=', it tells
29474 the compiler that the variable will be used to store data into it.
29476 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
29477 allowing the optimizer to choose whatever it deems best.
29479 There are a fairly large number of constraints, but the ones that are
29480 most useful (for the Intel x86 processor) are the following:
29485 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
29500 global (i.e., can be stored anywhere)
29572 use one of eax, ebx, ecx or edx
29580 use one of eax, ebx, ecx, edx, esi or edi
29586 The full set of constraints is described in the gcc and @code{as}
29587 documentation; note that it is possible to combine certain constraints
29588 in one constraint string.
29590 You specify the association of an output variable with an assembler operand
29591 through the @code{%@emph{n}} notation, where @emph{n} is a non-negative
29597 Asm ("pushfl" & LF & HT & -- push flags on stack
29598 "popl %%eax" & LF & HT & -- load eax with flags
29599 "movl %%eax, %0", -- store flags in variable
29600 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29604 @code{%0} will be replaced in the expanded code by the appropriate operand,
29606 the compiler decided for the @code{Flags} variable.
29608 In general, you may have any number of output variables:
29614 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
29617 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
29618 of @code{Asm_Output} attributes
29626 Asm ("movl %%eax, %0" & LF & HT &
29627 "movl %%ebx, %1" & LF & HT &
29629 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
29630 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
29631 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
29635 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
29636 in the Ada program.
29638 As a variation on the @code{Get_Flags} example, we can use the constraints
29639 string to direct the compiler to store the eax register into the @code{Flags}
29640 variable, instead of including the store instruction explicitly in the
29641 @code{Asm} template string:
29646 with Interfaces; use Interfaces;
29647 with Ada.Text_IO; use Ada.Text_IO;
29648 with System.Machine_Code; use System.Machine_Code;
29649 procedure Get_Flags_2 is
29650 Flags : Unsigned_32;
29653 Asm ("pushfl" & LF & HT & -- push flags on stack
29654 "popl %%eax", -- save flags in eax
29655 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
29656 Put_Line ("Flags register:" & Flags'Img);
29661 The @code{"a"} constraint tells the compiler that the @code{Flags}
29662 variable will come from the eax register. Here is the resulting code:
29671 movl %eax,-40(%ebp)
29675 The compiler generated the store of eax into Flags after
29676 expanding the assembler code.
29678 Actually, there was no need to pop the flags into the eax register;
29679 more simply, we could just pop the flags directly into the program variable:
29684 with Interfaces; use Interfaces;
29685 with Ada.Text_IO; use Ada.Text_IO;
29686 with System.Machine_Code; use System.Machine_Code;
29687 procedure Get_Flags_3 is
29688 Flags : Unsigned_32;
29691 Asm ("pushfl" & LF & HT & -- push flags on stack
29692 "pop %0", -- save flags in Flags
29693 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29694 Put_Line ("Flags register:" & Flags'Img);
29699 @node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
29700 @anchor{gnat_ugn/inline_assembler id5}@anchor{252}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{253}
29701 @section Input Variables in Inline Assembler
29704 The example in this section illustrates how to specify the source operands
29705 for assembly language statements.
29706 The program simply increments its input value by 1:
29711 with Interfaces; use Interfaces;
29712 with Ada.Text_IO; use Ada.Text_IO;
29713 with System.Machine_Code; use System.Machine_Code;
29714 procedure Increment is
29716 function Incr (Value : Unsigned_32) return Unsigned_32 is
29717 Result : Unsigned_32;
29720 Outputs => Unsigned_32'Asm_Output ("=a", Result),
29721 Inputs => Unsigned_32'Asm_Input ("a", Value));
29725 Value : Unsigned_32;
29729 Put_Line ("Value before is" & Value'Img);
29730 Value := Incr (Value);
29731 Put_Line ("Value after is" & Value'Img);
29736 The @code{Outputs} parameter to @code{Asm} specifies
29737 that the result will be in the eax register and that it is to be stored
29738 in the @code{Result} variable.
29740 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
29741 but with an @code{Asm_Input} attribute.
29742 The @code{"="} constraint, indicating an output value, is not present.
29744 You can have multiple input variables, in the same way that you can have more
29745 than one output variable.
29747 The parameter count (%0, %1) etc, still starts at the first output statement,
29748 and continues with the input statements.
29750 Just as the @code{Outputs} parameter causes the register to be stored into the
29751 target variable after execution of the assembler statements, so does the
29752 @code{Inputs} parameter cause its variable to be loaded into the register
29753 before execution of the assembler statements.
29755 Thus the effect of the @code{Asm} invocation is:
29761 load the 32-bit value of @code{Value} into eax
29764 execute the @code{incl %eax} instruction
29767 store the contents of eax into the @code{Result} variable
29770 The resulting assembler file (with @code{-O2} optimization) contains:
29775 _increment__incr.1:
29788 @node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
29789 @anchor{gnat_ugn/inline_assembler id6}@anchor{254}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{255}
29790 @section Inlining Inline Assembler Code
29793 For a short subprogram such as the @code{Incr} function in the previous
29794 section, the overhead of the call and return (creating / deleting the stack
29795 frame) can be significant, compared to the amount of code in the subprogram
29796 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
29797 which directs the compiler to expand invocations of the subprogram at the
29798 point(s) of call, instead of setting up a stack frame for out-of-line calls.
29799 Here is the resulting program:
29804 with Interfaces; use Interfaces;
29805 with Ada.Text_IO; use Ada.Text_IO;
29806 with System.Machine_Code; use System.Machine_Code;
29807 procedure Increment_2 is
29809 function Incr (Value : Unsigned_32) return Unsigned_32 is
29810 Result : Unsigned_32;
29813 Outputs => Unsigned_32'Asm_Output ("=a", Result),
29814 Inputs => Unsigned_32'Asm_Input ("a", Value));
29817 pragma Inline (Increment);
29819 Value : Unsigned_32;
29823 Put_Line ("Value before is" & Value'Img);
29824 Value := Increment (Value);
29825 Put_Line ("Value after is" & Value'Img);
29830 Compile the program with both optimization (@code{-O2}) and inlining
29831 (@code{-gnatn}) enabled.
29833 The @code{Incr} function is still compiled as usual, but at the
29834 point in @code{Increment} where our function used to be called:
29840 call _increment__incr.1
29844 the code for the function body directly appears:
29857 thus saving the overhead of stack frame setup and an out-of-line call.
29859 @node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
29860 @anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{256}@anchor{gnat_ugn/inline_assembler id7}@anchor{257}
29861 @section Other @code{Asm} Functionality
29864 This section describes two important parameters to the @code{Asm}
29865 procedure: @code{Clobber}, which identifies register usage;
29866 and @code{Volatile}, which inhibits unwanted optimizations.
29869 * The Clobber Parameter::
29870 * The Volatile Parameter::
29874 @node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
29875 @anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{258}@anchor{gnat_ugn/inline_assembler id8}@anchor{259}
29876 @subsection The @code{Clobber} Parameter
29879 One of the dangers of intermixing assembly language and a compiled language
29880 such as Ada is that the compiler needs to be aware of which registers are
29881 being used by the assembly code. In some cases, such as the earlier examples,
29882 the constraint string is sufficient to indicate register usage (e.g.,
29884 the eax register). But more generally, the compiler needs an explicit
29885 identification of the registers that are used by the Inline Assembly
29888 Using a register that the compiler doesn't know about
29889 could be a side effect of an instruction (like @code{mull}
29890 storing its result in both eax and edx).
29891 It can also arise from explicit register usage in your
29892 assembly code; for example:
29897 Asm ("movl %0, %%ebx" & LF & HT &
29899 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29900 Inputs => Unsigned_32'Asm_Input ("g", Var_In));
29904 where the compiler (since it does not analyze the @code{Asm} template string)
29905 does not know you are using the ebx register.
29907 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
29908 to identify the registers that will be used by your assembly code:
29913 Asm ("movl %0, %%ebx" & LF & HT &
29915 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29916 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
29921 The Clobber parameter is a static string expression specifying the
29922 register(s) you are using. Note that register names are @emph{not} prefixed
29923 by a percent sign. Also, if more than one register is used then their names
29924 are separated by commas; e.g., @code{"eax, ebx"}
29926 The @code{Clobber} parameter has several additional uses:
29932 Use 'register' name @code{cc} to indicate that flags might have changed
29935 Use 'register' name @code{memory} if you changed a memory location
29938 @node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
29939 @anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{25a}@anchor{gnat_ugn/inline_assembler id9}@anchor{25b}
29940 @subsection The @code{Volatile} Parameter
29943 @geindex Volatile parameter
29945 Compiler optimizations in the presence of Inline Assembler may sometimes have
29946 unwanted effects. For example, when an @code{Asm} invocation with an input
29947 variable is inside a loop, the compiler might move the loading of the input
29948 variable outside the loop, regarding it as a one-time initialization.
29950 If this effect is not desired, you can disable such optimizations by setting
29951 the @code{Volatile} parameter to @code{True}; for example:
29956 Asm ("movl %0, %%ebx" & LF & HT &
29958 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29959 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
29965 By default, @code{Volatile} is set to @code{False} unless there is no
29966 @code{Outputs} parameter.
29968 Although setting @code{Volatile} to @code{True} prevents unwanted
29969 optimizations, it will also disable other optimizations that might be
29970 important for efficiency. In general, you should set @code{Volatile}
29971 to @code{True} only if the compiler's optimizations have created
29974 @node GNU Free Documentation License,Index,Inline Assembler,Top
29975 @anchor{share/gnu_free_documentation_license gnu-fdl}@anchor{1}@anchor{share/gnu_free_documentation_license doc}@anchor{25c}@anchor{share/gnu_free_documentation_license gnu-free-documentation-license}@anchor{25d}
29976 @chapter GNU Free Documentation License
29979 Version 1.3, 3 November 2008
29981 Copyright 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc
29982 @indicateurl{http://fsf.org/}
29984 Everyone is permitted to copy and distribute verbatim copies of this
29985 license document, but changing it is not allowed.
29989 The purpose of this License is to make a manual, textbook, or other
29990 functional and useful document "free" in the sense of freedom: to
29991 assure everyone the effective freedom to copy and redistribute it,
29992 with or without modifying it, either commercially or noncommercially.
29993 Secondarily, this License preserves for the author and publisher a way
29994 to get credit for their work, while not being considered responsible
29995 for modifications made by others.
29997 This License is a kind of "copyleft", which means that derivative
29998 works of the document must themselves be free in the same sense. It
29999 complements the GNU General Public License, which is a copyleft
30000 license designed for free software.
30002 We have designed this License in order to use it for manuals for free
30003 software, because free software needs free documentation: a free
30004 program should come with manuals providing the same freedoms that the
30005 software does. But this License is not limited to software manuals;
30006 it can be used for any textual work, regardless of subject matter or
30007 whether it is published as a printed book. We recommend this License
30008 principally for works whose purpose is instruction or reference.
30010 @strong{1. APPLICABILITY AND DEFINITIONS}
30012 This License applies to any manual or other work, in any medium, that
30013 contains a notice placed by the copyright holder saying it can be
30014 distributed under the terms of this License. Such a notice grants a
30015 world-wide, royalty-free license, unlimited in duration, to use that
30016 work under the conditions stated herein. The @strong{Document}, below,
30017 refers to any such manual or work. Any member of the public is a
30018 licensee, and is addressed as "@strong{you}". You accept the license if you
30019 copy, modify or distribute the work in a way requiring permission
30020 under copyright law.
30022 A "@strong{Modified Version}" of the Document means any work containing the
30023 Document or a portion of it, either copied verbatim, or with
30024 modifications and/or translated into another language.
30026 A "@strong{Secondary Section}" is a named appendix or a front-matter section of
30027 the Document that deals exclusively with the relationship of the
30028 publishers or authors of the Document to the Document's overall subject
30029 (or to related matters) and contains nothing that could fall directly
30030 within that overall subject. (Thus, if the Document is in part a
30031 textbook of mathematics, a Secondary Section may not explain any
30032 mathematics.) The relationship could be a matter of historical
30033 connection with the subject or with related matters, or of legal,
30034 commercial, philosophical, ethical or political position regarding
30037 The "@strong{Invariant Sections}" are certain Secondary Sections whose titles
30038 are designated, as being those of Invariant Sections, in the notice
30039 that says that the Document is released under this License. If a
30040 section does not fit the above definition of Secondary then it is not
30041 allowed to be designated as Invariant. The Document may contain zero
30042 Invariant Sections. If the Document does not identify any Invariant
30043 Sections then there are none.
30045 The "@strong{Cover Texts}" are certain short passages of text that are listed,
30046 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
30047 the Document is released under this License. A Front-Cover Text may
30048 be at most 5 words, and a Back-Cover Text may be at most 25 words.
30050 A "@strong{Transparent}" copy of the Document means a machine-readable copy,
30051 represented in a format whose specification is available to the
30052 general public, that is suitable for revising the document
30053 straightforwardly with generic text editors or (for images composed of
30054 pixels) generic paint programs or (for drawings) some widely available
30055 drawing editor, and that is suitable for input to text formatters or
30056 for automatic translation to a variety of formats suitable for input
30057 to text formatters. A copy made in an otherwise Transparent file
30058 format whose markup, or absence of markup, has been arranged to thwart
30059 or discourage subsequent modification by readers is not Transparent.
30060 An image format is not Transparent if used for any substantial amount
30061 of text. A copy that is not "Transparent" is called @strong{Opaque}.
30063 Examples of suitable formats for Transparent copies include plain
30064 ASCII without markup, Texinfo input format, LaTeX input format, SGML
30065 or XML using a publicly available DTD, and standard-conforming simple
30066 HTML, PostScript or PDF designed for human modification. Examples of
30067 transparent image formats include PNG, XCF and JPG. Opaque formats
30068 include proprietary formats that can be read and edited only by
30069 proprietary word processors, SGML or XML for which the DTD and/or
30070 processing tools are not generally available, and the
30071 machine-generated HTML, PostScript or PDF produced by some word
30072 processors for output purposes only.
30074 The "@strong{Title Page}" means, for a printed book, the title page itself,
30075 plus such following pages as are needed to hold, legibly, the material
30076 this License requires to appear in the title page. For works in
30077 formats which do not have any title page as such, "Title Page" means
30078 the text near the most prominent appearance of the work's title,
30079 preceding the beginning of the body of the text.
30081 The "@strong{publisher}" means any person or entity that distributes
30082 copies of the Document to the public.
30084 A section "@strong{Entitled XYZ}" means a named subunit of the Document whose
30085 title either is precisely XYZ or contains XYZ in parentheses following
30086 text that translates XYZ in another language. (Here XYZ stands for a
30087 specific section name mentioned below, such as "@strong{Acknowledgements}",
30088 "@strong{Dedications}", "@strong{Endorsements}", or "@strong{History}".)
30089 To "@strong{Preserve the Title}"
30090 of such a section when you modify the Document means that it remains a
30091 section "Entitled XYZ" according to this definition.
30093 The Document may include Warranty Disclaimers next to the notice which
30094 states that this License applies to the Document. These Warranty
30095 Disclaimers are considered to be included by reference in this
30096 License, but only as regards disclaiming warranties: any other
30097 implication that these Warranty Disclaimers may have is void and has
30098 no effect on the meaning of this License.
30100 @strong{2. VERBATIM COPYING}
30102 You may copy and distribute the Document in any medium, either
30103 commercially or noncommercially, provided that this License, the
30104 copyright notices, and the license notice saying this License applies
30105 to the Document are reproduced in all copies, and that you add no other
30106 conditions whatsoever to those of this License. You may not use
30107 technical measures to obstruct or control the reading or further
30108 copying of the copies you make or distribute. However, you may accept
30109 compensation in exchange for copies. If you distribute a large enough
30110 number of copies you must also follow the conditions in section 3.
30112 You may also lend copies, under the same conditions stated above, and
30113 you may publicly display copies.
30115 @strong{3. COPYING IN QUANTITY}
30117 If you publish printed copies (or copies in media that commonly have
30118 printed covers) of the Document, numbering more than 100, and the
30119 Document's license notice requires Cover Texts, you must enclose the
30120 copies in covers that carry, clearly and legibly, all these Cover
30121 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
30122 the back cover. Both covers must also clearly and legibly identify
30123 you as the publisher of these copies. The front cover must present
30124 the full title with all words of the title equally prominent and
30125 visible. You may add other material on the covers in addition.
30126 Copying with changes limited to the covers, as long as they preserve
30127 the title of the Document and satisfy these conditions, can be treated
30128 as verbatim copying in other respects.
30130 If the required texts for either cover are too voluminous to fit
30131 legibly, you should put the first ones listed (as many as fit
30132 reasonably) on the actual cover, and continue the rest onto adjacent
30135 If you publish or distribute Opaque copies of the Document numbering
30136 more than 100, you must either include a machine-readable Transparent
30137 copy along with each Opaque copy, or state in or with each Opaque copy
30138 a computer-network location from which the general network-using
30139 public has access to download using public-standard network protocols
30140 a complete Transparent copy of the Document, free of added material.
30141 If you use the latter option, you must take reasonably prudent steps,
30142 when you begin distribution of Opaque copies in quantity, to ensure
30143 that this Transparent copy will remain thus accessible at the stated
30144 location until at least one year after the last time you distribute an
30145 Opaque copy (directly or through your agents or retailers) of that
30146 edition to the public.
30148 It is requested, but not required, that you contact the authors of the
30149 Document well before redistributing any large number of copies, to give
30150 them a chance to provide you with an updated version of the Document.
30152 @strong{4. MODIFICATIONS}
30154 You may copy and distribute a Modified Version of the Document under
30155 the conditions of sections 2 and 3 above, provided that you release
30156 the Modified Version under precisely this License, with the Modified
30157 Version filling the role of the Document, thus licensing distribution
30158 and modification of the Modified Version to whoever possesses a copy
30159 of it. In addition, you must do these things in the Modified Version:
30165 Use in the Title Page (and on the covers, if any) a title distinct
30166 from that of the Document, and from those of previous versions
30167 (which should, if there were any, be listed in the History section
30168 of the Document). You may use the same title as a previous version
30169 if the original publisher of that version gives permission.
30172 List on the Title Page, as authors, one or more persons or entities
30173 responsible for authorship of the modifications in the Modified
30174 Version, together with at least five of the principal authors of the
30175 Document (all of its principal authors, if it has fewer than five),
30176 unless they release you from this requirement.
30179 State on the Title page the name of the publisher of the
30180 Modified Version, as the publisher.
30183 Preserve all the copyright notices of the Document.
30186 Add an appropriate copyright notice for your modifications
30187 adjacent to the other copyright notices.
30190 Include, immediately after the copyright notices, a license notice
30191 giving the public permission to use the Modified Version under the
30192 terms of this License, in the form shown in the Addendum below.
30195 Preserve in that license notice the full lists of Invariant Sections
30196 and required Cover Texts given in the Document's license notice.
30199 Include an unaltered copy of this License.
30202 Preserve the section Entitled "History", Preserve its Title, and add
30203 to it an item stating at least the title, year, new authors, and
30204 publisher of the Modified Version as given on the Title Page. If
30205 there is no section Entitled "History" in the Document, create one
30206 stating the title, year, authors, and publisher of the Document as
30207 given on its Title Page, then add an item describing the Modified
30208 Version as stated in the previous sentence.
30211 Preserve the network location, if any, given in the Document for
30212 public access to a Transparent copy of the Document, and likewise
30213 the network locations given in the Document for previous versions
30214 it was based on. These may be placed in the "History" section.
30215 You may omit a network location for a work that was published at
30216 least four years before the Document itself, or if the original
30217 publisher of the version it refers to gives permission.
30220 For any section Entitled "Acknowledgements" or "Dedications",
30221 Preserve the Title of the section, and preserve in the section all
30222 the substance and tone of each of the contributor acknowledgements
30223 and/or dedications given therein.
30226 Preserve all the Invariant Sections of the Document,
30227 unaltered in their text and in their titles. Section numbers
30228 or the equivalent are not considered part of the section titles.
30231 Delete any section Entitled "Endorsements". Such a section
30232 may not be included in the Modified Version.
30235 Do not retitle any existing section to be Entitled "Endorsements"
30236 or to conflict in title with any Invariant Section.
30239 Preserve any Warranty Disclaimers.
30242 If the Modified Version includes new front-matter sections or
30243 appendices that qualify as Secondary Sections and contain no material
30244 copied from the Document, you may at your option designate some or all
30245 of these sections as invariant. To do this, add their titles to the
30246 list of Invariant Sections in the Modified Version's license notice.
30247 These titles must be distinct from any other section titles.
30249 You may add a section Entitled "Endorsements", provided it contains
30250 nothing but endorsements of your Modified Version by various
30251 parties---for example, statements of peer review or that the text has
30252 been approved by an organization as the authoritative definition of a
30255 You may add a passage of up to five words as a Front-Cover Text, and a
30256 passage of up to 25 words as a Back-Cover Text, to the end of the list
30257 of Cover Texts in the Modified Version. Only one passage of
30258 Front-Cover Text and one of Back-Cover Text may be added by (or
30259 through arrangements made by) any one entity. If the Document already
30260 includes a cover text for the same cover, previously added by you or
30261 by arrangement made by the same entity you are acting on behalf of,
30262 you may not add another; but you may replace the old one, on explicit
30263 permission from the previous publisher that added the old one.
30265 The author(s) and publisher(s) of the Document do not by this License
30266 give permission to use their names for publicity for or to assert or
30267 imply endorsement of any Modified Version.
30269 @strong{5. COMBINING DOCUMENTS}
30271 You may combine the Document with other documents released under this
30272 License, under the terms defined in section 4 above for modified
30273 versions, provided that you include in the combination all of the
30274 Invariant Sections of all of the original documents, unmodified, and
30275 list them all as Invariant Sections of your combined work in its
30276 license notice, and that you preserve all their Warranty Disclaimers.
30278 The combined work need only contain one copy of this License, and
30279 multiple identical Invariant Sections may be replaced with a single
30280 copy. If there are multiple Invariant Sections with the same name but
30281 different contents, make the title of each such section unique by
30282 adding at the end of it, in parentheses, the name of the original
30283 author or publisher of that section if known, or else a unique number.
30284 Make the same adjustment to the section titles in the list of
30285 Invariant Sections in the license notice of the combined work.
30287 In the combination, you must combine any sections Entitled "History"
30288 in the various original documents, forming one section Entitled
30289 "History"; likewise combine any sections Entitled "Acknowledgements",
30290 and any sections Entitled "Dedications". You must delete all sections
30291 Entitled "Endorsements".
30293 @strong{6. COLLECTIONS OF DOCUMENTS}
30295 You may make a collection consisting of the Document and other documents
30296 released under this License, and replace the individual copies of this
30297 License in the various documents with a single copy that is included in
30298 the collection, provided that you follow the rules of this License for
30299 verbatim copying of each of the documents in all other respects.
30301 You may extract a single document from such a collection, and distribute
30302 it individually under this License, provided you insert a copy of this
30303 License into the extracted document, and follow this License in all
30304 other respects regarding verbatim copying of that document.
30306 @strong{7. AGGREGATION WITH INDEPENDENT WORKS}
30308 A compilation of the Document or its derivatives with other separate
30309 and independent documents or works, in or on a volume of a storage or
30310 distribution medium, is called an "aggregate" if the copyright
30311 resulting from the compilation is not used to limit the legal rights
30312 of the compilation's users beyond what the individual works permit.
30313 When the Document is included in an aggregate, this License does not
30314 apply to the other works in the aggregate which are not themselves
30315 derivative works of the Document.
30317 If the Cover Text requirement of section 3 is applicable to these
30318 copies of the Document, then if the Document is less than one half of
30319 the entire aggregate, the Document's Cover Texts may be placed on
30320 covers that bracket the Document within the aggregate, or the
30321 electronic equivalent of covers if the Document is in electronic form.
30322 Otherwise they must appear on printed covers that bracket the whole
30325 @strong{8. TRANSLATION}
30327 Translation is considered a kind of modification, so you may
30328 distribute translations of the Document under the terms of section 4.
30329 Replacing Invariant Sections with translations requires special
30330 permission from their copyright holders, but you may include
30331 translations of some or all Invariant Sections in addition to the
30332 original versions of these Invariant Sections. You may include a
30333 translation of this License, and all the license notices in the
30334 Document, and any Warranty Disclaimers, provided that you also include
30335 the original English version of this License and the original versions
30336 of those notices and disclaimers. In case of a disagreement between
30337 the translation and the original version of this License or a notice
30338 or disclaimer, the original version will prevail.
30340 If a section in the Document is Entitled "Acknowledgements",
30341 "Dedications", or "History", the requirement (section 4) to Preserve
30342 its Title (section 1) will typically require changing the actual
30345 @strong{9. TERMINATION}
30347 You may not copy, modify, sublicense, or distribute the Document
30348 except as expressly provided under this License. Any attempt
30349 otherwise to copy, modify, sublicense, or distribute it is void, and
30350 will automatically terminate your rights under this License.
30352 However, if you cease all violation of this License, then your license
30353 from a particular copyright holder is reinstated (a) provisionally,
30354 unless and until the copyright holder explicitly and finally
30355 terminates your license, and (b) permanently, if the copyright holder
30356 fails to notify you of the violation by some reasonable means prior to
30357 60 days after the cessation.
30359 Moreover, your license from a particular copyright holder is
30360 reinstated permanently if the copyright holder notifies you of the
30361 violation by some reasonable means, this is the first time you have
30362 received notice of violation of this License (for any work) from that
30363 copyright holder, and you cure the violation prior to 30 days after
30364 your receipt of the notice.
30366 Termination of your rights under this section does not terminate the
30367 licenses of parties who have received copies or rights from you under
30368 this License. If your rights have been terminated and not permanently
30369 reinstated, receipt of a copy of some or all of the same material does
30370 not give you any rights to use it.
30372 @strong{10. FUTURE REVISIONS OF THIS LICENSE}
30374 The Free Software Foundation may publish new, revised versions
30375 of the GNU Free Documentation License from time to time. Such new
30376 versions will be similar in spirit to the present version, but may
30377 differ in detail to address new problems or concerns. See
30378 @indicateurl{http://www.gnu.org/copyleft/}.
30380 Each version of the License is given a distinguishing version number.
30381 If the Document specifies that a particular numbered version of this
30382 License "or any later version" applies to it, you have the option of
30383 following the terms and conditions either of that specified version or
30384 of any later version that has been published (not as a draft) by the
30385 Free Software Foundation. If the Document does not specify a version
30386 number of this License, you may choose any version ever published (not
30387 as a draft) by the Free Software Foundation. If the Document
30388 specifies that a proxy can decide which future versions of this
30389 License can be used, that proxy's public statement of acceptance of a
30390 version permanently authorizes you to choose that version for the
30393 @strong{11. RELICENSING}
30395 "Massive Multiauthor Collaboration Site" (or "MMC Site") means any
30396 World Wide Web server that publishes copyrightable works and also
30397 provides prominent facilities for anybody to edit those works. A
30398 public wiki that anybody can edit is an example of such a server. A
30399 "Massive Multiauthor Collaboration" (or "MMC") contained in the
30400 site means any set of copyrightable works thus published on the MMC
30403 "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0
30404 license published by Creative Commons Corporation, a not-for-profit
30405 corporation with a principal place of business in San Francisco,
30406 California, as well as future copyleft versions of that license
30407 published by that same organization.
30409 "Incorporate" means to publish or republish a Document, in whole or
30410 in part, as part of another Document.
30412 An MMC is "eligible for relicensing" if it is licensed under this
30413 License, and if all works that were first published under this License
30414 somewhere other than this MMC, and subsequently incorporated in whole
30415 or in part into the MMC, (1) had no cover texts or invariant sections,
30416 and (2) were thus incorporated prior to November 1, 2008.
30418 The operator of an MMC Site may republish an MMC contained in the site
30419 under CC-BY-SA on the same site at any time before August 1, 2009,
30420 provided the MMC is eligible for relicensing.
30422 @strong{ADDENDUM: How to use this License for your documents}
30424 To use this License in a document you have written, include a copy of
30425 the License in the document and put the following copyright and
30426 license notices just after the title page:
30430 Copyright © YEAR YOUR NAME.
30431 Permission is granted to copy, distribute and/or modify this document
30432 under the terms of the GNU Free Documentation License, Version 1.3
30433 or any later version published by the Free Software Foundation;
30434 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
30435 A copy of the license is included in the section entitled "GNU
30436 Free Documentation License".
30439 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
30440 replace the "with ... Texts." line with this:
30444 with the Invariant Sections being LIST THEIR TITLES, with the
30445 Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
30448 If you have Invariant Sections without Cover Texts, or some other
30449 combination of the three, merge those two alternatives to suit the
30452 If your document contains nontrivial examples of program code, we
30453 recommend releasing these examples in parallel under your choice of
30454 free software license, such as the GNU General Public License,
30455 to permit their use in free software.
30457 @node Index,,GNU Free Documentation License,Top
30464 @anchor{gnat_ugn/gnat_utility_programs switches-related-to-project-files}@w{ }