1 \input texinfo @c -*-texinfo-*-
3 @setfilename gnat_ugn.info
4 @documentencoding UTF-8
6 @*Generated by Sphinx 5.2.3.@*
8 @settitle GNAT User's Guide for Native Platforms
13 @dircategory GNU Ada Tools
15 * gnat_ugn: (gnat_ugn.info). gnat_ugn
22 GNAT User's Guide for Native Platforms , Jun 16, 2023
26 Copyright @copyright{} 2008-2023, Free Software Foundation
32 @title GNAT User's Guide for Native Platforms
37 @c %** start of user preamble
39 @c %** end of user preamble
43 @top GNAT User's Guide for Native Platforms
48 @anchor{gnat_ugn doc}@anchor{0}
49 `GNAT, The GNU Ada Development Environment'
52 @include gcc-common.texi
53 GCC version @value{version-GCC}@*
56 Permission is granted to copy, distribute and/or modify this document
57 under the terms of the GNU Free Documentation License, Version 1.3 or
58 any later version published by the Free Software Foundation; with no
59 Invariant Sections, with the Front-Cover Texts being
60 “GNAT User’s Guide for Native Platforms”,
61 and with no Back-Cover Texts. A copy of the license is
62 included in the section entitled @ref{1,,GNU Free Documentation License}.
66 * Getting Started with GNAT::
67 * The GNAT Compilation Model::
68 * Building Executable Programs with GNAT::
69 * GNAT Utility Programs::
70 * GNAT and Program Execution::
71 * Platform-Specific Information::
72 * Example of Binder Output File::
73 * Elaboration Order Handling in GNAT::
75 * GNU Free Documentation License::
79 --- The Detailed Node Listing ---
83 * What This Guide Contains::
84 * What You Should Know before Reading This Guide::
85 * Related Information::
88 Getting Started with GNAT
90 * System Requirements::
92 * Running a Simple Ada Program::
93 * Running a Program with Multiple Units::
95 The GNAT Compilation Model
97 * Source Representation::
98 * Foreign Language Representation::
99 * File Naming Topics and Utilities::
100 * Configuration Pragmas::
101 * Generating Object Files::
102 * Source Dependencies::
103 * The Ada Library Information Files::
104 * Binding an Ada Program::
105 * GNAT and Libraries::
106 * Conditional Compilation::
107 * Mixed Language Programming::
108 * GNAT and Other Compilation Models::
109 * Using GNAT Files with External Tools::
111 Foreign Language Representation
114 * Other 8-Bit Codes::
115 * Wide_Character Encodings::
116 * Wide_Wide_Character Encodings::
118 File Naming Topics and Utilities
120 * File Naming Rules::
121 * Using Other File Names::
122 * Alternative File Naming Schemes::
123 * Handling Arbitrary File Naming Conventions with gnatname::
124 * File Name Krunching with gnatkr::
125 * Renaming Files with gnatchop::
127 Handling Arbitrary File Naming Conventions with gnatname
129 * Arbitrary File Naming Conventions::
131 * Switches for gnatname::
132 * Examples of gnatname Usage::
134 File Name Krunching with gnatkr
139 * Examples of gnatkr Usage::
141 Renaming Files with gnatchop
143 * Handling Files with Multiple Units::
144 * Operating gnatchop in Compilation Mode::
145 * Command Line for gnatchop::
146 * Switches for gnatchop::
147 * Examples of gnatchop Usage::
149 Configuration Pragmas
151 * Handling of Configuration Pragmas::
152 * The Configuration Pragmas Files::
156 * Introduction to Libraries in GNAT::
157 * General Ada Libraries::
158 * Stand-alone Ada Libraries::
159 * Rebuilding the GNAT Run-Time Library::
161 General Ada Libraries
163 * Building a library::
164 * Installing a library::
167 Stand-alone Ada Libraries
169 * Introduction to Stand-alone Libraries::
170 * Building a Stand-alone Library::
171 * Creating a Stand-alone Library to be used in a non-Ada context::
172 * Restrictions in Stand-alone Libraries::
174 Conditional Compilation
176 * Modeling Conditional Compilation in Ada::
177 * Preprocessing with gnatprep::
178 * Integrated Preprocessing::
180 Modeling Conditional Compilation in Ada
182 * Use of Boolean Constants::
183 * Debugging - A Special Case::
184 * Conditionalizing Declarations::
185 * Use of Alternative Implementations::
188 Preprocessing with gnatprep
190 * Preprocessing Symbols::
192 * Switches for gnatprep::
193 * Form of Definitions File::
194 * Form of Input Text for gnatprep::
196 Mixed Language Programming
199 * Calling Conventions::
200 * Building Mixed Ada and C++ Programs::
201 * Partition-Wide Settings::
202 * Generating Ada Bindings for C and C++ headers::
203 * Generating C Headers for Ada Specifications::
205 Building Mixed Ada and C++ Programs
207 * Interfacing to C++::
208 * Linking a Mixed C++ & Ada Program::
210 * Interfacing with C++ constructors::
211 * Interfacing with C++ at the Class Level::
213 Generating Ada Bindings for C and C++ headers
215 * Running the Binding Generator::
216 * Generating Bindings for C++ Headers::
219 Generating C Headers for Ada Specifications
221 * Running the C Header Generator::
223 GNAT and Other Compilation Models
225 * Comparison between GNAT and C/C++ Compilation Models::
226 * Comparison between GNAT and Conventional Ada Library Models::
228 Using GNAT Files with External Tools
230 * Using Other Utility Programs with GNAT::
231 * The External Symbol Naming Scheme of GNAT::
233 Building Executable Programs with GNAT
235 * Building with gnatmake::
236 * Compiling with gcc::
237 * Compiler Switches::
239 * Binding with gnatbind::
240 * Linking with gnatlink::
241 * Using the GNU make Utility::
243 Building with gnatmake
246 * Switches for gnatmake::
247 * Mode Switches for gnatmake::
248 * Notes on the Command Line::
249 * How gnatmake Works::
250 * Examples of gnatmake Usage::
254 * Compiling Programs::
255 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL.
256 * Order of Compilation Issues::
261 * Alphabetical List of All Switches::
262 * Output and Error Message Control::
263 * Warning Message Control::
264 * Debugging and Assertion Control::
265 * Validity Checking::
268 * Using gcc for Syntax Checking::
269 * Using gcc for Semantic Checking::
270 * Compiling Different Versions of Ada::
271 * Character Set Control::
272 * File Naming Control::
273 * Subprogram Inlining Control::
274 * Auxiliary Output Control::
275 * Debugging Control::
276 * Exception Handling Control::
277 * Units to Sources Mapping Files::
278 * Code Generation Control::
280 Binding with gnatbind
283 * Switches for gnatbind::
284 * Command-Line Access::
285 * Search Paths for gnatbind::
286 * Examples of gnatbind Usage::
288 Switches for gnatbind
290 * Consistency-Checking Modes::
291 * Binder Error Message Control::
292 * Elaboration Control::
294 * Dynamic Allocation Control::
295 * Binding with Non-Ada Main Programs::
296 * Binding Programs with No Main Subprogram::
298 Linking with gnatlink
301 * Switches for gnatlink::
303 Using the GNU make Utility
305 * Using gnatmake in a Makefile::
306 * Automatically Creating a List of Directories::
307 * Generating the Command Line Switches::
308 * Overcoming Command Line Length Limits::
310 GNAT Utility Programs
312 * The File Cleanup Utility gnatclean::
313 * The GNAT Library Browser gnatls::
315 The File Cleanup Utility gnatclean
317 * Running gnatclean::
318 * Switches for gnatclean::
320 The GNAT Library Browser gnatls
323 * Switches for gnatls::
324 * Example of gnatls Usage::
326 GNAT and Program Execution
328 * Running and Debugging Ada Programs::
330 * Improving Performance::
331 * Overflow Check Handling in GNAT::
332 * Performing Dimensionality Analysis in GNAT::
333 * Stack Related Facilities::
334 * Memory Management Issues::
336 Running and Debugging Ada Programs
338 * The GNAT Debugger GDB::
340 * Introduction to GDB Commands::
341 * Using Ada Expressions::
342 * Calling User-Defined Subprograms::
343 * Using the next Command in a Function::
344 * Stopping When Ada Exceptions Are Raised::
346 * Debugging Generic Units::
347 * Remote Debugging with gdbserver::
348 * GNAT Abnormal Termination or Failure to Terminate::
349 * Naming Conventions for GNAT Source Files::
350 * Getting Internal Debugging Information::
352 * Pretty-Printers for the GNAT runtime::
356 * Non-Symbolic Traceback::
357 * Symbolic Traceback::
361 * Profiling an Ada Program with gprof::
363 Profiling an Ada Program with gprof
365 * Compilation for profiling::
366 * Program execution::
368 * Interpretation of profiling results::
370 Improving Performance
372 * Performance Considerations::
373 * Text_IO Suggestions::
374 * Reducing Size of Executables with Unused Subprogram/Data Elimination::
376 Performance Considerations
378 * Controlling Run-Time Checks::
379 * Use of Restrictions::
380 * Optimization Levels::
381 * Debugging Optimized Code::
382 * Inlining of Subprograms::
383 * Floating Point Operations::
384 * Vectorization of loops::
385 * Other Optimization Switches::
386 * Optimization and Strict Aliasing::
387 * Aliased Variables and Optimization::
388 * Atomic Variables and Optimization::
389 * Passive Task Optimization::
391 Reducing Size of Executables with Unused Subprogram/Data Elimination
393 * About unused subprogram/data elimination::
394 * Compilation options::
395 * Example of unused subprogram/data elimination::
397 Overflow Check Handling in GNAT
400 * Management of Overflows in GNAT::
401 * Specifying the Desired Mode::
403 * Implementation Notes::
405 Stack Related Facilities
407 * Stack Overflow Checking::
408 * Static Stack Usage Analysis::
409 * Dynamic Stack Usage Analysis::
411 Memory Management Issues
413 * Some Useful Memory Pools::
414 * The GNAT Debug Pool Facility::
416 Platform-Specific Information
418 * Run-Time Libraries::
419 * Specifying a Run-Time Library::
421 * Microsoft Windows Topics::
426 * Summary of Run-Time Configurations::
428 Specifying a Run-Time Library
430 * Choosing the Scheduling Policy::
434 * Required Packages on GNU/Linux::
435 * Position Independent Executable (PIE) Enabled by Default on Linux: Position Independent Executable PIE Enabled by Default on Linux.
436 * A GNU/Linux Debug Quirk::
438 Microsoft Windows Topics
440 * Using GNAT on Windows::
441 * Using a network installation of GNAT::
442 * CONSOLE and WINDOWS subsystems::
444 * Disabling Command Line Argument Expansion::
445 * Windows Socket Timeouts::
446 * Mixed-Language Programming on Windows::
447 * Windows Specific Add-Ons::
449 Mixed-Language Programming on Windows
451 * Windows Calling Conventions::
452 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs.
453 * Using DLLs with GNAT::
454 * Building DLLs with GNAT Project files::
455 * Building DLLs with GNAT::
456 * Building DLLs with gnatdll::
457 * Ada DLLs and Finalization::
458 * Creating a Spec for Ada DLLs::
459 * GNAT and Windows Resources::
460 * Using GNAT DLLs from Microsoft Visual Studio Applications::
462 * Setting Stack Size from gnatlink::
463 * Setting Heap Size from gnatlink::
465 Windows Calling Conventions
467 * C Calling Convention::
468 * Stdcall Calling Convention::
469 * Win32 Calling Convention::
470 * DLL Calling Convention::
474 * Creating an Ada Spec for the DLL Services::
475 * Creating an Import Library::
477 Building DLLs with gnatdll
479 * Limitations When Using Ada DLLs from Ada::
480 * Exporting Ada Entities::
481 * Ada DLLs and Elaboration::
483 Creating a Spec for Ada DLLs
485 * Creating the Definition File::
488 GNAT and Windows Resources
490 * Building Resources::
491 * Compiling Resources::
496 * Program and DLL Both Built with GCC/GNAT::
497 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
499 Windows Specific Add-Ons
506 * Codesigning the Debugger::
508 Elaboration Order Handling in GNAT
511 * Elaboration Order::
512 * Checking the Elaboration Order::
513 * Controlling the Elaboration Order in Ada::
514 * Controlling the Elaboration Order in GNAT::
515 * Mixing Elaboration Models::
517 * SPARK Diagnostics::
518 * Elaboration Circularities::
519 * Resolving Elaboration Circularities::
520 * Elaboration-related Compiler Switches::
521 * Summary of Procedures for Elaboration Control::
522 * Inspecting the Chosen Elaboration Order::
526 * Basic Assembler Syntax::
527 * A Simple Example of Inline Assembler::
528 * Output Variables in Inline Assembler::
529 * Input Variables in Inline Assembler::
530 * Inlining Inline Assembler Code::
531 * Other Asm Functionality::
533 Other Asm Functionality
535 * The Clobber Parameter::
536 * The Volatile Parameter::
541 @node About This Guide,Getting Started with GNAT,Top,Top
542 @anchor{gnat_ugn/about_this_guide doc}@anchor{2}@anchor{gnat_ugn/about_this_guide about-this-guide}@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}
543 @chapter About This Guide
547 This guide describes the use of GNAT,
548 a compiler and software development
549 toolset for the full Ada programming language.
550 It documents the features of the compiler and tools, and explains
551 how to use them to build Ada applications.
553 GNAT implements Ada 95, Ada 2005, Ada 2012, and Ada 202x, and it may also be
554 invoked in Ada 83 compatibility mode.
555 By default, GNAT assumes Ada 2012, but you can override with a
556 compiler switch (@ref{6,,Compiling Different Versions of Ada})
557 to explicitly specify the language version.
558 Throughout this manual, references to ‘Ada’ without a year suffix
559 apply to all Ada versions of the language, starting with Ada 95.
562 * What This Guide Contains::
563 * What You Should Know before Reading This Guide::
564 * Related Information::
569 @node What This Guide Contains,What You Should Know before Reading This Guide,,About This Guide
570 @anchor{gnat_ugn/about_this_guide what-this-guide-contains}@anchor{7}
571 @section What This Guide Contains
574 This guide contains the following chapters:
580 @ref{8,,Getting Started with GNAT} describes how to get started compiling
581 and running Ada programs with the GNAT Ada programming environment.
584 @ref{9,,The GNAT Compilation Model} describes the compilation model used
588 @ref{a,,Building Executable Programs with GNAT} describes how to use the
589 main GNAT tools to build executable programs, and it also gives examples of
590 using the GNU make utility with GNAT.
593 @ref{b,,GNAT Utility Programs} explains the various utility programs that
594 are included in the GNAT environment.
597 @ref{c,,GNAT and Program Execution} covers a number of topics related to
598 running, debugging, and tuning the performance of programs developed
602 Appendices cover several additional topics:
608 @ref{d,,Platform-Specific Information} describes the different run-time
609 library implementations and also presents information on how to use
610 GNAT on several specific platforms.
613 @ref{e,,Example of Binder Output File} shows the source code for the binder
614 output file for a sample program.
617 @ref{f,,Elaboration Order Handling in GNAT} describes how GNAT helps
618 you deal with elaboration order issues.
621 @ref{10,,Inline Assembler} shows how to use the inline assembly facility
625 @node What You Should Know before Reading This Guide,Related Information,What This Guide Contains,About This Guide
626 @anchor{gnat_ugn/about_this_guide what-you-should-know-before-reading-this-guide}@anchor{11}
627 @section What You Should Know before Reading This Guide
630 @geindex Ada 95 Language Reference Manual
632 @geindex Ada 2005 Language Reference Manual
634 This guide assumes a basic familiarity with the Ada 95 language, as
635 described in the International Standard ANSI/ISO/IEC-8652:1995, January
637 Reference manuals for Ada 95, Ada 2005, and Ada 2012 are included in
638 the GNAT documentation package.
640 @node Related Information,Conventions,What You Should Know before Reading This Guide,About This Guide
641 @anchor{gnat_ugn/about_this_guide related-information}@anchor{12}
642 @section Related Information
645 For further information about Ada and related tools, please refer to the
652 @cite{Ada 95 Reference Manual}, @cite{Ada 2005 Reference Manual}, and
653 @cite{Ada 2012 Reference Manual}, which contain reference
654 material for the several revisions of the Ada language standard.
657 @cite{GNAT Reference_Manual}, which contains all reference material for the GNAT
658 implementation of Ada.
661 @cite{Using GNAT Studio}, which describes the GNAT Studio
662 Integrated Development Environment.
665 @cite{GNAT Studio Tutorial}, which introduces the
666 main GNAT Studio features through examples.
669 @cite{Debugging with GDB},
670 for all details on the use of the GNU source-level debugger.
673 @cite{GNU Emacs Manual},
674 for full information on the extensible editor and programming
678 @node Conventions,,Related Information,About This Guide
679 @anchor{gnat_ugn/about_this_guide conventions}@anchor{13}
684 @geindex typographical
686 @geindex Typographical conventions
688 Following are examples of the typographical and graphic conventions used
695 @code{Functions}, @code{utility program names}, @code{standard names},
711 [optional information or parameters]
714 Examples are described by text
717 and then shown this way.
721 Commands that are entered by the user are shown as preceded by a prompt string
722 comprising the @code{$} character followed by a space.
725 Full file names are shown with the ‘/’ character
726 as the directory separator; e.g., @code{parent-dir/subdir/myfile.adb}.
727 If you are using GNAT on a Windows platform, please note that
728 the ‘\’ character should be used instead.
731 @node Getting Started with GNAT,The GNAT Compilation Model,About This Guide,Top
732 @anchor{gnat_ugn/getting_started_with_gnat doc}@anchor{14}@anchor{gnat_ugn/getting_started_with_gnat getting-started-with-gnat}@anchor{8}@anchor{gnat_ugn/getting_started_with_gnat id1}@anchor{15}
733 @chapter Getting Started with GNAT
736 This chapter describes how to use GNAT’s command line interface to build
737 executable Ada programs.
738 On most platforms a visually oriented Integrated Development Environment
739 is also available: GNAT Studio.
740 GNAT Studio offers a graphical “look and feel”, support for development in
741 other programming languages, comprehensive browsing features, and
742 many other capabilities.
743 For information on GNAT Studio please refer to the
744 @cite{GNAT Studio documentation}.
747 * System Requirements::
749 * Running a Simple Ada Program::
750 * Running a Program with Multiple Units::
754 @node System Requirements,Running GNAT,,Getting Started with GNAT
755 @anchor{gnat_ugn/getting_started_with_gnat id2}@anchor{16}@anchor{gnat_ugn/getting_started_with_gnat system-requirements}@anchor{17}
756 @section System Requirements
759 Even though any machine can run the GNAT toolset and GNAT Studio IDE, in order
760 to get the best experience, we recommend using a machine with as many cores
761 as possible since all individual compilations can run in parallel.
762 A comfortable setup for a compiler server is a machine with 24 physical cores
763 or more, with at least 48 GB of memory (2 GB per core).
765 For a desktop machine, a minimum of 4 cores is recommended (8 preferred),
766 with at least 2GB per core (so 8 to 16GB).
768 In addition, for running and navigating sources in GNAT Studio smoothly, we
769 recommend at least 1.5 GB plus 3 GB of RAM per 1 million source line of code.
770 In other words, we recommend at least 3 GB for for 500K lines of code and
771 7.5 GB for 2 million lines of code.
773 Note that using local and fast drives will also make a difference in terms of
774 build and link time. Network drives such as NFS, SMB, or worse, configuration
775 management filesystems (such as ClearCase dynamic views) should be avoided as
776 much as possible and will produce very degraded performance (typically 2 to 3
777 times slower than on local fast drives). If such slow drives cannot be avoided
778 for accessing the source code, then you should at least configure your project
779 file so that the result of the compilation is stored on a drive local to the
780 machine performing the run. This can be achieved by setting the @code{Object_Dir}
781 project file attribute.
783 @node Running GNAT,Running a Simple Ada Program,System Requirements,Getting Started with GNAT
784 @anchor{gnat_ugn/getting_started_with_gnat id3}@anchor{18}@anchor{gnat_ugn/getting_started_with_gnat running-gnat}@anchor{19}
785 @section Running GNAT
788 Three steps are needed to create an executable file from an Ada source
795 The source file(s) must be compiled.
798 The file(s) must be bound using the GNAT binder.
801 All appropriate object files must be linked to produce an executable.
804 All three steps are most commonly handled by using the @code{gnatmake}
805 utility program that, given the name of the main program, automatically
806 performs the necessary compilation, binding and linking steps.
808 @node Running a Simple Ada Program,Running a Program with Multiple Units,Running GNAT,Getting Started with GNAT
809 @anchor{gnat_ugn/getting_started_with_gnat id4}@anchor{1a}@anchor{gnat_ugn/getting_started_with_gnat running-a-simple-ada-program}@anchor{1b}
810 @section Running a Simple Ada Program
813 Any text editor may be used to prepare an Ada program.
814 (If Emacs is used, the optional Ada mode may be helpful in laying out the
816 The program text is a normal text file. We will assume in our initial
817 example that you have used your editor to prepare the following
818 standard format text file:
821 with Ada.Text_IO; use Ada.Text_IO;
824 Put_Line ("Hello WORLD!");
828 This file should be named @code{hello.adb}.
829 With the normal default file naming conventions, GNAT requires
831 contain a single compilation unit whose file name is the
833 with periods replaced by hyphens; the
834 extension is @code{ads} for a
835 spec and @code{adb} for a body.
836 You can override this default file naming convention by use of the
837 special pragma @code{Source_File_Name} (for further information please
838 see @ref{1c,,Using Other File Names}).
839 Alternatively, if you want to rename your files according to this default
840 convention, which is probably more convenient if you will be using GNAT
841 for all your compilations, then the @code{gnatchop} utility
842 can be used to generate correctly-named source files
843 (see @ref{1d,,Renaming Files with gnatchop}).
845 You can compile the program using the following command (@code{$} is used
846 as the command prompt in the examples in this document):
852 @code{gcc} is the command used to run the compiler. This compiler is
853 capable of compiling programs in several languages, including Ada and
854 C. It assumes that you have given it an Ada program if the file extension is
855 either @code{.ads} or @code{.adb}, and it will then call
856 the GNAT compiler to compile the specified file.
858 The @code{-c} switch is required. It tells @code{gcc} to only do a
859 compilation. (For C programs, @code{gcc} can also do linking, but this
860 capability is not used directly for Ada programs, so the @code{-c}
861 switch must always be present.)
863 This compile command generates a file
864 @code{hello.o}, which is the object
865 file corresponding to your Ada program. It also generates
866 an ‘Ada Library Information’ file @code{hello.ali},
867 which contains additional information used to check
868 that an Ada program is consistent.
870 To build an executable file, use either @code{gnatmake} or gprbuild with
871 the name of the main file: these tools are builders that will take care of
872 all the necessary build steps in the correct order.
873 In particular, these builders automatically recompile any sources that have
874 been modified since they were last compiled, or sources that depend
875 on such modified sources, so that ‘version skew’ is avoided.
877 @geindex Version skew (avoided by `@w{`}gnatmake`@w{`})
883 The result is an executable program called @code{hello}, which can be
890 assuming that the current directory is on the search path
891 for executable programs.
893 and, if all has gone well, you will see:
899 appear in response to this command.
901 @node Running a Program with Multiple Units,,Running a Simple Ada Program,Getting Started with GNAT
902 @anchor{gnat_ugn/getting_started_with_gnat id5}@anchor{1e}@anchor{gnat_ugn/getting_started_with_gnat running-a-program-with-multiple-units}@anchor{1f}
903 @section Running a Program with Multiple Units
906 Consider a slightly more complicated example that has three files: a
907 main program, and the spec and body of a package:
915 with Ada.Text_IO; use Ada.Text_IO;
916 package body Greetings is
919 Put_Line ("Hello WORLD!");
924 Put_Line ("Goodbye WORLD!");
936 Following the one-unit-per-file rule, place this program in the
937 following three separate files:
942 @item `greetings.ads'
944 spec of package @code{Greetings}
946 @item `greetings.adb'
948 body of package @code{Greetings}
955 Note that there is no required order of compilation when using GNAT.
956 In particular it is perfectly fine to compile the main program first.
957 Also, it is not necessary to compile package specs in the case where
958 there is an accompanying body; you only need to compile the body. If you want
959 to submit these files to the compiler for semantic checking and not code
960 generation, then use the @code{-gnatc} switch:
963 $ gcc -c greetings.ads -gnatc
966 Although the compilation can be done in separate steps, in practice it is
967 almost always more convenient to use the @code{gnatmake} or @code{gprbuild} tools:
973 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
975 @node The GNAT Compilation Model,Building Executable Programs with GNAT,Getting Started with GNAT,Top
976 @anchor{gnat_ugn/the_gnat_compilation_model doc}@anchor{20}@anchor{gnat_ugn/the_gnat_compilation_model id1}@anchor{21}@anchor{gnat_ugn/the_gnat_compilation_model the-gnat-compilation-model}@anchor{9}
977 @chapter The GNAT Compilation Model
980 @geindex GNAT compilation model
982 @geindex Compilation model
984 This chapter describes the compilation model used by GNAT. Although
985 similar to that used by other languages such as C and C++, this model
986 is substantially different from the traditional Ada compilation models,
987 which are based on a centralized program library. The chapter covers
988 the following material:
994 Topics related to source file makeup and naming
1000 @ref{22,,Source Representation}
1003 @ref{23,,Foreign Language Representation}
1006 @ref{24,,File Naming Topics and Utilities}
1010 @ref{25,,Configuration Pragmas}
1013 @ref{26,,Generating Object Files}
1016 @ref{27,,Source Dependencies}
1019 @ref{28,,The Ada Library Information Files}
1022 @ref{29,,Binding an Ada Program}
1025 @ref{2a,,GNAT and Libraries}
1028 @ref{2b,,Conditional Compilation}
1031 @ref{2c,,Mixed Language Programming}
1034 @ref{2d,,GNAT and Other Compilation Models}
1037 @ref{2e,,Using GNAT Files with External Tools}
1041 * Source Representation::
1042 * Foreign Language Representation::
1043 * File Naming Topics and Utilities::
1044 * Configuration Pragmas::
1045 * Generating Object Files::
1046 * Source Dependencies::
1047 * The Ada Library Information Files::
1048 * Binding an Ada Program::
1049 * GNAT and Libraries::
1050 * Conditional Compilation::
1051 * Mixed Language Programming::
1052 * GNAT and Other Compilation Models::
1053 * Using GNAT Files with External Tools::
1057 @node Source Representation,Foreign Language Representation,,The GNAT Compilation Model
1058 @anchor{gnat_ugn/the_gnat_compilation_model id2}@anchor{2f}@anchor{gnat_ugn/the_gnat_compilation_model source-representation}@anchor{22}
1059 @section Source Representation
1070 Ada source programs are represented in standard text files, using
1071 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1072 7-bit ASCII set, plus additional characters used for
1073 representing foreign languages (see @ref{23,,Foreign Language Representation}
1074 for support of non-USA character sets). The format effector characters
1075 are represented using their standard ASCII encodings, as follows:
1080 @multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxx}
1157 Source files are in standard text file format. In addition, GNAT will
1158 recognize a wide variety of stream formats, in which the end of
1159 physical lines is marked by any of the following sequences:
1160 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1161 in accommodating files that are imported from other operating systems.
1163 @geindex End of source file; Source file@comma{} end
1165 @geindex SUB (control character)
1167 The end of a source file is normally represented by the physical end of
1168 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1169 recognized as signalling the end of the source file. Again, this is
1170 provided for compatibility with other operating systems where this
1171 code is used to represent the end of file.
1173 @geindex spec (definition)
1174 @geindex compilation (definition)
1176 Each file contains a single Ada compilation unit, including any pragmas
1177 associated with the unit. For example, this means you must place a
1178 package declaration (a package `spec') and the corresponding body in
1179 separate files. An Ada `compilation' (which is a sequence of
1180 compilation units) is represented using a sequence of files. Similarly,
1181 you will place each subunit or child unit in a separate file.
1183 @node Foreign Language Representation,File Naming Topics and Utilities,Source Representation,The GNAT Compilation Model
1184 @anchor{gnat_ugn/the_gnat_compilation_model foreign-language-representation}@anchor{23}@anchor{gnat_ugn/the_gnat_compilation_model id3}@anchor{30}
1185 @section Foreign Language Representation
1188 GNAT supports the standard character sets defined in Ada as well as
1189 several other non-standard character sets for use in localized versions
1190 of the compiler (@ref{31,,Character Set Control}).
1194 * Other 8-Bit Codes::
1195 * Wide_Character Encodings::
1196 * Wide_Wide_Character Encodings::
1200 @node Latin-1,Other 8-Bit Codes,,Foreign Language Representation
1201 @anchor{gnat_ugn/the_gnat_compilation_model id4}@anchor{32}@anchor{gnat_ugn/the_gnat_compilation_model latin-1}@anchor{33}
1207 The basic character set is Latin-1. This character set is defined by ISO
1208 standard 8859, part 1. The lower half (character codes @code{16#00#}
1209 … @code{16#7F#)} is identical to standard ASCII coding, but the upper
1210 half is used to represent additional characters. These include extended letters
1211 used by European languages, such as French accents, the vowels with umlauts
1212 used in German, and the extra letter A-ring used in Swedish.
1214 @geindex Ada.Characters.Latin_1
1216 For a complete list of Latin-1 codes and their encodings, see the source
1217 file of library unit @code{Ada.Characters.Latin_1} in file
1218 @code{a-chlat1.ads}.
1219 You may use any of these extended characters freely in character or
1220 string literals. In addition, the extended characters that represent
1221 letters can be used in identifiers.
1223 @node Other 8-Bit Codes,Wide_Character Encodings,Latin-1,Foreign Language Representation
1224 @anchor{gnat_ugn/the_gnat_compilation_model id5}@anchor{34}@anchor{gnat_ugn/the_gnat_compilation_model other-8-bit-codes}@anchor{35}
1225 @subsection Other 8-Bit Codes
1228 GNAT also supports several other 8-bit coding schemes:
1237 @item `ISO 8859-2 (Latin-2)'
1239 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1250 @item `ISO 8859-3 (Latin-3)'
1252 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1263 @item `ISO 8859-4 (Latin-4)'
1265 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1276 @item `ISO 8859-5 (Cyrillic)'
1278 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1279 lowercase equivalence.
1282 @geindex ISO 8859-15
1289 @item `ISO 8859-15 (Latin-9)'
1291 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1292 lowercase equivalence.
1295 @geindex code page 437 (IBM PC)
1300 @item `IBM PC (code page 437)'
1302 This code page is the normal default for PCs in the U.S. It corresponds
1303 to the original IBM PC character set. This set has some, but not all, of
1304 the extended Latin-1 letters, but these letters do not have the same
1305 encoding as Latin-1. In this mode, these letters are allowed in
1306 identifiers with uppercase and lowercase equivalence.
1309 @geindex code page 850 (IBM PC)
1314 @item `IBM PC (code page 850)'
1316 This code page is a modification of 437 extended to include all the
1317 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1318 mode, all these letters are allowed in identifiers with uppercase and
1319 lowercase equivalence.
1321 @item `Full Upper 8-bit'
1323 Any character in the range 80-FF allowed in identifiers, and all are
1324 considered distinct. In other words, there are no uppercase and lowercase
1325 equivalences in this range. This is useful in conjunction with
1326 certain encoding schemes used for some foreign character sets (e.g.,
1327 the typical method of representing Chinese characters on the PC).
1329 @item `No Upper-Half'
1331 No upper-half characters in the range 80-FF are allowed in identifiers.
1332 This gives Ada 83 compatibility for identifier names.
1335 For precise data on the encodings permitted, and the uppercase and lowercase
1336 equivalences that are recognized, see the file @code{csets.adb} in
1337 the GNAT compiler sources. You will need to obtain a full source release
1338 of GNAT to obtain this file.
1340 @node Wide_Character Encodings,Wide_Wide_Character Encodings,Other 8-Bit Codes,Foreign Language Representation
1341 @anchor{gnat_ugn/the_gnat_compilation_model id6}@anchor{36}@anchor{gnat_ugn/the_gnat_compilation_model wide-character-encodings}@anchor{37}
1342 @subsection Wide_Character Encodings
1345 GNAT allows wide character codes to appear in character and string
1346 literals, and also optionally in identifiers, by means of the following
1347 possible encoding schemes:
1354 In this encoding, a wide character is represented by the following five
1361 where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1362 characters (using uppercase letters) of the wide character code. For
1363 example, ESC A345 is used to represent the wide character with code
1365 This scheme is compatible with use of the full Wide_Character set.
1367 @item `Upper-Half Coding'
1369 @geindex Upper-Half Coding
1371 The wide character with encoding @code{16#abcd#} where the upper bit is on
1372 (in other words, ‘a’ is in the range 8-F) is represented as two bytes,
1373 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1374 character, but is not required to be in the upper half. This method can
1375 be also used for shift-JIS or EUC, where the internal coding matches the
1378 @item `Shift JIS Coding'
1380 @geindex Shift JIS Coding
1382 A wide character is represented by a two-character sequence,
1384 @code{16#cd#}, with the restrictions described for upper-half encoding as
1385 described above. The internal character code is the corresponding JIS
1386 character according to the standard algorithm for Shift-JIS
1387 conversion. Only characters defined in the JIS code set table can be
1388 used with this encoding method.
1394 A wide character is represented by a two-character sequence
1396 @code{16#cd#}, with both characters being in the upper half. The internal
1397 character code is the corresponding JIS character according to the EUC
1398 encoding algorithm. Only characters defined in the JIS code set table
1399 can be used with this encoding method.
1401 @item `UTF-8 Coding'
1403 A wide character is represented using
1404 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1405 10646-1/Am.2. Depending on the character value, the representation
1406 is a one, two, or three byte sequence:
1409 16#0000#-16#007f#: 2#0xxxxxxx#
1410 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1411 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1414 where the @code{xxx} bits correspond to the left-padded bits of the
1415 16-bit character value. Note that all lower half ASCII characters
1416 are represented as ASCII bytes and all upper half characters and
1417 other wide characters are represented as sequences of upper-half
1418 (The full UTF-8 scheme allows for encoding 31-bit characters as
1419 6-byte sequences, and in the following section on wide wide
1420 characters, the use of these sequences is documented).
1422 @item `Brackets Coding'
1424 In this encoding, a wide character is represented by the following eight
1431 where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1432 characters (using uppercase letters) of the wide character code. For
1433 example, [‘A345’] is used to represent the wide character with code
1434 @code{16#A345#}. It is also possible (though not required) to use the
1435 Brackets coding for upper half characters. For example, the code
1436 @code{16#A3#} can be represented as @code{['A3']}.
1438 This scheme is compatible with use of the full Wide_Character set,
1439 and is also the method used for wide character encoding in some standard
1440 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1445 Some of these coding schemes do not permit the full use of the
1446 Ada character set. For example, neither Shift JIS nor EUC allow the
1447 use of the upper half of the Latin-1 set.
1451 @node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1452 @anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{38}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{39}
1453 @subsection Wide_Wide_Character Encodings
1456 GNAT allows wide wide character codes to appear in character and string
1457 literals, and also optionally in identifiers, by means of the following
1458 possible encoding schemes:
1463 @item `UTF-8 Coding'
1465 A wide character is represented using
1466 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1467 10646-1/Am.2. Depending on the character value, the representation
1468 of character codes with values greater than 16#FFFF# is a
1469 is a four, five, or six byte sequence:
1472 16#01_0000#-16#10_FFFF#: 11110xxx 10xxxxxx 10xxxxxx
1474 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1476 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1477 10xxxxxx 10xxxxxx 10xxxxxx
1480 where the @code{xxx} bits correspond to the left-padded bits of the
1481 32-bit character value.
1483 @item `Brackets Coding'
1485 In this encoding, a wide wide character is represented by the following ten or
1486 twelve byte character sequence:
1490 [ " a b c d e f g h " ]
1493 where @code{a-h} are the six or eight hexadecimal
1494 characters (using uppercase letters) of the wide wide character code. For
1495 example, [“1F4567”] is used to represent the wide wide character with code
1496 @code{16#001F_4567#}.
1498 This scheme is compatible with use of the full Wide_Wide_Character set,
1499 and is also the method used for wide wide character encoding in some standard
1500 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1503 @node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1504 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{24}@anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{3a}
1505 @section File Naming Topics and Utilities
1508 GNAT has a default file naming scheme and also provides the user with
1509 a high degree of control over how the names and extensions of the
1510 source files correspond to the Ada compilation units that they contain.
1513 * File Naming Rules::
1514 * Using Other File Names::
1515 * Alternative File Naming Schemes::
1516 * Handling Arbitrary File Naming Conventions with gnatname::
1517 * File Name Krunching with gnatkr::
1518 * Renaming Files with gnatchop::
1522 @node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1523 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{3b}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{3c}
1524 @subsection File Naming Rules
1527 The default file name is determined by the name of the unit that the
1528 file contains. The name is formed by taking the full expanded name of
1529 the unit and replacing the separating dots with hyphens and using
1530 lowercase for all letters.
1532 An exception arises if the file name generated by the above rules starts
1533 with one of the characters
1534 @code{a}, @code{g}, @code{i}, or @code{s}, and the second character is a
1535 minus. In this case, the character tilde is used in place
1536 of the minus. The reason for this special rule is to avoid clashes with
1537 the standard names for child units of the packages System, Ada,
1538 Interfaces, and GNAT, which use the prefixes
1539 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
1542 The file extension is @code{.ads} for a spec and
1543 @code{.adb} for a body. The following table shows some
1544 examples of these rules.
1549 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
1556 Ada Compilation Unit
1576 @code{arith_functions.ads}
1580 Arith_Functions (package spec)
1584 @code{arith_functions.adb}
1588 Arith_Functions (package body)
1592 @code{func-spec.ads}
1596 Func.Spec (child package spec)
1600 @code{func-spec.adb}
1604 Func.Spec (child package body)
1612 Sub (subunit of Main)
1620 A.Bad (child package body)
1626 Following these rules can result in excessively long
1627 file names if corresponding
1628 unit names are long (for example, if child units or subunits are
1629 heavily nested). An option is available to shorten such long file names
1630 (called file name ‘krunching’). This may be particularly useful when
1631 programs being developed with GNAT are to be used on operating systems
1632 with limited file name lengths. @ref{3d,,Using gnatkr}.
1634 Of course, no file shortening algorithm can guarantee uniqueness over
1635 all possible unit names; if file name krunching is used, it is your
1636 responsibility to ensure no name clashes occur. Alternatively you
1637 can specify the exact file names that you want used, as described
1638 in the next section. Finally, if your Ada programs are migrating from a
1639 compiler with a different naming convention, you can use the gnatchop
1640 utility to produce source files that follow the GNAT naming conventions.
1641 (For details see @ref{1d,,Renaming Files with gnatchop}.)
1643 Note: in the case of Windows or Mac OS operating systems, case is not
1644 significant. So for example on Windows if the canonical name is
1645 @code{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1646 However, case is significant for other operating systems, so for example,
1647 if you want to use other than canonically cased file names on a Unix system,
1648 you need to follow the procedures described in the next section.
1650 @node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1651 @anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{3e}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{1c}
1652 @subsection Using Other File Names
1657 In the previous section, we have described the default rules used by
1658 GNAT to determine the file name in which a given unit resides. It is
1659 often convenient to follow these default rules, and if you follow them,
1660 the compiler knows without being explicitly told where to find all
1663 @geindex Source_File_Name pragma
1665 However, in some cases, particularly when a program is imported from
1666 another Ada compiler environment, it may be more convenient for the
1667 programmer to specify which file names contain which units. GNAT allows
1668 arbitrary file names to be used by means of the Source_File_Name pragma.
1669 The form of this pragma is as shown in the following examples:
1672 pragma Source_File_Name (My_Utilities.Stacks,
1673 Spec_File_Name => "myutilst_a.ada");
1674 pragma Source_File_name (My_Utilities.Stacks,
1675 Body_File_Name => "myutilst.ada");
1678 As shown in this example, the first argument for the pragma is the unit
1679 name (in this example a child unit). The second argument has the form
1680 of a named association. The identifier
1681 indicates whether the file name is for a spec or a body;
1682 the file name itself is given by a string literal.
1684 The source file name pragma is a configuration pragma, which means that
1685 normally it will be placed in the @code{gnat.adc}
1686 file used to hold configuration
1687 pragmas that apply to a complete compilation environment.
1688 For more details on how the @code{gnat.adc} file is created and used
1689 see @ref{3f,,Handling of Configuration Pragmas}.
1693 GNAT allows completely arbitrary file names to be specified using the
1694 source file name pragma. However, if the file name specified has an
1695 extension other than @code{.ads} or @code{.adb} it is necessary to use
1696 a special syntax when compiling the file. The name in this case must be
1697 preceded by the special sequence @code{-x} followed by a space and the name
1698 of the language, here @code{ada}, as in:
1701 $ gcc -c -x ada peculiar_file_name.sim
1704 @code{gnatmake} handles non-standard file names in the usual manner (the
1705 non-standard file name for the main program is simply used as the
1706 argument to gnatmake). Note that if the extension is also non-standard,
1707 then it must be included in the @code{gnatmake} command, it may not
1710 @node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
1711 @anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{41}
1712 @subsection Alternative File Naming Schemes
1715 @geindex File naming schemes
1716 @geindex alternative
1720 The previous section described the use of the @code{Source_File_Name}
1721 pragma to allow arbitrary names to be assigned to individual source files.
1722 However, this approach requires one pragma for each file, and especially in
1723 large systems can result in very long @code{gnat.adc} files, and also create
1724 a maintenance problem.
1726 @geindex Source_File_Name pragma
1728 GNAT also provides a facility for specifying systematic file naming schemes
1729 other than the standard default naming scheme previously described. An
1730 alternative scheme for naming is specified by the use of
1731 @code{Source_File_Name} pragmas having the following format:
1734 pragma Source_File_Name (
1735 Spec_File_Name => FILE_NAME_PATTERN
1736 [ , Casing => CASING_SPEC]
1737 [ , Dot_Replacement => STRING_LITERAL ] );
1739 pragma Source_File_Name (
1740 Body_File_Name => FILE_NAME_PATTERN
1741 [ , Casing => CASING_SPEC ]
1742 [ , Dot_Replacement => STRING_LITERAL ] ) ;
1744 pragma Source_File_Name (
1745 Subunit_File_Name => FILE_NAME_PATTERN
1746 [ , Casing => CASING_SPEC ]
1747 [ , Dot_Replacement => STRING_LITERAL ] ) ;
1749 FILE_NAME_PATTERN ::= STRING_LITERAL
1750 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1753 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1754 It contains a single asterisk character, and the unit name is substituted
1755 systematically for this asterisk. The optional parameter
1756 @code{Casing} indicates
1757 whether the unit name is to be all upper-case letters, all lower-case letters,
1758 or mixed-case. If no
1759 @code{Casing} parameter is used, then the default is all
1762 The optional @code{Dot_Replacement} string is used to replace any periods
1763 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1764 argument is used then separating dots appear unchanged in the resulting
1766 Although the above syntax indicates that the
1767 @code{Casing} argument must appear
1768 before the @code{Dot_Replacement} argument, but it
1769 is also permissible to write these arguments in the opposite order.
1771 As indicated, it is possible to specify different naming schemes for
1772 bodies, specs, and subunits. Quite often the rule for subunits is the
1773 same as the rule for bodies, in which case, there is no need to give
1774 a separate @code{Subunit_File_Name} rule, and in this case the
1775 @code{Body_File_name} rule is used for subunits as well.
1777 The separate rule for subunits can also be used to implement the rather
1778 unusual case of a compilation environment (e.g., a single directory) which
1779 contains a subunit and a child unit with the same unit name. Although
1780 both units cannot appear in the same partition, the Ada Reference Manual
1781 allows (but does not require) the possibility of the two units coexisting
1782 in the same environment.
1784 The file name translation works in the following steps:
1790 If there is a specific @code{Source_File_Name} pragma for the given unit,
1791 then this is always used, and any general pattern rules are ignored.
1794 If there is a pattern type @code{Source_File_Name} pragma that applies to
1795 the unit, then the resulting file name will be used if the file exists. If
1796 more than one pattern matches, the latest one will be tried first, and the
1797 first attempt resulting in a reference to a file that exists will be used.
1800 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1801 for which the corresponding file exists, then the standard GNAT default
1802 naming rules are used.
1805 As an example of the use of this mechanism, consider a commonly used scheme
1806 in which file names are all lower case, with separating periods copied
1807 unchanged to the resulting file name, and specs end with @code{.1.ada}, and
1808 bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
1812 pragma Source_File_Name
1813 (Spec_File_Name => ".1.ada");
1814 pragma Source_File_Name
1815 (Body_File_Name => ".2.ada");
1818 The default GNAT scheme is actually implemented by providing the following
1819 default pragmas internally:
1822 pragma Source_File_Name
1823 (Spec_File_Name => ".ads", Dot_Replacement => "-");
1824 pragma Source_File_Name
1825 (Body_File_Name => ".adb", Dot_Replacement => "-");
1828 Our final example implements a scheme typically used with one of the
1829 Ada 83 compilers, where the separator character for subunits was ‘__’
1830 (two underscores), specs were identified by adding @code{_.ADA}, bodies
1831 by adding @code{.ADA}, and subunits by
1832 adding @code{.SEP}. All file names were
1833 upper case. Child units were not present of course since this was an
1834 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1835 the same double underscore separator for child units.
1838 pragma Source_File_Name
1839 (Spec_File_Name => "_.ADA",
1840 Dot_Replacement => "__",
1841 Casing = Uppercase);
1842 pragma Source_File_Name
1843 (Body_File_Name => ".ADA",
1844 Dot_Replacement => "__",
1845 Casing = Uppercase);
1846 pragma Source_File_Name
1847 (Subunit_File_Name => ".SEP",
1848 Dot_Replacement => "__",
1849 Casing = Uppercase);
1854 @node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
1855 @anchor{gnat_ugn/the_gnat_compilation_model handling-arbitrary-file-naming-conventions-with-gnatname}@anchor{42}@anchor{gnat_ugn/the_gnat_compilation_model id12}@anchor{43}
1856 @subsection Handling Arbitrary File Naming Conventions with @code{gnatname}
1859 @geindex File Naming Conventions
1862 * Arbitrary File Naming Conventions::
1863 * Running gnatname::
1864 * Switches for gnatname::
1865 * Examples of gnatname Usage::
1869 @node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
1870 @anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{44}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{45}
1871 @subsubsection Arbitrary File Naming Conventions
1874 The GNAT compiler must be able to know the source file name of a compilation
1875 unit. When using the standard GNAT default file naming conventions
1876 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
1877 does not need additional information.
1879 When the source file names do not follow the standard GNAT default file naming
1880 conventions, the GNAT compiler must be given additional information through
1881 a configuration pragmas file (@ref{25,,Configuration Pragmas})
1883 When the non-standard file naming conventions are well-defined,
1884 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
1885 (@ref{40,,Alternative File Naming Schemes}) may be sufficient. However,
1886 if the file naming conventions are irregular or arbitrary, a number
1887 of pragma @code{Source_File_Name} for individual compilation units
1889 To help maintain the correspondence between compilation unit names and
1890 source file names within the compiler,
1891 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
1894 @node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
1895 @anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{46}@anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{47}
1896 @subsubsection Running @code{gnatname}
1899 The usual form of the @code{gnatname} command is:
1902 $ gnatname [ switches ] naming_pattern [ naming_patterns ]
1903 [--and [ switches ] naming_pattern [ naming_patterns ]]
1906 All of the arguments are optional. If invoked without any argument,
1907 @code{gnatname} will display its usage.
1909 When used with at least one naming pattern, @code{gnatname} will attempt to
1910 find all the compilation units in files that follow at least one of the
1911 naming patterns. To find these compilation units,
1912 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
1915 One or several Naming Patterns may be given as arguments to @code{gnatname}.
1916 Each Naming Pattern is enclosed between double quotes (or single
1918 A Naming Pattern is a regular expression similar to the wildcard patterns
1919 used in file names by the Unix shells or the DOS prompt.
1921 @code{gnatname} may be called with several sections of directories/patterns.
1922 Sections are separated by the switch @code{--and}. In each section, there must be
1923 at least one pattern. If no directory is specified in a section, the current
1924 directory (or the project directory if @code{-P} is used) is implied.
1925 The options other that the directory switches and the patterns apply globally
1926 even if they are in different sections.
1928 Examples of Naming Patterns are:
1936 For a more complete description of the syntax of Naming Patterns,
1937 see the second kind of regular expressions described in @code{g-regexp.ads}
1938 (the ‘Glob’ regular expressions).
1940 When invoked without the switch @code{-P}, @code{gnatname} will create a
1941 configuration pragmas file @code{gnat.adc} in the current working directory,
1942 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
1945 @node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
1946 @anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{48}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{49}
1947 @subsubsection Switches for @code{gnatname}
1950 Switches for @code{gnatname} must precede any specified Naming Pattern.
1952 You may specify any of the following switches to @code{gnatname}:
1954 @geindex --version (gnatname)
1959 @item @code{--version}
1961 Display Copyright and version, then exit disregarding all other options.
1964 @geindex --help (gnatname)
1971 If @code{--version} was not used, display usage, then exit disregarding
1974 @item @code{--subdirs=`dir'}
1976 Real object, library or exec directories are subdirectories <dir> of the
1979 @item @code{--no-backup}
1981 Do not create a backup copy of an existing project file.
1985 Start another section of directories/patterns.
1988 @geindex -c (gnatname)
1993 @item @code{-c`filename'}
1995 Create a configuration pragmas file @code{filename} (instead of the default
1997 There may be zero, one or more space between @code{-c} and
1999 @code{filename} may include directory information. @code{filename} must be
2000 writable. There may be only one switch @code{-c}.
2001 When a switch @code{-c} is
2002 specified, no switch @code{-P} may be specified (see below).
2005 @geindex -d (gnatname)
2010 @item @code{-d`dir'}
2012 Look for source files in directory @code{dir}. There may be zero, one or more
2013 spaces between @code{-d} and @code{dir}.
2014 @code{dir} may end with @code{/**}, that is it may be of the form
2015 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
2016 subdirectories, recursively, have to be searched for sources.
2017 When a switch @code{-d}
2018 is specified, the current working directory will not be searched for source
2019 files, unless it is explicitly specified with a @code{-d}
2020 or @code{-D} switch.
2021 Several switches @code{-d} may be specified.
2022 If @code{dir} is a relative path, it is relative to the directory of
2023 the configuration pragmas file specified with switch
2025 or to the directory of the project file specified with switch
2027 if neither switch @code{-c}
2028 nor switch @code{-P} are specified, it is relative to the
2029 current working directory. The directory
2030 specified with switch @code{-d} must exist and be readable.
2033 @geindex -D (gnatname)
2038 @item @code{-D`filename'}
2040 Look for source files in all directories listed in text file @code{filename}.
2041 There may be zero, one or more spaces between @code{-D}
2042 and @code{filename}.
2043 @code{filename} must be an existing, readable text file.
2044 Each nonempty line in @code{filename} must be a directory.
2045 Specifying switch @code{-D} is equivalent to specifying as many
2046 switches @code{-d} as there are nonempty lines in
2051 Follow symbolic links when processing project files.
2053 @geindex -f (gnatname)
2055 @item @code{-f`pattern'}
2057 Foreign patterns. Using this switch, it is possible to add sources of languages
2058 other than Ada to the list of sources of a project file.
2059 It is only useful if a -P switch is used.
2063 gnatname -Pprj -f"*.c" "*.ada"
2066 will look for Ada units in all files with the @code{.ada} extension,
2067 and will add to the list of file for project @code{prj.gpr} the C files
2068 with extension @code{.c}.
2070 @geindex -h (gnatname)
2074 Output usage (help) information. The output is written to @code{stdout}.
2076 @geindex -P (gnatname)
2078 @item @code{-P`proj'}
2080 Create or update project file @code{proj}. There may be zero, one or more space
2081 between @code{-P} and @code{proj}. @code{proj} may include directory
2082 information. @code{proj} must be writable.
2083 There may be only one switch @code{-P}.
2084 When a switch @code{-P} is specified,
2085 no switch @code{-c} may be specified.
2086 On all platforms, except on VMS, when @code{gnatname} is invoked for an
2087 existing project file <proj>.gpr, a backup copy of the project file is created
2088 in the project directory with file name <proj>.gpr.saved_x. ‘x’ is the first
2089 non negative number that makes this backup copy a new file.
2091 @geindex -v (gnatname)
2095 Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2096 This includes name of the file written, the name of the directories to search
2097 and, for each file in those directories whose name matches at least one of
2098 the Naming Patterns, an indication of whether the file contains a unit,
2099 and if so the name of the unit.
2102 @geindex -v -v (gnatname)
2109 Very Verbose mode. In addition to the output produced in verbose mode,
2110 for each file in the searched directories whose name matches none of
2111 the Naming Patterns, an indication is given that there is no match.
2113 @geindex -x (gnatname)
2115 @item @code{-x`pattern'}
2117 Excluded patterns. Using this switch, it is possible to exclude some files
2118 that would match the name patterns. For example,
2121 gnatname -x "*_nt.ada" "*.ada"
2124 will look for Ada units in all files with the @code{.ada} extension,
2125 except those whose names end with @code{_nt.ada}.
2128 @node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2129 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{4a}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{4b}
2130 @subsubsection Examples of @code{gnatname} Usage
2134 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2137 In this example, the directory @code{/home/me} must already exist
2138 and be writable. In addition, the directory
2139 @code{/home/me/sources} (specified by
2140 @code{-d sources}) must exist and be readable.
2142 Note the optional spaces after @code{-c} and @code{-d}.
2145 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
2146 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2149 Note that several switches @code{-d} may be used,
2150 even in conjunction with one or several switches
2151 @code{-D}. Several Naming Patterns and one excluded pattern
2152 are used in this example.
2154 @node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2155 @anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{4c}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{4d}
2156 @subsection File Name Krunching with @code{gnatkr}
2161 This section discusses the method used by the compiler to shorten
2162 the default file names chosen for Ada units so that they do not
2163 exceed the maximum length permitted. It also describes the
2164 @code{gnatkr} utility that can be used to determine the result of
2165 applying this shortening.
2170 * Krunching Method::
2171 * Examples of gnatkr Usage::
2175 @node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2176 @anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{4e}@anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{4f}
2177 @subsubsection About @code{gnatkr}
2180 The default file naming rule in GNAT
2181 is that the file name must be derived from
2182 the unit name. The exact default rule is as follows:
2188 Take the unit name and replace all dots by hyphens.
2191 If such a replacement occurs in the
2192 second character position of a name, and the first character is
2193 @code{a}, @code{g}, @code{s}, or @code{i},
2194 then replace the dot by the character
2198 The reason for this exception is to avoid clashes
2199 with the standard names for children of System, Ada, Interfaces,
2200 and GNAT, which use the prefixes
2201 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
2205 The @code{-gnatk`nn'}
2206 switch of the compiler activates a ‘krunching’
2207 circuit that limits file names to nn characters (where nn is a decimal
2210 The @code{gnatkr} utility can be used to determine the krunched name for
2211 a given file, when krunched to a specified maximum length.
2213 @node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2214 @anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{50}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{3d}
2215 @subsubsection Using @code{gnatkr}
2218 The @code{gnatkr} command has the form:
2221 $ gnatkr name [ length ]
2224 @code{name} is the uncrunched file name, derived from the name of the unit
2225 in the standard manner described in the previous section (i.e., in particular
2226 all dots are replaced by hyphens). The file name may or may not have an
2227 extension (defined as a suffix of the form period followed by arbitrary
2228 characters other than period). If an extension is present then it will
2229 be preserved in the output. For example, when krunching @code{hellofile.ads}
2230 to eight characters, the result will be hellofil.ads.
2232 Note: for compatibility with previous versions of @code{gnatkr} dots may
2233 appear in the name instead of hyphens, but the last dot will always be
2234 taken as the start of an extension. So if @code{gnatkr} is given an argument
2235 such as @code{Hello.World.adb} it will be treated exactly as if the first
2236 period had been a hyphen, and for example krunching to eight characters
2237 gives the result @code{hellworl.adb}.
2239 Note that the result is always all lower case.
2240 Characters of the other case are folded as required.
2242 @code{length} represents the length of the krunched name. The default
2243 when no argument is given is 8 characters. A length of zero stands for
2244 unlimited, in other words do not chop except for system files where the
2245 implied crunching length is always eight characters.
2247 The output is the krunched name. The output has an extension only if the
2248 original argument was a file name with an extension.
2250 @node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2251 @anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{52}
2252 @subsubsection Krunching Method
2255 The initial file name is determined by the name of the unit that the file
2256 contains. The name is formed by taking the full expanded name of the
2257 unit and replacing the separating dots with hyphens and
2259 for all letters, except that a hyphen in the second character position is
2260 replaced by a tilde if the first character is
2261 @code{a}, @code{i}, @code{g}, or @code{s}.
2262 The extension is @code{.ads} for a
2263 spec and @code{.adb} for a body.
2264 Krunching does not affect the extension, but the file name is shortened to
2265 the specified length by following these rules:
2271 The name is divided into segments separated by hyphens, tildes or
2272 underscores and all hyphens, tildes, and underscores are
2273 eliminated. If this leaves the name short enough, we are done.
2276 If the name is too long, the longest segment is located (left-most
2277 if there are two of equal length), and shortened by dropping
2278 its last character. This is repeated until the name is short enough.
2280 As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2281 to fit the name into 8 characters as required by some operating systems:
2284 our-strings-wide_fixed 22
2285 our strings wide fixed 19
2286 our string wide fixed 18
2287 our strin wide fixed 17
2288 our stri wide fixed 16
2289 our stri wide fixe 15
2290 our str wide fixe 14
2297 Final file name: oustwifi.adb
2301 The file names for all predefined units are always krunched to eight
2302 characters. The krunching of these predefined units uses the following
2303 special prefix replacements:
2306 @multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx}
2350 These system files have a hyphen in the second character position. That
2351 is why normal user files replace such a character with a
2352 tilde, to avoid confusion with system file names.
2354 As an example of this special rule, consider
2355 @code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2358 ada-strings-wide_fixed 22
2359 a- strings wide fixed 18
2360 a- string wide fixed 17
2361 a- strin wide fixed 16
2362 a- stri wide fixed 15
2363 a- stri wide fixe 14
2370 Final file name: a-stwifi.adb
2374 Of course no file shortening algorithm can guarantee uniqueness over all
2375 possible unit names, and if file name krunching is used then it is your
2376 responsibility to ensure that no name clashes occur. The utility
2377 program @code{gnatkr} is supplied for conveniently determining the
2378 krunched name of a file.
2380 @node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2381 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{53}@anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{54}
2382 @subsubsection Examples of @code{gnatkr} Usage
2386 $ gnatkr very_long_unit_name.ads --> velounna.ads
2387 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
2388 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2389 $ gnatkr grandparent-parent-child --> grparchi
2390 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2391 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2394 @node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2395 @anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{55}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{1d}
2396 @subsection Renaming Files with @code{gnatchop}
2401 This section discusses how to handle files with multiple units by using
2402 the @code{gnatchop} utility. This utility is also useful in renaming
2403 files to meet the standard GNAT default file naming conventions.
2406 * Handling Files with Multiple Units::
2407 * Operating gnatchop in Compilation Mode::
2408 * Command Line for gnatchop::
2409 * Switches for gnatchop::
2410 * Examples of gnatchop Usage::
2414 @node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2415 @anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{56}@anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{57}
2416 @subsubsection Handling Files with Multiple Units
2419 The basic compilation model of GNAT requires that a file submitted to the
2420 compiler have only one unit and there be a strict correspondence
2421 between the file name and the unit name.
2423 If you want to keep your files with multiple units,
2424 perhaps to maintain compatibility with some other Ada compilation system,
2425 you can use @code{gnatname} to generate or update your project files.
2426 Generated or modified project files can be processed by GNAT.
2428 See @ref{42,,Handling Arbitrary File Naming Conventions with gnatname}
2429 for more details on how to use @cite{gnatname}.
2431 Alternatively, if you want to permanently restructure a set of ‘foreign’
2432 files so that they match the GNAT rules, and do the remaining development
2433 using the GNAT structure, you can simply use @code{gnatchop} once, generate the
2434 new set of files and work with them from that point on.
2436 Note that if your file containing multiple units starts with a byte order
2437 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2438 will each start with a copy of this BOM, meaning that they can be compiled
2439 automatically in UTF-8 mode without needing to specify an explicit encoding.
2441 @node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2442 @anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{58}@anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{59}
2443 @subsubsection Operating gnatchop in Compilation Mode
2446 The basic function of @code{gnatchop} is to take a file with multiple units
2447 and split it into separate files. The boundary between files is reasonably
2448 clear, except for the issue of comments and pragmas. In default mode, the
2449 rule is that any pragmas between units belong to the previous unit, except
2450 that configuration pragmas always belong to the following unit. Any comments
2451 belong to the following unit. These rules
2452 almost always result in the right choice of
2453 the split point without needing to mark it explicitly and most users will
2454 find this default to be what they want. In this default mode it is incorrect to
2455 submit a file containing only configuration pragmas, or one that ends in
2456 configuration pragmas, to @code{gnatchop}.
2458 However, using a special option to activate ‘compilation mode’,
2460 can perform another function, which is to provide exactly the semantics
2461 required by the RM for handling of configuration pragmas in a compilation.
2462 In the absence of configuration pragmas (at the main file level), this
2463 option has no effect, but it causes such configuration pragmas to be handled
2464 in a quite different manner.
2466 First, in compilation mode, if @code{gnatchop} is given a file that consists of
2467 only configuration pragmas, then this file is appended to the
2468 @code{gnat.adc} file in the current directory. This behavior provides
2469 the required behavior described in the RM for the actions to be taken
2470 on submitting such a file to the compiler, namely that these pragmas
2471 should apply to all subsequent compilations in the same compilation
2472 environment. Using GNAT, the current directory, possibly containing a
2473 @code{gnat.adc} file is the representation
2474 of a compilation environment. For more information on the
2475 @code{gnat.adc} file, see @ref{3f,,Handling of Configuration Pragmas}.
2477 Second, in compilation mode, if @code{gnatchop}
2478 is given a file that starts with
2479 configuration pragmas, and contains one or more units, then these
2480 configuration pragmas are prepended to each of the chopped files. This
2481 behavior provides the required behavior described in the RM for the
2482 actions to be taken on compiling such a file, namely that the pragmas
2483 apply to all units in the compilation, but not to subsequently compiled
2486 Finally, if configuration pragmas appear between units, they are appended
2487 to the previous unit. This results in the previous unit being illegal,
2488 since the compiler does not accept configuration pragmas that follow
2489 a unit. This provides the required RM behavior that forbids configuration
2490 pragmas other than those preceding the first compilation unit of a
2493 For most purposes, @code{gnatchop} will be used in default mode. The
2494 compilation mode described above is used only if you need exactly
2495 accurate behavior with respect to compilations, and you have files
2496 that contain multiple units and configuration pragmas. In this
2497 circumstance the use of @code{gnatchop} with the compilation mode
2498 switch provides the required behavior, and is for example the mode
2499 in which GNAT processes the ACVC tests.
2501 @node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2502 @anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{5a}@anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{5b}
2503 @subsubsection Command Line for @code{gnatchop}
2506 The @code{gnatchop} command has the form:
2509 $ gnatchop switches file_name [file_name ...]
2513 The only required argument is the file name of the file to be chopped.
2514 There are no restrictions on the form of this file name. The file itself
2515 contains one or more Ada units, in normal GNAT format, concatenated
2516 together. As shown, more than one file may be presented to be chopped.
2518 When run in default mode, @code{gnatchop} generates one output file in
2519 the current directory for each unit in each of the files.
2521 @code{directory}, if specified, gives the name of the directory to which
2522 the output files will be written. If it is not specified, all files are
2523 written to the current directory.
2525 For example, given a
2526 file called @code{hellofiles} containing
2531 with Ada.Text_IO; use Ada.Text_IO;
2541 $ gnatchop hellofiles
2544 generates two files in the current directory, one called
2545 @code{hello.ads} containing the single line that is the procedure spec,
2546 and the other called @code{hello.adb} containing the remaining text. The
2547 original file is not affected. The generated files can be compiled in
2550 When gnatchop is invoked on a file that is empty or that contains only empty
2551 lines and/or comments, gnatchop will not fail, but will not produce any
2554 For example, given a
2555 file called @code{toto.txt} containing
2567 will not produce any new file and will result in the following warnings:
2570 toto.txt:1:01: warning: empty file, contains no compilation units
2571 no compilation units found
2572 no source files written
2575 @node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2576 @anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{5c}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{5d}
2577 @subsubsection Switches for @code{gnatchop}
2580 @code{gnatchop} recognizes the following switches:
2582 @geindex --version (gnatchop)
2587 @item @code{--version}
2589 Display Copyright and version, then exit disregarding all other options.
2592 @geindex --help (gnatchop)
2599 If @code{--version} was not used, display usage, then exit disregarding
2603 @geindex -c (gnatchop)
2610 Causes @code{gnatchop} to operate in compilation mode, in which
2611 configuration pragmas are handled according to strict RM rules. See
2612 previous section for a full description of this mode.
2614 @item @code{-gnat`xxx'}
2616 This passes the given @code{-gnat`xxx'} switch to @code{gnat} which is
2617 used to parse the given file. Not all `xxx' options make sense,
2618 but for example, the use of @code{-gnati2} allows @code{gnatchop} to
2619 process a source file that uses Latin-2 coding for identifiers.
2623 Causes @code{gnatchop} to generate a brief help summary to the standard
2624 output file showing usage information.
2627 @geindex -k (gnatchop)
2634 Limit generated file names to the specified number @code{mm}
2636 This is useful if the
2637 resulting set of files is required to be interoperable with systems
2638 which limit the length of file names.
2639 No space is allowed between the @code{-k} and the numeric value. The numeric
2640 value may be omitted in which case a default of @code{-k8},
2642 with DOS-like file systems, is used. If no @code{-k} switch
2644 there is no limit on the length of file names.
2647 @geindex -p (gnatchop)
2654 Causes the file modification time stamp of the input file to be
2655 preserved and used for the time stamp of the output file(s). This may be
2656 useful for preserving coherency of time stamps in an environment where
2657 @code{gnatchop} is used as part of a standard build process.
2660 @geindex -q (gnatchop)
2667 Causes output of informational messages indicating the set of generated
2668 files to be suppressed. Warnings and error messages are unaffected.
2671 @geindex -r (gnatchop)
2673 @geindex Source_Reference pragmas
2680 Generate @code{Source_Reference} pragmas. Use this switch if the output
2681 files are regarded as temporary and development is to be done in terms
2682 of the original unchopped file. This switch causes
2683 @code{Source_Reference} pragmas to be inserted into each of the
2684 generated files to refers back to the original file name and line number.
2685 The result is that all error messages refer back to the original
2687 In addition, the debugging information placed into the object file (when
2688 the @code{-g} switch of @code{gcc} or @code{gnatmake} is
2690 also refers back to this original file so that tools like profilers and
2691 debuggers will give information in terms of the original unchopped file.
2693 If the original file to be chopped itself contains
2694 a @code{Source_Reference}
2695 pragma referencing a third file, then gnatchop respects
2696 this pragma, and the generated @code{Source_Reference} pragmas
2697 in the chopped file refer to the original file, with appropriate
2698 line numbers. This is particularly useful when @code{gnatchop}
2699 is used in conjunction with @code{gnatprep} to compile files that
2700 contain preprocessing statements and multiple units.
2703 @geindex -v (gnatchop)
2710 Causes @code{gnatchop} to operate in verbose mode. The version
2711 number and copyright notice are output, as well as exact copies of
2712 the gnat1 commands spawned to obtain the chop control information.
2715 @geindex -w (gnatchop)
2722 Overwrite existing file names. Normally @code{gnatchop} regards it as a
2723 fatal error if there is already a file with the same name as a
2724 file it would otherwise output, in other words if the files to be
2725 chopped contain duplicated units. This switch bypasses this
2726 check, and causes all but the last instance of such duplicated
2727 units to be skipped.
2730 @geindex --GCC= (gnatchop)
2735 @item @code{--GCC=`xxxx'}
2737 Specify the path of the GNAT parser to be used. When this switch is used,
2738 no attempt is made to add the prefix to the GNAT parser executable.
2741 @node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
2742 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{5e}@anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{5f}
2743 @subsubsection Examples of @code{gnatchop} Usage
2747 $ gnatchop -w hello_s.ada prerelease/files
2750 Chops the source file @code{hello_s.ada}. The output files will be
2751 placed in the directory @code{prerelease/files},
2753 files with matching names in that directory (no files in the current
2754 directory are modified).
2760 Chops the source file @code{archive}
2761 into the current directory. One
2762 useful application of @code{gnatchop} is in sending sets of sources
2763 around, for example in email messages. The required sources are simply
2764 concatenated (for example, using a Unix @code{cat}
2766 @code{gnatchop} is used at the other end to reconstitute the original
2770 $ gnatchop file1 file2 file3 direc
2773 Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
2774 the resulting files in the directory @code{direc}. Note that if any units
2775 occur more than once anywhere within this set of files, an error message
2776 is generated, and no files are written. To override this check, use the
2778 in which case the last occurrence in the last file will
2779 be the one that is output, and earlier duplicate occurrences for a given
2780 unit will be skipped.
2782 @node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
2783 @anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{25}@anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{60}
2784 @section Configuration Pragmas
2787 @geindex Configuration pragmas
2790 @geindex configuration
2792 Configuration pragmas include those pragmas described as
2793 such in the Ada Reference Manual, as well as
2794 implementation-dependent pragmas that are configuration pragmas.
2795 See the @code{Implementation_Defined_Pragmas} chapter in the
2796 @cite{GNAT_Reference_Manual} for details on these
2797 additional GNAT-specific configuration pragmas.
2798 Most notably, the pragma @code{Source_File_Name}, which allows
2799 specifying non-default names for source files, is a configuration
2800 pragma. The following is a complete list of configuration pragmas
2811 Aggregate_Individually_Assign
2812 Allow_Integer_Address
2815 Assume_No_Invalid_Values
2817 Check_Float_Overflow
2821 Convention_Identifier
2823 Default_Scalar_Storage_Order
2824 Default_Storage_Pool
2826 Disable_Atomic_Synchronization
2830 Enable_Atomic_Synchronization
2833 External_Name_Casing
2842 No_Component_Reordering
2843 No_Heap_Finalization
2848 Overriding_Renamings
2849 Partition_Elaboration_Policy
2851 Prefix_Exception_Messages
2852 Priority_Specific_Dispatching
2858 Restriction_Warnings
2860 Short_Circuit_And_Or
2862 Source_File_Name_Project
2866 Suppress_Exception_Locations
2867 Task_Dispatching_Policy
2868 Unevaluated_Use_Of_Old
2874 Wide_Character_Encoding
2878 * Handling of Configuration Pragmas::
2879 * The Configuration Pragmas Files::
2883 @node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
2884 @anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{3f}@anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{61}
2885 @subsection Handling of Configuration Pragmas
2888 Configuration pragmas may either appear at the start of a compilation
2889 unit, or they can appear in a configuration pragma file to apply to
2890 all compilations performed in a given compilation environment.
2892 GNAT also provides the @code{gnatchop} utility to provide an automatic
2893 way to handle configuration pragmas following the semantics for
2894 compilations (that is, files with multiple units), described in the RM.
2895 See @ref{59,,Operating gnatchop in Compilation Mode} for details.
2896 However, for most purposes, it will be more convenient to edit the
2897 @code{gnat.adc} file that contains configuration pragmas directly,
2898 as described in the following section.
2900 In the case of @code{Restrictions} pragmas appearing as configuration
2901 pragmas in individual compilation units, the exact handling depends on
2902 the type of restriction.
2904 Restrictions that require partition-wide consistency (like
2905 @code{No_Tasking}) are
2906 recognized wherever they appear
2907 and can be freely inherited, e.g. from a `with'ed unit to the `with'ing
2908 unit. This makes sense since the binder will in any case insist on seeing
2909 consistent use, so any unit not conforming to any restrictions that are
2910 anywhere in the partition will be rejected, and you might as well find
2911 that out at compile time rather than at bind time.
2913 For restrictions that do not require partition-wide consistency, e.g.
2914 SPARK or No_Implementation_Attributes, in general the restriction applies
2915 only to the unit in which the pragma appears, and not to any other units.
2917 The exception is No_Elaboration_Code which always applies to the entire
2918 object file from a compilation, i.e. to the body, spec, and all subunits.
2919 This restriction can be specified in a configuration pragma file, or it
2920 can be on the body and/or the spec (in either case it applies to all the
2921 relevant units). It can appear on a subunit only if it has previously
2922 appeared in the body of spec.
2924 @node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
2925 @anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{62}@anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{63}
2926 @subsection The Configuration Pragmas Files
2931 In GNAT a compilation environment is defined by the current
2932 directory at the time that a compile command is given. This current
2933 directory is searched for a file whose name is @code{gnat.adc}. If
2934 this file is present, it is expected to contain one or more
2935 configuration pragmas that will be applied to the current compilation.
2936 However, if the switch @code{-gnatA} is used, @code{gnat.adc} is not
2937 considered. When taken into account, @code{gnat.adc} is added to the
2938 dependencies, so that if @code{gnat.adc} is modified later, an invocation of
2939 @code{gnatmake} will recompile the source.
2941 Configuration pragmas may be entered into the @code{gnat.adc} file
2942 either by running @code{gnatchop} on a source file that consists only of
2943 configuration pragmas, or more conveniently by direct editing of the
2944 @code{gnat.adc} file, which is a standard format source file.
2946 Besides @code{gnat.adc}, additional files containing configuration
2947 pragmas may be applied to the current compilation using the switch
2948 @code{-gnatec=`path'} where @code{path} must designate an existing file that
2949 contains only configuration pragmas. These configuration pragmas are
2950 in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
2951 is present and switch @code{-gnatA} is not used).
2953 It is allowable to specify several switches @code{-gnatec=}, all of which
2954 will be taken into account.
2956 Files containing configuration pragmas specified with switches
2957 @code{-gnatec=} are added to the dependencies, unless they are
2958 temporary files. A file is considered temporary if its name ends in
2959 @code{.tmp} or @code{.TMP}. Certain tools follow this naming
2960 convention because they pass information to @code{gcc} via
2961 temporary files that are immediately deleted; it doesn’t make sense to
2962 depend on a file that no longer exists. Such tools include
2963 @code{gprbuild}, @code{gnatmake}, and @code{gnatcheck}.
2965 By default, configuration pragma files are stored by their absolute paths in
2966 ALI files. You can use the @code{-gnateb} switch in order to store them by
2967 their basename instead.
2969 If you are using project file, a separate mechanism is provided using
2973 @c See :ref:`Specifying_Configuration_Pragmas` for more details.
2975 @node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
2976 @anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{26}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{64}
2977 @section Generating Object Files
2980 An Ada program consists of a set of source files, and the first step in
2981 compiling the program is to generate the corresponding object files.
2982 These are generated by compiling a subset of these source files.
2983 The files you need to compile are the following:
2989 If a package spec has no body, compile the package spec to produce the
2990 object file for the package.
2993 If a package has both a spec and a body, compile the body to produce the
2994 object file for the package. The source file for the package spec need
2995 not be compiled in this case because there is only one object file, which
2996 contains the code for both the spec and body of the package.
2999 For a subprogram, compile the subprogram body to produce the object file
3000 for the subprogram. The spec, if one is present, is as usual in a
3001 separate file, and need not be compiled.
3010 In the case of subunits, only compile the parent unit. A single object
3011 file is generated for the entire subunit tree, which includes all the
3015 Compile child units independently of their parent units
3016 (though, of course, the spec of all the ancestor unit must be present in order
3017 to compile a child unit).
3022 Compile generic units in the same manner as any other units. The object
3023 files in this case are small dummy files that contain at most the
3024 flag used for elaboration checking. This is because GNAT always handles generic
3025 instantiation by means of macro expansion. However, it is still necessary to
3026 compile generic units, for dependency checking and elaboration purposes.
3029 The preceding rules describe the set of files that must be compiled to
3030 generate the object files for a program. Each object file has the same
3031 name as the corresponding source file, except that the extension is
3034 You may wish to compile other files for the purpose of checking their
3035 syntactic and semantic correctness. For example, in the case where a
3036 package has a separate spec and body, you would not normally compile the
3037 spec. However, it is convenient in practice to compile the spec to make
3038 sure it is error-free before compiling clients of this spec, because such
3039 compilations will fail if there is an error in the spec.
3041 GNAT provides an option for compiling such files purely for the
3042 purposes of checking correctness; such compilations are not required as
3043 part of the process of building a program. To compile a file in this
3044 checking mode, use the @code{-gnatc} switch.
3046 @node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3047 @anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{27}
3048 @section Source Dependencies
3051 A given object file clearly depends on the source file which is compiled
3052 to produce it. Here we are using “depends” in the sense of a typical
3053 @code{make} utility; in other words, an object file depends on a source
3054 file if changes to the source file require the object file to be
3056 In addition to this basic dependency, a given object may depend on
3057 additional source files as follows:
3063 If a file being compiled `with's a unit @code{X}, the object file
3064 depends on the file containing the spec of unit @code{X}. This includes
3065 files that are `with'ed implicitly either because they are parents
3066 of `with'ed child units or they are run-time units required by the
3067 language constructs used in a particular unit.
3070 If a file being compiled instantiates a library level generic unit, the
3071 object file depends on both the spec and body files for this generic
3075 If a file being compiled instantiates a generic unit defined within a
3076 package, the object file depends on the body file for the package as
3077 well as the spec file.
3082 @geindex -gnatn switch
3088 If a file being compiled contains a call to a subprogram for which
3089 pragma @code{Inline} applies and inlining is activated with the
3090 @code{-gnatn} switch, the object file depends on the file containing the
3091 body of this subprogram as well as on the file containing the spec. Note
3092 that for inlining to actually occur as a result of the use of this switch,
3093 it is necessary to compile in optimizing mode.
3095 @geindex -gnatN switch
3097 The use of @code{-gnatN} activates inlining optimization
3098 that is performed by the front end of the compiler. This inlining does
3099 not require that the code generation be optimized. Like @code{-gnatn},
3100 the use of this switch generates additional dependencies.
3102 When using a gcc-based back end, then the use of
3103 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
3104 Historically front end inlining was more extensive than the gcc back end
3105 inlining, but that is no longer the case.
3108 If an object file @code{O} depends on the proper body of a subunit through
3109 inlining or instantiation, it depends on the parent unit of the subunit.
3110 This means that any modification of the parent unit or one of its subunits
3111 affects the compilation of @code{O}.
3114 The object file for a parent unit depends on all its subunit body files.
3117 The previous two rules meant that for purposes of computing dependencies and
3118 recompilation, a body and all its subunits are treated as an indivisible whole.
3120 These rules are applied transitively: if unit @code{A} `with's
3121 unit @code{B}, whose elaboration calls an inlined procedure in package
3122 @code{C}, the object file for unit @code{A} will depend on the body of
3123 @code{C}, in file @code{c.adb}.
3125 The set of dependent files described by these rules includes all the
3126 files on which the unit is semantically dependent, as dictated by the
3127 Ada language standard. However, it is a superset of what the
3128 standard describes, because it includes generic, inline, and subunit
3131 An object file must be recreated by recompiling the corresponding source
3132 file if any of the source files on which it depends are modified. For
3133 example, if the @code{make} utility is used to control compilation,
3134 the rule for an Ada object file must mention all the source files on
3135 which the object file depends, according to the above definition.
3136 The determination of the necessary
3137 recompilations is done automatically when one uses @code{gnatmake}.
3140 @node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3141 @anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{66}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{28}
3142 @section The Ada Library Information Files
3145 @geindex Ada Library Information files
3149 Each compilation actually generates two output files. The first of these
3150 is the normal object file that has a @code{.o} extension. The second is a
3151 text file containing full dependency information. It has the same
3152 name as the source file, but an @code{.ali} extension.
3153 This file is known as the Ada Library Information (@code{ALI}) file.
3154 The following information is contained in the @code{ALI} file.
3160 Version information (indicates which version of GNAT was used to compile
3161 the unit(s) in question)
3164 Main program information (including priority and time slice settings,
3165 as well as the wide character encoding used during compilation).
3168 List of arguments used in the @code{gcc} command for the compilation
3171 Attributes of the unit, including configuration pragmas used, an indication
3172 of whether the compilation was successful, exception model used etc.
3175 A list of relevant restrictions applying to the unit (used for consistency)
3179 Categorization information (e.g., use of pragma @code{Pure}).
3182 Information on all `with'ed units, including presence of
3183 @code{Elaborate} or @code{Elaborate_All} pragmas.
3186 Information from any @code{Linker_Options} pragmas used in the unit
3189 Information on the use of @code{Body_Version} or @code{Version}
3190 attributes in the unit.
3193 Dependency information. This is a list of files, together with
3194 time stamp and checksum information. These are files on which
3195 the unit depends in the sense that recompilation is required
3196 if any of these units are modified.
3199 Cross-reference data. Contains information on all entities referenced
3200 in the unit. Used by some tools to provide cross-reference information.
3203 For a full detailed description of the format of the @code{ALI} file,
3204 see the source of the body of unit @code{Lib.Writ}, contained in file
3205 @code{lib-writ.adb} in the GNAT compiler sources.
3207 @node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3208 @anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{29}@anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{67}
3209 @section Binding an Ada Program
3212 When using languages such as C and C++, once the source files have been
3213 compiled the only remaining step in building an executable program
3214 is linking the object modules together. This means that it is possible to
3215 link an inconsistent version of a program, in which two units have
3216 included different versions of the same header.
3218 The rules of Ada do not permit such an inconsistent program to be built.
3219 For example, if two clients have different versions of the same package,
3220 it is illegal to build a program containing these two clients.
3221 These rules are enforced by the GNAT binder, which also determines an
3222 elaboration order consistent with the Ada rules.
3224 The GNAT binder is run after all the object files for a program have
3225 been created. It is given the name of the main program unit, and from
3226 this it determines the set of units required by the program, by reading the
3227 corresponding ALI files. It generates error messages if the program is
3228 inconsistent or if no valid order of elaboration exists.
3230 If no errors are detected, the binder produces a main program, in Ada by
3231 default, that contains calls to the elaboration procedures of those
3232 compilation unit that require them, followed by
3233 a call to the main program. This Ada program is compiled to generate the
3234 object file for the main program. The name of
3235 the Ada file is @code{b~xxx.adb} (with the corresponding spec
3236 @code{b~xxx.ads}) where @code{xxx} is the name of the
3239 Finally, the linker is used to build the resulting executable program,
3240 using the object from the main program from the bind step as well as the
3241 object files for the Ada units of the program.
3243 @node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3244 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{2a}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{68}
3245 @section GNAT and Libraries
3248 @geindex Library building and using
3250 This section describes how to build and use libraries with GNAT, and also shows
3251 how to recompile the GNAT run-time library. You should be familiar with the
3252 Project Manager facility (see the `GNAT_Project_Manager' chapter of the
3253 `GPRbuild User’s Guide') before reading this chapter.
3256 * Introduction to Libraries in GNAT::
3257 * General Ada Libraries::
3258 * Stand-alone Ada Libraries::
3259 * Rebuilding the GNAT Run-Time Library::
3263 @node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3264 @anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{69}@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{6a}
3265 @subsection Introduction to Libraries in GNAT
3268 A library is, conceptually, a collection of objects which does not have its
3269 own main thread of execution, but rather provides certain services to the
3270 applications that use it. A library can be either statically linked with the
3271 application, in which case its code is directly included in the application,
3272 or, on platforms that support it, be dynamically linked, in which case
3273 its code is shared by all applications making use of this library.
3275 GNAT supports both types of libraries.
3276 In the static case, the compiled code can be provided in different ways. The
3277 simplest approach is to provide directly the set of objects resulting from
3278 compilation of the library source files. Alternatively, you can group the
3279 objects into an archive using whatever commands are provided by the operating
3280 system. For the latter case, the objects are grouped into a shared library.
3282 In the GNAT environment, a library has three types of components:
3291 @code{ALI} files (see @ref{28,,The Ada Library Information Files}), and
3294 Object files, an archive or a shared library.
3297 A GNAT library may expose all its source files, which is useful for
3298 documentation purposes. Alternatively, it may expose only the units needed by
3299 an external user to make use of the library. That is to say, the specs
3300 reflecting the library services along with all the units needed to compile
3301 those specs, which can include generic bodies or any body implementing an
3302 inlined routine. In the case of `stand-alone libraries' those exposed
3303 units are called `interface units' (@ref{6b,,Stand-alone Ada Libraries}).
3305 All compilation units comprising an application, including those in a library,
3306 need to be elaborated in an order partially defined by Ada’s semantics. GNAT
3307 computes the elaboration order from the @code{ALI} files and this is why they
3308 constitute a mandatory part of GNAT libraries.
3309 `Stand-alone libraries' are the exception to this rule because a specific
3310 library elaboration routine is produced independently of the application(s)
3313 @node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3314 @anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{6d}
3315 @subsection General Ada Libraries
3319 * Building a library::
3320 * Installing a library::
3325 @node Building a library,Installing a library,,General Ada Libraries
3326 @anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{6e}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{6f}
3327 @subsubsection Building a library
3330 The easiest way to build a library is to use the Project Manager,
3331 which supports a special type of project called a `Library Project'
3332 (see the `Library Projects' section in the `GNAT Project Manager'
3333 chapter of the `GPRbuild User’s Guide').
3335 A project is considered a library project, when two project-level attributes
3336 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
3337 control different aspects of library configuration, additional optional
3338 project-level attributes can be specified:
3347 @item @code{Library_Kind}
3349 This attribute controls whether the library is to be static or dynamic
3356 @item @code{Library_Version}
3358 This attribute specifies the library version; this value is used
3359 during dynamic linking of shared libraries to determine if the currently
3360 installed versions of the binaries are compatible.
3364 @code{Library_Options}
3370 @item @code{Library_GCC}
3372 These attributes specify additional low-level options to be used during
3373 library generation, and redefine the actual application used to generate
3378 The GNAT Project Manager takes full care of the library maintenance task,
3379 including recompilation of the source files for which objects do not exist
3380 or are not up to date, assembly of the library archive, and installation of
3381 the library (i.e., copying associated source, object and @code{ALI} files
3382 to the specified location).
3384 Here is a simple library project file:
3388 for Source_Dirs use ("src1", "src2");
3389 for Object_Dir use "obj";
3390 for Library_Name use "mylib";
3391 for Library_Dir use "lib";
3392 for Library_Kind use "dynamic";
3396 and the compilation command to build and install the library:
3402 It is not entirely trivial to perform manually all the steps required to
3403 produce a library. We recommend that you use the GNAT Project Manager
3404 for this task. In special cases where this is not desired, the necessary
3405 steps are discussed below.
3407 There are various possibilities for compiling the units that make up the
3408 library: for example with a Makefile (@ref{70,,Using the GNU make Utility}) or
3409 with a conventional script. For simple libraries, it is also possible to create
3410 a dummy main program which depends upon all the packages that comprise the
3411 interface of the library. This dummy main program can then be given to
3412 @code{gnatmake}, which will ensure that all necessary objects are built.
3414 After this task is accomplished, you should follow the standard procedure
3415 of the underlying operating system to produce the static or shared library.
3417 Here is an example of such a dummy program:
3420 with My_Lib.Service1;
3421 with My_Lib.Service2;
3422 with My_Lib.Service3;
3423 procedure My_Lib_Dummy is
3429 Here are the generic commands that will build an archive or a shared library.
3432 # compiling the library
3433 $ gnatmake -c my_lib_dummy.adb
3435 # we don't need the dummy object itself
3436 $ rm my_lib_dummy.o my_lib_dummy.ali
3438 # create an archive with the remaining objects
3439 $ ar rc libmy_lib.a *.o
3440 # some systems may require "ranlib" to be run as well
3442 # or create a shared library
3443 $ gcc -shared -o libmy_lib.so *.o
3444 # some systems may require the code to have been compiled with -fPIC
3446 # remove the object files that are now in the library
3449 # Make the ALI files read-only so that gnatmake will not try to
3450 # regenerate the objects that are in the library
3454 Please note that the library must have a name of the form @code{lib`xxx'.a}
3455 or @code{lib`xxx'.so} (or @code{lib`xxx'.dll} on Windows) in order to
3456 be accessed by the directive @code{-l`xxx'} at link time.
3458 @node Installing a library,Using a library,Building a library,General Ada Libraries
3459 @anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{72}
3460 @subsubsection Installing a library
3463 @geindex ADA_PROJECT_PATH
3465 @geindex GPR_PROJECT_PATH
3467 If you use project files, library installation is part of the library build
3468 process (see the `Installing a Library with Project Files' section of the
3469 `GNAT Project Manager' chapter of the `GPRbuild User’s Guide').
3471 When project files are not an option, it is also possible, but not recommended,
3472 to install the library so that the sources needed to use the library are on the
3473 Ada source path and the ALI files & libraries be on the Ada Object path (see
3474 @ref{73,,Search Paths and the Run-Time Library (RTL)}). Alternatively, the system
3475 administrator can place general-purpose libraries in the default compiler
3476 paths, by specifying the libraries’ location in the configuration files
3477 @code{ada_source_path} and @code{ada_object_path}. These configuration files
3478 must be located in the GNAT installation tree at the same place as the gcc spec
3479 file. The location of the gcc spec file can be determined as follows:
3485 The configuration files mentioned above have a simple format: each line
3486 must contain one unique directory name.
3487 Those names are added to the corresponding path
3488 in their order of appearance in the file. The names can be either absolute
3489 or relative; in the latter case, they are relative to where theses files
3492 The files @code{ada_source_path} and @code{ada_object_path} might not be
3494 GNAT installation, in which case, GNAT will look for its run-time library in
3495 the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3496 objects and @code{ALI} files). When the files exist, the compiler does not
3497 look in @code{adainclude} and @code{adalib}, and thus the
3498 @code{ada_source_path} file
3499 must contain the location for the GNAT run-time sources (which can simply
3500 be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3501 contain the location for the GNAT run-time objects (which can simply
3504 You can also specify a new default path to the run-time library at compilation
3505 time with the switch @code{--RTS=rts-path}. You can thus choose / change
3506 the run-time library you want your program to be compiled with. This switch is
3507 recognized by @code{gcc}, @code{gnatmake}, @code{gnatbind}, @code{gnatls}, and all
3508 project aware tools.
3510 It is possible to install a library before or after the standard GNAT
3511 library, by reordering the lines in the configuration files. In general, a
3512 library must be installed before the GNAT library if it redefines
3515 @node Using a library,,Installing a library,General Ada Libraries
3516 @anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{74}@anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{75}
3517 @subsubsection Using a library
3520 Once again, the project facility greatly simplifies the use of
3521 libraries. In this context, using a library is just a matter of adding a
3522 `with' clause in the user project. For instance, to make use of the
3523 library @code{My_Lib} shown in examples in earlier sections, you can
3533 Even if you have a third-party, non-Ada library, you can still use GNAT’s
3534 Project Manager facility to provide a wrapper for it. For example, the
3535 following project, when `with'ed by your main project, will link with the
3536 third-party library @code{liba.a}:
3540 for Externally_Built use "true";
3541 for Source_Files use ();
3542 for Library_Dir use "lib";
3543 for Library_Name use "a";
3544 for Library_Kind use "static";
3548 This is an alternative to the use of @code{pragma Linker_Options}. It is
3549 especially interesting in the context of systems with several interdependent
3550 static libraries where finding a proper linker order is not easy and best be
3551 left to the tools having visibility over project dependence information.
3553 In order to use an Ada library manually, you need to make sure that this
3554 library is on both your source and object path
3555 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}
3556 and @ref{76,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3557 in an archive or a shared library, you need to specify the desired
3558 library at link time.
3560 For example, you can use the library @code{mylib} installed in
3561 @code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3564 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3568 This can be expressed more simply:
3574 when the following conditions are met:
3580 @code{/dir/my_lib_src} has been added by the user to the environment
3582 @geindex ADA_INCLUDE_PATH
3583 @geindex environment variable; ADA_INCLUDE_PATH
3584 @code{ADA_INCLUDE_PATH}, or by the administrator to the file
3585 @code{ada_source_path}
3588 @code{/dir/my_lib_obj} has been added by the user to the environment
3590 @geindex ADA_OBJECTS_PATH
3591 @geindex environment variable; ADA_OBJECTS_PATH
3592 @code{ADA_OBJECTS_PATH}, or by the administrator to the file
3593 @code{ada_object_path}
3596 a pragma @code{Linker_Options} has been added to one of the sources.
3600 pragma Linker_Options ("-lmy_lib");
3604 Note that you may also load a library dynamically at
3605 run time given its filename, as illustrated in the GNAT @code{plugins} example
3606 in the directory @code{share/examples/gnat/plugins} within the GNAT
3609 @node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3610 @anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{6b}
3611 @subsection Stand-alone Ada Libraries
3614 @geindex Stand-alone libraries
3617 * Introduction to Stand-alone Libraries::
3618 * Building a Stand-alone Library::
3619 * Creating a Stand-alone Library to be used in a non-Ada context::
3620 * Restrictions in Stand-alone Libraries::
3624 @node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3625 @anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{78}@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{79}
3626 @subsubsection Introduction to Stand-alone Libraries
3629 A Stand-alone Library (abbreviated ‘SAL’) is a library that contains the
3631 elaborate the Ada units that are included in the library. In contrast with
3632 an ordinary library, which consists of all sources, objects and @code{ALI}
3634 library, a SAL may specify a restricted subset of compilation units
3635 to serve as a library interface. In this case, the fully
3636 self-sufficient set of files will normally consist of an objects
3637 archive, the sources of interface units’ specs, and the @code{ALI}
3638 files of interface units.
3639 If an interface spec contains a generic unit or an inlined subprogram,
3641 source must also be provided; if the units that must be provided in the source
3642 form depend on other units, the source and @code{ALI} files of those must
3645 The main purpose of a SAL is to minimize the recompilation overhead of client
3646 applications when a new version of the library is installed. Specifically,
3647 if the interface sources have not changed, client applications do not need to
3648 be recompiled. If, furthermore, a SAL is provided in the shared form and its
3649 version, controlled by @code{Library_Version} attribute, is not changed,
3650 then the clients do not need to be relinked.
3652 SALs also allow the library providers to minimize the amount of library source
3653 text exposed to the clients. Such ‘information hiding’ might be useful or
3654 necessary for various reasons.
3656 Stand-alone libraries are also well suited to be used in an executable whose
3657 main routine is not written in Ada.
3659 @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
3660 @anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{7a}@anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{7b}
3661 @subsubsection Building a Stand-alone Library
3664 GNAT’s Project facility provides a simple way of building and installing
3665 stand-alone libraries; see the `Stand-alone Library Projects' section
3666 in the `GNAT Project Manager' chapter of the `GPRbuild User’s Guide'.
3667 To be a Stand-alone Library Project, in addition to the two attributes
3668 that make a project a Library Project (@code{Library_Name} and
3669 @code{Library_Dir}; see the `Library Projects' section in the
3670 `GNAT Project Manager' chapter of the `GPRbuild User’s Guide'),
3671 the attribute @code{Library_Interface} must be defined. For example:
3674 for Library_Dir use "lib_dir";
3675 for Library_Name use "dummy";
3676 for Library_Interface use ("int1", "int1.child");
3679 Attribute @code{Library_Interface} has a non-empty string list value,
3680 each string in the list designating a unit contained in an immediate source
3681 of the project file.
3683 When a Stand-alone Library is built, first the binder is invoked to build
3684 a package whose name depends on the library name
3685 (@code{b~dummy.ads/b} in the example above).
3686 This binder-generated package includes initialization and
3687 finalization procedures whose
3688 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
3690 above). The object corresponding to this package is included in the library.
3692 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
3693 calling of these procedures if a static SAL is built, or if a shared SAL
3695 with the project-level attribute @code{Library_Auto_Init} set to
3698 For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
3699 (those that are listed in attribute @code{Library_Interface}) are copied to
3700 the Library Directory. As a consequence, only the Interface Units may be
3701 imported from Ada units outside of the library. If other units are imported,
3702 the binding phase will fail.
3704 It is also possible to build an encapsulated library where not only
3705 the code to elaborate and finalize the library is embedded but also
3706 ensuring that the library is linked only against static
3707 libraries. So an encapsulated library only depends on system
3708 libraries, all other code, including the GNAT runtime, is embedded. To
3709 build an encapsulated library the attribute
3710 @code{Library_Standalone} must be set to @code{encapsulated}:
3713 for Library_Dir use "lib_dir";
3714 for Library_Name use "dummy";
3715 for Library_Kind use "dynamic";
3716 for Library_Interface use ("int1", "int1.child");
3717 for Library_Standalone use "encapsulated";
3720 The default value for this attribute is @code{standard} in which case
3721 a stand-alone library is built.
3723 The attribute @code{Library_Src_Dir} may be specified for a
3724 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
3725 single string value. Its value must be the path (absolute or relative to the
3726 project directory) of an existing directory. This directory cannot be the
3727 object directory or one of the source directories, but it can be the same as
3728 the library directory. The sources of the Interface
3729 Units of the library that are needed by an Ada client of the library will be
3730 copied to the designated directory, called the Interface Copy directory.
3731 These sources include the specs of the Interface Units, but they may also
3732 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
3733 are used, or when there is a generic unit in the spec. Before the sources
3734 are copied to the Interface Copy directory, an attempt is made to delete all
3735 files in the Interface Copy directory.
3737 Building stand-alone libraries by hand is somewhat tedious, but for those
3738 occasions when it is necessary here are the steps that you need to perform:
3744 Compile all library sources.
3747 Invoke the binder with the switch @code{-n} (No Ada main program),
3748 with all the @code{ALI} files of the interfaces, and
3749 with the switch @code{-L} to give specific names to the @code{init}
3750 and @code{final} procedures. For example:
3753 $ gnatbind -n int1.ali int2.ali -Lsal1
3757 Compile the binder generated file:
3764 Link the dynamic library with all the necessary object files,
3765 indicating to the linker the names of the @code{init} (and possibly
3766 @code{final}) procedures for automatic initialization (and finalization).
3767 The built library should be placed in a directory different from
3768 the object directory.
3771 Copy the @code{ALI} files of the interface to the library directory,
3772 add in this copy an indication that it is an interface to a SAL
3773 (i.e., add a word @code{SL} on the line in the @code{ALI} file that starts
3774 with letter ‘P’) and make the modified copy of the @code{ALI} file
3778 Using SALs is not different from using other libraries
3779 (see @ref{75,,Using a library}).
3781 @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
3782 @anchor{gnat_ugn/the_gnat_compilation_model creating-a-stand-alone-library-to-be-used-in-a-non-ada-context}@anchor{7c}@anchor{gnat_ugn/the_gnat_compilation_model id44}@anchor{7d}
3783 @subsubsection Creating a Stand-alone Library to be used in a non-Ada context
3786 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
3789 The only extra step required is to ensure that library interface subprograms
3790 are compatible with the main program, by means of @code{pragma Export}
3791 or @code{pragma Convention}.
3793 Here is an example of simple library interface for use with C main program:
3796 package My_Package is
3798 procedure Do_Something;
3799 pragma Export (C, Do_Something, "do_something");
3801 procedure Do_Something_Else;
3802 pragma Export (C, Do_Something_Else, "do_something_else");
3807 On the foreign language side, you must provide a ‘foreign’ view of the
3808 library interface; remember that it should contain elaboration routines in
3809 addition to interface subprograms.
3811 The example below shows the content of @code{mylib_interface.h} (note
3812 that there is no rule for the naming of this file, any name can be used)
3815 /* the library elaboration procedure */
3816 extern void mylibinit (void);
3818 /* the library finalization procedure */
3819 extern void mylibfinal (void);
3821 /* the interface exported by the library */
3822 extern void do_something (void);
3823 extern void do_something_else (void);
3826 Libraries built as explained above can be used from any program, provided
3827 that the elaboration procedures (named @code{mylibinit} in the previous
3828 example) are called before the library services are used. Any number of
3829 libraries can be used simultaneously, as long as the elaboration
3830 procedure of each library is called.
3832 Below is an example of a C program that uses the @code{mylib} library.
3835 #include "mylib_interface.h"
3840 /* First, elaborate the library before using it */
3843 /* Main program, using the library exported entities */
3845 do_something_else ();
3847 /* Library finalization at the end of the program */
3853 Note that invoking any library finalization procedure generated by
3854 @code{gnatbind} shuts down the Ada run-time environment.
3856 finalization of all Ada libraries must be performed at the end of the program.
3857 No call to these libraries or to the Ada run-time library should be made
3858 after the finalization phase.
3860 Note also that special care must be taken with multi-tasks
3861 applications. The initialization and finalization routines are not
3862 protected against concurrent access. If such requirement is needed it
3863 must be ensured at the application level using a specific operating
3864 system services like a mutex or a critical-section.
3866 @node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
3867 @anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{7e}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{7f}
3868 @subsubsection Restrictions in Stand-alone Libraries
3871 The pragmas listed below should be used with caution inside libraries,
3872 as they can create incompatibilities with other Ada libraries:
3878 pragma @code{Locking_Policy}
3881 pragma @code{Partition_Elaboration_Policy}
3884 pragma @code{Queuing_Policy}
3887 pragma @code{Task_Dispatching_Policy}
3890 pragma @code{Unreserve_All_Interrupts}
3893 When using a library that contains such pragmas, the user must make sure
3894 that all libraries use the same pragmas with the same values. Otherwise,
3895 @code{Program_Error} will
3896 be raised during the elaboration of the conflicting
3897 libraries. The usage of these pragmas and its consequences for the user
3898 should therefore be well documented.
3900 Similarly, the traceback in the exception occurrence mechanism should be
3901 enabled or disabled in a consistent manner across all libraries.
3902 Otherwise, Program_Error will be raised during the elaboration of the
3903 conflicting libraries.
3905 If the @code{Version} or @code{Body_Version}
3906 attributes are used inside a library, then you need to
3907 perform a @code{gnatbind} step that specifies all @code{ALI} files in all
3908 libraries, so that version identifiers can be properly computed.
3909 In practice these attributes are rarely used, so this is unlikely
3910 to be a consideration.
3912 @node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
3913 @anchor{gnat_ugn/the_gnat_compilation_model id46}@anchor{80}@anchor{gnat_ugn/the_gnat_compilation_model rebuilding-the-gnat-run-time-library}@anchor{81}
3914 @subsection Rebuilding the GNAT Run-Time Library
3917 @geindex GNAT Run-Time Library
3920 @geindex Building the GNAT Run-Time Library
3922 @geindex Rebuilding the GNAT Run-Time Library
3924 @geindex Run-Time Library
3927 It may be useful to recompile the GNAT library in various debugging or
3928 experimentation contexts. A project file called
3929 @code{libada.gpr} is provided to that effect and can be found in
3930 the directory containing the GNAT library. The location of this
3931 directory depends on the way the GNAT environment has been installed and can
3932 be determined by means of the command:
3938 The last entry in the source search path usually contains the
3939 gnat library (the @code{adainclude} directory). This project file contains its
3940 own documentation and in particular the set of instructions needed to rebuild a
3941 new library and to use it.
3943 Note that rebuilding the GNAT Run-Time is only recommended for temporary
3944 experiments or debugging, and is not supported.
3946 @geindex Conditional compilation
3948 @node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
3949 @anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{2b}@anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{82}
3950 @section Conditional Compilation
3953 This section presents some guidelines for modeling conditional compilation in Ada and describes the
3954 gnatprep preprocessor utility.
3956 @geindex Conditional compilation
3959 * Modeling Conditional Compilation in Ada::
3960 * Preprocessing with gnatprep::
3961 * Integrated Preprocessing::
3965 @node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
3966 @anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{83}@anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{84}
3967 @subsection Modeling Conditional Compilation in Ada
3970 It is often necessary to arrange for a single source program
3971 to serve multiple purposes, where it is compiled in different
3972 ways to achieve these different goals. Some examples of the
3973 need for this feature are
3979 Adapting a program to a different hardware environment
3982 Adapting a program to a different target architecture
3985 Turning debugging features on and off
3988 Arranging for a program to compile with different compilers
3991 In C, or C++, the typical approach would be to use the preprocessor
3992 that is defined as part of the language. The Ada language does not
3993 contain such a feature. This is not an oversight, but rather a very
3994 deliberate design decision, based on the experience that overuse of
3995 the preprocessing features in C and C++ can result in programs that
3996 are extremely difficult to maintain. For example, if we have ten
3997 switches that can be on or off, this means that there are a thousand
3998 separate programs, any one of which might not even be syntactically
3999 correct, and even if syntactically correct, the resulting program
4000 might not work correctly. Testing all combinations can quickly become
4003 Nevertheless, the need to tailor programs certainly exists, and in
4004 this section we will discuss how this can
4005 be achieved using Ada in general, and GNAT in particular.
4008 * Use of Boolean Constants::
4009 * Debugging - A Special Case::
4010 * Conditionalizing Declarations::
4011 * Use of Alternative Implementations::
4016 @node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4017 @anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{85}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{86}
4018 @subsubsection Use of Boolean Constants
4021 In the case where the difference is simply which code
4022 sequence is executed, the cleanest solution is to use Boolean
4023 constants to control which code is executed.
4026 FP_Initialize_Required : constant Boolean := True;
4028 if FP_Initialize_Required then
4033 Not only will the code inside the @code{if} statement not be executed if
4034 the constant Boolean is @code{False}, but it will also be completely
4035 deleted from the program.
4036 However, the code is only deleted after the @code{if} statement
4037 has been checked for syntactic and semantic correctness.
4038 (In contrast, with preprocessors the code is deleted before the
4039 compiler ever gets to see it, so it is not checked until the switch
4042 @geindex Preprocessors (contrasted with conditional compilation)
4044 Typically the Boolean constants will be in a separate package,
4049 FP_Initialize_Required : constant Boolean := True;
4050 Reset_Available : constant Boolean := False;
4055 The @code{Config} package exists in multiple forms for the various targets,
4056 with an appropriate script selecting the version of @code{Config} needed.
4057 Then any other unit requiring conditional compilation can do a `with'
4058 of @code{Config} to make the constants visible.
4060 @node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4061 @anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{87}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{88}
4062 @subsubsection Debugging - A Special Case
4065 A common use of conditional code is to execute statements (for example
4066 dynamic checks, or output of intermediate results) under control of a
4067 debug switch, so that the debugging behavior can be turned on and off.
4068 This can be done using a Boolean constant to control whether the code
4073 Put_Line ("got to the first stage!");
4080 if Debugging and then Temperature > 999.0 then
4081 raise Temperature_Crazy;
4085 @geindex pragma Assert
4087 Since this is a common case, there are special features to deal with
4088 this in a convenient manner. For the case of tests, Ada 2005 has added
4089 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
4090 on the @code{Assert} pragma that has always been available in GNAT, so this
4091 feature may be used with GNAT even if you are not using Ada 2005 features.
4092 The use of pragma @code{Assert} is described in the
4093 @cite{GNAT_Reference_Manual}, but as an
4094 example, the last test could be written:
4097 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4103 pragma Assert (Temperature <= 999.0);
4106 In both cases, if assertions are active and the temperature is excessive,
4107 the exception @code{Assert_Failure} will be raised, with the given string in
4108 the first case or a string indicating the location of the pragma in the second
4109 case used as the exception message.
4111 @geindex pragma Assertion_Policy
4113 You can turn assertions on and off by using the @code{Assertion_Policy}
4116 @geindex -gnata switch
4118 This is an Ada 2005 pragma which is implemented in all modes by
4119 GNAT. Alternatively, you can use the @code{-gnata} switch
4120 to enable assertions from the command line, which applies to
4121 all versions of Ada.
4123 @geindex pragma Debug
4125 For the example above with the @code{Put_Line}, the GNAT-specific pragma
4126 @code{Debug} can be used:
4129 pragma Debug (Put_Line ("got to the first stage!"));
4132 If debug pragmas are enabled, the argument, which must be of the form of
4133 a procedure call, is executed (in this case, @code{Put_Line} will be called).
4134 Only one call can be present, but of course a special debugging procedure
4135 containing any code you like can be included in the program and then
4136 called in a pragma @code{Debug} argument as needed.
4138 One advantage of pragma @code{Debug} over the @code{if Debugging then}
4139 construct is that pragma @code{Debug} can appear in declarative contexts,
4140 such as at the very beginning of a procedure, before local declarations have
4143 @geindex pragma Debug_Policy
4145 Debug pragmas are enabled using either the @code{-gnata} switch that also
4146 controls assertions, or with a separate Debug_Policy pragma.
4148 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4149 in Ada 95 and Ada 83 programs as well), and is analogous to
4150 pragma @code{Assertion_Policy} to control assertions.
4152 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
4153 and thus they can appear in @code{gnat.adc} if you are not using a
4154 project file, or in the file designated to contain configuration pragmas
4156 They then apply to all subsequent compilations. In practice the use of
4157 the @code{-gnata} switch is often the most convenient method of controlling
4158 the status of these pragmas.
4160 Note that a pragma is not a statement, so in contexts where a statement
4161 sequence is required, you can’t just write a pragma on its own. You have
4162 to add a @code{null} statement.
4166 ... -- some statements
4168 pragma Assert (Num_Cases < 10);
4173 @node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4174 @anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{89}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{8a}
4175 @subsubsection Conditionalizing Declarations
4178 In some cases it may be necessary to conditionalize declarations to meet
4179 different requirements. For example we might want a bit string whose length
4180 is set to meet some hardware message requirement.
4182 This may be possible using declare blocks controlled
4183 by conditional constants:
4186 if Small_Machine then
4188 X : Bit_String (1 .. 10);
4194 X : Large_Bit_String (1 .. 1000);
4201 Note that in this approach, both declarations are analyzed by the
4202 compiler so this can only be used where both declarations are legal,
4203 even though one of them will not be used.
4205 Another approach is to define integer constants, e.g., @code{Bits_Per_Word},
4206 or Boolean constants, e.g., @code{Little_Endian}, and then write declarations
4207 that are parameterized by these constants. For example
4211 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4215 If @code{Bits_Per_Word} is set to 32, this generates either
4219 Field1 at 0 range 0 .. 32;
4223 for the big endian case, or
4227 Field1 at 0 range 10 .. 32;
4231 for the little endian case. Since a powerful subset of Ada expression
4232 notation is usable for creating static constants, clever use of this
4233 feature can often solve quite difficult problems in conditionalizing
4234 compilation (note incidentally that in Ada 95, the little endian
4235 constant was introduced as @code{System.Default_Bit_Order}, so you do not
4236 need to define this one yourself).
4238 @node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4239 @anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{8b}@anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{8c}
4240 @subsubsection Use of Alternative Implementations
4243 In some cases, none of the approaches described above are adequate. This
4244 can occur for example if the set of declarations required is radically
4245 different for two different configurations.
4247 In this situation, the official Ada way of dealing with conditionalizing
4248 such code is to write separate units for the different cases. As long as
4249 this does not result in excessive duplication of code, this can be done
4250 without creating maintenance problems. The approach is to share common
4251 code as far as possible, and then isolate the code and declarations
4252 that are different. Subunits are often a convenient method for breaking
4253 out a piece of a unit that is to be conditionalized, with separate files
4254 for different versions of the subunit for different targets, where the
4255 build script selects the right one to give to the compiler.
4257 @geindex Subunits (and conditional compilation)
4259 As an example, consider a situation where a new feature in Ada 2005
4260 allows something to be done in a really nice way. But your code must be able
4261 to compile with an Ada 95 compiler. Conceptually you want to say:
4265 ... neat Ada 2005 code
4267 ... not quite as neat Ada 95 code
4271 where @code{Ada_2005} is a Boolean constant.
4273 But this won’t work when @code{Ada_2005} is set to @code{False},
4274 since the @code{then} clause will be illegal for an Ada 95 compiler.
4275 (Recall that although such unreachable code would eventually be deleted
4276 by the compiler, it still needs to be legal. If it uses features
4277 introduced in Ada 2005, it will be illegal in Ada 95.)
4282 procedure Insert is separate;
4285 Then we have two files for the subunit @code{Insert}, with the two sets of
4287 If the package containing this is called @code{File_Queries}, then we might
4294 @code{file_queries-insert-2005.adb}
4297 @code{file_queries-insert-95.adb}
4300 and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4302 This can also be done with project files’ naming schemes. For example:
4305 for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4308 Note also that with project files it is desirable to use a different extension
4309 than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4310 conflict may arise through another commonly used feature: to declare as part
4311 of the project a set of directories containing all the sources obeying the
4312 default naming scheme.
4314 The use of alternative units is certainly feasible in all situations,
4315 and for example the Ada part of the GNAT run-time is conditionalized
4316 based on the target architecture using this approach. As a specific example,
4317 consider the implementation of the AST feature in VMS. There is one
4318 spec: @code{s-asthan.ads} which is the same for all architectures, and three
4328 @item @code{s-asthan.adb}
4330 used for all non-VMS operating systems
4337 @item @code{s-asthan-vms-alpha.adb}
4339 used for VMS on the Alpha
4346 @item @code{s-asthan-vms-ia64.adb}
4348 used for VMS on the ia64
4352 The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4353 this operating system feature is not available, and the two remaining
4354 versions interface with the corresponding versions of VMS to provide
4355 VMS-compatible AST handling. The GNAT build script knows the architecture
4356 and operating system, and automatically selects the right version,
4357 renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4359 Another style for arranging alternative implementations is through Ada’s
4360 access-to-subprogram facility.
4361 In case some functionality is to be conditionally included,
4362 you can declare an access-to-procedure variable @code{Ref} that is initialized
4363 to designate a ‘do nothing’ procedure, and then invoke @code{Ref.all}
4365 In some library package, set @code{Ref} to @code{Proc'Access} for some
4366 procedure @code{Proc} that performs the relevant processing.
4367 The initialization only occurs if the library package is included in the
4369 The same idea can also be implemented using tagged types and dispatching
4372 @node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4373 @anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{8d}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{8e}
4374 @subsubsection Preprocessing
4377 @geindex Preprocessing
4379 Although it is quite possible to conditionalize code without the use of
4380 C-style preprocessing, as described earlier in this section, it is
4381 nevertheless convenient in some cases to use the C approach. Moreover,
4382 older Ada compilers have often provided some preprocessing capability,
4383 so legacy code may depend on this approach, even though it is not
4386 To accommodate such use, GNAT provides a preprocessor (modeled to a large
4387 extent on the various preprocessors that have been used
4388 with legacy code on other compilers, to enable easier transition).
4392 The preprocessor may be used in two separate modes. It can be used quite
4393 separately from the compiler, to generate a separate output source file
4394 that is then fed to the compiler as a separate step. This is the
4395 @code{gnatprep} utility, whose use is fully described in
4396 @ref{8f,,Preprocessing with gnatprep}.
4398 The preprocessing language allows such constructs as
4401 #if DEBUG or else (PRIORITY > 4) then
4402 sequence of declarations
4404 completely different sequence of declarations
4408 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
4409 defined either on the command line or in a separate file.
4411 The other way of running the preprocessor is even closer to the C style and
4412 often more convenient. In this approach the preprocessing is integrated into
4413 the compilation process. The compiler is given the preprocessor input which
4414 includes @code{#if} lines etc, and then the compiler carries out the
4415 preprocessing internally and processes the resulting output.
4416 For more details on this approach, see @ref{90,,Integrated Preprocessing}.
4418 @node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4419 @anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{91}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{8f}
4420 @subsection Preprocessing with @code{gnatprep}
4425 @geindex Preprocessing (gnatprep)
4427 This section discusses how to use GNAT’s @code{gnatprep} utility for simple
4429 Although designed for use with GNAT, @code{gnatprep} does not depend on any
4430 special GNAT features.
4431 For further discussion of conditional compilation in general, see
4432 @ref{2b,,Conditional Compilation}.
4435 * Preprocessing Symbols::
4437 * Switches for gnatprep::
4438 * Form of Definitions File::
4439 * Form of Input Text for gnatprep::
4443 @node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4444 @anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{92}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{93}
4445 @subsubsection Preprocessing Symbols
4448 Preprocessing symbols are defined in `definition files' and referenced in the
4449 sources to be preprocessed. A preprocessing symbol is an identifier, following
4450 normal Ada (case-insensitive) rules for its syntax, with the restriction that
4451 all characters need to be in the ASCII set (no accented letters).
4453 @node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4454 @anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{94}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{95}
4455 @subsubsection Using @code{gnatprep}
4458 To call @code{gnatprep} use:
4461 $ gnatprep [ switches ] infile outfile [ deffile ]
4475 is an optional sequence of switches as described in the next section.
4484 is the full name of the input file, which is an Ada source
4485 file containing preprocessor directives.
4494 is the full name of the output file, which is an Ada source
4495 in standard Ada form. When used with GNAT, this file name will
4496 normally have an @code{ads} or @code{adb} suffix.
4503 @item @code{deffile}
4505 is the full name of a text file containing definitions of
4506 preprocessing symbols to be referenced by the preprocessor. This argument is
4507 optional, and can be replaced by the use of the @code{-D} switch.
4511 @node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4512 @anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{96}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{97}
4513 @subsubsection Switches for @code{gnatprep}
4516 @geindex --version (gnatprep)
4521 @item @code{--version}
4523 Display Copyright and version, then exit disregarding all other options.
4526 @geindex --help (gnatprep)
4533 If @code{--version} was not used, display usage and then exit disregarding
4537 @geindex -b (gnatprep)
4544 Causes both preprocessor lines and the lines deleted by
4545 preprocessing to be replaced by blank lines in the output source file,
4546 preserving line numbers in the output file.
4549 @geindex -c (gnatprep)
4556 Causes both preprocessor lines and the lines deleted
4557 by preprocessing to be retained in the output source as comments marked
4558 with the special string @code{"--! "}. This option will result in line numbers
4559 being preserved in the output file.
4562 @geindex -C (gnatprep)
4569 Causes comments to be scanned. Normally comments are ignored by gnatprep.
4570 If this option is specified, then comments are scanned and any $symbol
4571 substitutions performed as in program text. This is particularly useful
4572 when structured comments are used (e.g., for programs written in a
4573 pre-2014 version of the SPARK Ada subset). Note that this switch is not
4574 available when doing integrated preprocessing (it would be useless in
4575 this context since comments are ignored by the compiler in any case).
4578 @geindex -D (gnatprep)
4583 @item @code{-D`symbol'[=`value']}
4585 Defines a new preprocessing symbol with the specified value. If no value is given
4586 on the command line, then symbol is considered to be @code{True}. This switch
4587 can be used in place of a definition file.
4590 @geindex -r (gnatprep)
4597 Causes a @code{Source_Reference} pragma to be generated that
4598 references the original input file, so that error messages will use
4599 the file name of this original file. The use of this switch implies
4600 that preprocessor lines are not to be removed from the file, so its
4601 use will force @code{-b} mode if @code{-c}
4602 has not been specified explicitly.
4604 Note that if the file to be preprocessed contains multiple units, then
4605 it will be necessary to @code{gnatchop} the output file from
4606 @code{gnatprep}. If a @code{Source_Reference} pragma is present
4607 in the preprocessed file, it will be respected by
4609 so that the final chopped files will correctly refer to the original
4610 input source file for @code{gnatprep}.
4613 @geindex -s (gnatprep)
4620 Causes a sorted list of symbol names and values to be
4621 listed on the standard output file.
4624 @geindex -T (gnatprep)
4631 Use LF as line terminators when writing files. By default the line terminator
4632 of the host (LF under unix, CR/LF under Windows) is used.
4635 @geindex -u (gnatprep)
4642 Causes undefined symbols to be treated as having the value FALSE in the context
4643 of a preprocessor test. In the absence of this option, an undefined symbol in
4644 a @code{#if} or @code{#elsif} test will be treated as an error.
4647 @geindex -v (gnatprep)
4654 Verbose mode: generates more output about work done.
4657 Note: if neither @code{-b} nor @code{-c} is present,
4658 then preprocessor lines and
4659 deleted lines are completely removed from the output, unless -r is
4660 specified, in which case -b is assumed.
4662 @node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4663 @anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{98}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{99}
4664 @subsubsection Form of Definitions File
4667 The definitions file contains lines of the form:
4673 where @code{symbol} is a preprocessing symbol, and @code{value} is one of the following:
4679 Empty, corresponding to a null substitution,
4682 A string literal using normal Ada syntax, or
4685 Any sequence of characters from the set @{letters, digits, period, underline@}.
4688 Comment lines may also appear in the definitions file, starting with
4689 the usual @code{--},
4690 and comments may be added to the definitions lines.
4692 @node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4693 @anchor{gnat_ugn/the_gnat_compilation_model form-of-input-text-for-gnatprep}@anchor{9a}@anchor{gnat_ugn/the_gnat_compilation_model id59}@anchor{9b}
4694 @subsubsection Form of Input Text for @code{gnatprep}
4697 The input text may contain preprocessor conditional inclusion lines,
4698 as well as general symbol substitution sequences.
4700 The preprocessor conditional inclusion commands have the form:
4703 #if <expression> [then]
4705 #elsif <expression> [then]
4707 #elsif <expression> [then]
4715 In this example, <expression> is defined by the following grammar:
4718 <expression> ::= <symbol>
4719 <expression> ::= <symbol> = "<value>"
4720 <expression> ::= <symbol> = <symbol>
4721 <expression> ::= <symbol> = <integer>
4722 <expression> ::= <symbol> > <integer>
4723 <expression> ::= <symbol> >= <integer>
4724 <expression> ::= <symbol> < <integer>
4725 <expression> ::= <symbol> <= <integer>
4726 <expression> ::= <symbol> 'Defined
4727 <expression> ::= not <expression>
4728 <expression> ::= <expression> and <expression>
4729 <expression> ::= <expression> or <expression>
4730 <expression> ::= <expression> and then <expression>
4731 <expression> ::= <expression> or else <expression>
4732 <expression> ::= ( <expression> )
4735 Note the following restriction: it is not allowed to have “and” or “or”
4736 following “not” in the same expression without parentheses. For example, this
4743 This can be expressed instead as one of the following forms:
4750 For the first test (<expression> ::= <symbol>) the symbol must have
4751 either the value true or false, that is to say the right-hand of the
4752 symbol definition must be one of the (case-insensitive) literals
4753 @code{True} or @code{False}. If the value is true, then the
4754 corresponding lines are included, and if the value is false, they are
4757 When comparing a symbol to an integer, the integer is any non negative
4758 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
4759 2#11#. The symbol value must also be a non negative integer. Integer values
4760 in the range 0 .. 2**31-1 are supported.
4762 The test (<expression> ::= <symbol>’Defined) is true only if
4763 the symbol has been defined in the definition file or by a @code{-D}
4764 switch on the command line. Otherwise, the test is false.
4766 The equality tests are case insensitive, as are all the preprocessor lines.
4768 If the symbol referenced is not defined in the symbol definitions file,
4769 then the effect depends on whether or not switch @code{-u}
4770 is specified. If so, then the symbol is treated as if it had the value
4771 false and the test fails. If this switch is not specified, then
4772 it is an error to reference an undefined symbol. It is also an error to
4773 reference a symbol that is defined with a value other than @code{True}
4776 The use of the @code{not} operator inverts the sense of this logical test.
4777 The @code{not} operator cannot be combined with the @code{or} or @code{and}
4778 operators, without parentheses. For example, “if not X or Y then” is not
4779 allowed, but “if (not X) or Y then” and “if not (X or Y) then” are.
4781 The @code{then} keyword is optional as shown
4783 The @code{#} must be the first non-blank character on a line, but
4784 otherwise the format is free form. Spaces or tabs may appear between
4785 the @code{#} and the keyword. The keywords and the symbols are case
4786 insensitive as in normal Ada code. Comments may be used on a
4787 preprocessor line, but other than that, no other tokens may appear on a
4788 preprocessor line. Any number of @code{elsif} clauses can be present,
4789 including none at all. The @code{else} is optional, as in Ada.
4791 The @code{#} marking the start of a preprocessor line must be the first
4792 non-blank character on the line, i.e., it must be preceded only by
4793 spaces or horizontal tabs.
4795 Symbol substitution outside of preprocessor lines is obtained by using
4802 anywhere within a source line, except in a comment or within a
4803 string literal. The identifier
4804 following the @code{$} must match one of the symbols defined in the symbol
4805 definition file, and the result is to substitute the value of the
4806 symbol in place of @code{$symbol} in the output file.
4808 Note that although the substitution of strings within a string literal
4809 is not possible, it is possible to have a symbol whose defined value is
4810 a string literal. So instead of setting XYZ to @code{hello} and writing:
4813 Header : String := "$XYZ";
4816 you should set XYZ to @code{"hello"} and write:
4819 Header : String := $XYZ;
4822 and then the substitution will occur as desired.
4824 @node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
4825 @anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{9c}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{90}
4826 @subsection Integrated Preprocessing
4829 As noted above, a file to be preprocessed consists of Ada source code
4830 in which preprocessing lines have been inserted. However,
4831 instead of using @code{gnatprep} to explicitly preprocess a file as a separate
4832 step before compilation, you can carry out the preprocessing implicitly
4833 as part of compilation. Such `integrated preprocessing', which is the common
4834 style with C, is performed when either or both of the following switches
4835 are passed to the compiler:
4843 @code{-gnatep}, which specifies the `preprocessor data file'.
4844 This file dictates how the source files will be preprocessed (e.g., which
4845 symbol definition files apply to which sources).
4848 @code{-gnateD}, which defines values for preprocessing symbols.
4852 Integrated preprocessing applies only to Ada source files, it is
4853 not available for configuration pragma files.
4855 With integrated preprocessing, the output from the preprocessor is not,
4856 by default, written to any external file. Instead it is passed
4857 internally to the compiler. To preserve the result of
4858 preprocessing in a file, either run @code{gnatprep}
4859 in standalone mode or else supply the @code{-gnateG} switch
4860 (described below) to the compiler.
4862 When using project files:
4870 the builder switch @code{-x} should be used if any Ada source is
4871 compiled with @code{gnatep=}, so that the compiler finds the
4872 `preprocessor data file'.
4875 the preprocessing data file and the symbol definition files should be
4876 located in the source directories of the project.
4880 Note that the @code{gnatmake} switch @code{-m} will almost
4881 always trigger recompilation for sources that are preprocessed,
4882 because @code{gnatmake} cannot compute the checksum of the source after
4885 The actual preprocessing function is described in detail in
4886 @ref{8f,,Preprocessing with gnatprep}. This section explains the switches
4887 that relate to integrated preprocessing.
4889 @geindex -gnatep (gcc)
4894 @item @code{-gnatep=`preprocessor_data_file'}
4896 This switch specifies the file name (without directory
4897 information) of the preprocessor data file. Either place this file
4898 in one of the source directories, or, when using project
4899 files, reference the project file’s directory via the
4900 @code{project_name'Project_Dir} project attribute; e.g:
4907 for Switches ("Ada") use
4908 ("-gnatep=" & Prj'Project_Dir & "prep.def");
4914 A preprocessor data file is a text file that contains `preprocessor
4915 control lines'. A preprocessor control line directs the preprocessing of
4916 either a particular source file, or, analogous to @code{others} in Ada,
4917 all sources not specified elsewhere in the preprocessor data file.
4918 A preprocessor control line
4919 can optionally identify a `definition file' that assigns values to
4920 preprocessor symbols, as well as a list of switches that relate to
4922 Empty lines and comments (using Ada syntax) are also permitted, with no
4925 Here’s an example of a preprocessor data file:
4930 "toto.adb" "prep.def" -u
4931 -- Preprocess toto.adb, using definition file prep.def
4932 -- Undefined symbols are treated as False
4935 -- Preprocess all other sources without using a definition file
4936 -- Suppressed lined are commented
4937 -- Symbol VERSION has the value V101
4939 "tata.adb" "prep2.def" -s
4940 -- Preprocess tata.adb, using definition file prep2.def
4941 -- List all symbols with their values
4945 A preprocessor control line has the following syntax:
4950 <preprocessor_control_line> ::=
4951 <preprocessor_input> [ <definition_file_name> ] @{ <switch> @}
4953 <preprocessor_input> ::= <source_file_name> | '*'
4955 <definition_file_name> ::= <string_literal>
4957 <source_file_name> := <string_literal>
4959 <switch> := (See below for list)
4963 Thus each preprocessor control line starts with either a literal string or
4970 A literal string is the file name (without directory information) of the source
4971 file that will be input to the preprocessor.
4974 The character ‘*’ is a wild-card indicator; the additional parameters on the line
4975 indicate the preprocessing for all the sources
4976 that are not specified explicitly on other lines (the order of the lines is not
4980 It is an error to have two lines with the same file name or two
4981 lines starting with the character ‘*’.
4983 After the file name or ‘*’, an optional literal string specifies the name of
4984 the definition file to be used for preprocessing
4985 (@ref{98,,Form of Definitions File}). The definition files are found by the
4986 compiler in one of the source directories. In some cases, when compiling
4987 a source in a directory other than the current directory, if the definition
4988 file is in the current directory, it may be necessary to add the current
4989 directory as a source directory through the @code{-I} switch; otherwise
4990 the compiler would not find the definition file.
4992 Finally, switches similar to those of @code{gnatprep} may optionally appear:
4999 Causes both preprocessor lines and the lines deleted by
5000 preprocessing to be replaced by blank lines, preserving the line number.
5001 This switch is always implied; however, if specified after @code{-c}
5002 it cancels the effect of @code{-c}.
5006 Causes both preprocessor lines and the lines deleted
5007 by preprocessing to be retained as comments marked
5008 with the special string ‘@cite{–!}’.
5010 @item @code{-D`symbol'=`new_value'}
5012 Define or redefine @code{symbol} to have @code{new_value} as its value.
5013 The permitted form for @code{symbol} is either an Ada identifier, or any Ada reserved word
5014 aside from @code{if},
5015 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5016 The permitted form for @code{new_value} is a literal string, an Ada identifier or any Ada reserved
5017 word. A symbol declared with this switch replaces a symbol with the
5018 same name defined in a definition file.
5022 Causes a sorted list of symbol names and values to be
5023 listed on the standard output file.
5027 Causes undefined symbols to be treated as having the value @code{FALSE}
5029 of a preprocessor test. In the absence of this option, an undefined symbol in
5030 a @code{#if} or @code{#elsif} test will be treated as an error.
5034 @geindex -gnateD (gcc)
5039 @item @code{-gnateD`symbol'[=`new_value']}
5041 Define or redefine @code{symbol} to have @code{new_value} as its value. If no value
5042 is supplied, then the value of @code{symbol} is @code{True}.
5043 The form of @code{symbol} is an identifier, following normal Ada (case-insensitive)
5044 rules for its syntax, and @code{new_value} is either an arbitrary string between double
5045 quotes or any sequence (including an empty sequence) of characters from the
5046 set (letters, digits, period, underline).
5047 Ada reserved words may be used as symbols, with the exceptions of @code{if},
5048 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5057 -gnateDFoo=\"Foo-Bar\"
5061 A symbol declared with this switch on the command line replaces a
5062 symbol with the same name either in a definition file or specified with a
5063 switch @code{-D} in the preprocessor data file.
5065 This switch is similar to switch @code{-D} of @code{gnatprep}.
5067 @item @code{-gnateG}
5069 When integrated preprocessing is performed on source file @code{filename.extension},
5070 create or overwrite @code{filename.extension.prep} to contain
5071 the result of the preprocessing.
5072 For example if the source file is @code{foo.adb} then
5073 the output file will be @code{foo.adb.prep}.
5076 @node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5077 @anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{9d}@anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{2c}
5078 @section Mixed Language Programming
5081 @geindex Mixed Language Programming
5083 This section describes how to develop a mixed-language program,
5084 with a focus on combining Ada with C or C++.
5087 * Interfacing to C::
5088 * Calling Conventions::
5089 * Building Mixed Ada and C++ Programs::
5090 * Partition-Wide Settings::
5091 * Generating Ada Bindings for C and C++ headers::
5092 * Generating C Headers for Ada Specifications::
5096 @node Interfacing to C,Calling Conventions,,Mixed Language Programming
5097 @anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{9e}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{9f}
5098 @subsection Interfacing to C
5101 Interfacing Ada with a foreign language such as C involves using
5102 compiler directives to import and/or export entity definitions in each
5103 language – using @code{extern} statements in C, for instance, and the
5104 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
5105 A full treatment of these topics is provided in Appendix B, section 1
5106 of the Ada Reference Manual.
5108 There are two ways to build a program using GNAT that contains some Ada
5109 sources and some foreign language sources, depending on whether or not
5110 the main subprogram is written in Ada. Here is a source example with
5111 the main subprogram in Ada:
5117 void print_num (int num)
5119 printf ("num is %d.\\n", num);
5127 /* num_from_Ada is declared in my_main.adb */
5128 extern int num_from_Ada;
5132 return num_from_Ada;
5138 procedure My_Main is
5140 -- Declare then export an Integer entity called num_from_Ada
5141 My_Num : Integer := 10;
5142 pragma Export (C, My_Num, "num_from_Ada");
5144 -- Declare an Ada function spec for Get_Num, then use
5145 -- C function get_num for the implementation.
5146 function Get_Num return Integer;
5147 pragma Import (C, Get_Num, "get_num");
5149 -- Declare an Ada procedure spec for Print_Num, then use
5150 -- C function print_num for the implementation.
5151 procedure Print_Num (Num : Integer);
5152 pragma Import (C, Print_Num, "print_num");
5155 Print_Num (Get_Num);
5159 To build this example:
5165 First compile the foreign language files to
5166 generate object files:
5174 Then, compile the Ada units to produce a set of object files and ALI
5178 $ gnatmake -c my_main.adb
5182 Run the Ada binder on the Ada main program:
5185 $ gnatbind my_main.ali
5189 Link the Ada main program, the Ada objects and the other language
5193 $ gnatlink my_main.ali file1.o file2.o
5197 The last three steps can be grouped in a single command:
5200 $ gnatmake my_main.adb -largs file1.o file2.o
5203 @geindex Binder output file
5205 If the main program is in a language other than Ada, then you may have
5206 more than one entry point into the Ada subsystem. You must use a special
5207 binder option to generate callable routines that initialize and
5208 finalize the Ada units (@ref{a0,,Binding with Non-Ada Main Programs}).
5209 Calls to the initialization and finalization routines must be inserted
5210 in the main program, or some other appropriate point in the code. The
5211 call to initialize the Ada units must occur before the first Ada
5212 subprogram is called, and the call to finalize the Ada units must occur
5213 after the last Ada subprogram returns. The binder will place the
5214 initialization and finalization subprograms into the
5215 @code{b~xxx.adb} file where they can be accessed by your C
5216 sources. To illustrate, we have the following example:
5220 extern void adainit (void);
5221 extern void adafinal (void);
5222 extern int add (int, int);
5223 extern int sub (int, int);
5225 int main (int argc, char *argv[])
5231 /* Should print "21 + 7 = 28" */
5232 printf ("%d + %d = %d\\n", a, b, add (a, b));
5234 /* Should print "21 - 7 = 14" */
5235 printf ("%d - %d = %d\\n", a, b, sub (a, b));
5244 function Add (A, B : Integer) return Integer;
5245 pragma Export (C, Add, "add");
5251 package body Unit1 is
5252 function Add (A, B : Integer) return Integer is
5262 function Sub (A, B : Integer) return Integer;
5263 pragma Export (C, Sub, "sub");
5269 package body Unit2 is
5270 function Sub (A, B : Integer) return Integer is
5277 The build procedure for this application is similar to the last
5284 First, compile the foreign language files to generate object files:
5291 Next, compile the Ada units to produce a set of object files and ALI
5295 $ gnatmake -c unit1.adb
5296 $ gnatmake -c unit2.adb
5300 Run the Ada binder on every generated ALI file. Make sure to use the
5301 @code{-n} option to specify a foreign main program:
5304 $ gnatbind -n unit1.ali unit2.ali
5308 Link the Ada main program, the Ada objects and the foreign language
5309 objects. You need only list the last ALI file here:
5312 $ gnatlink unit2.ali main.o -o exec_file
5315 This procedure yields a binary executable called @code{exec_file}.
5318 Depending on the circumstances (for example when your non-Ada main object
5319 does not provide symbol @code{main}), you may also need to instruct the
5320 GNAT linker not to include the standard startup objects by passing the
5321 @code{-nostartfiles} switch to @code{gnatlink}.
5323 @node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5324 @anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{a2}
5325 @subsection Calling Conventions
5328 @geindex Foreign Languages
5330 @geindex Calling Conventions
5332 GNAT follows standard calling sequence conventions and will thus interface
5333 to any other language that also follows these conventions. The following
5334 Convention identifiers are recognized by GNAT:
5336 @geindex Interfacing to Ada
5338 @geindex Other Ada compilers
5340 @geindex Convention Ada
5347 This indicates that the standard Ada calling sequence will be
5348 used and all Ada data items may be passed without any limitations in the
5349 case where GNAT is used to generate both the caller and callee. It is also
5350 possible to mix GNAT generated code and code generated by another Ada
5351 compiler. In this case, the data types should be restricted to simple
5352 cases, including primitive types. Whether complex data types can be passed
5353 depends on the situation. Probably it is safe to pass simple arrays, such
5354 as arrays of integers or floats. Records may or may not work, depending
5355 on whether both compilers lay them out identically. Complex structures
5356 involving variant records, access parameters, tasks, or protected types,
5357 are unlikely to be able to be passed.
5359 Note that in the case of GNAT running
5360 on a platform that supports HP Ada 83, a higher degree of compatibility
5361 can be guaranteed, and in particular records are laid out in an identical
5362 manner in the two compilers. Note also that if output from two different
5363 compilers is mixed, the program is responsible for dealing with elaboration
5364 issues. Probably the safest approach is to write the main program in the
5365 version of Ada other than GNAT, so that it takes care of its own elaboration
5366 requirements, and then call the GNAT-generated adainit procedure to ensure
5367 elaboration of the GNAT components. Consult the documentation of the other
5368 Ada compiler for further details on elaboration.
5370 However, it is not possible to mix the tasking run time of GNAT and
5371 HP Ada 83, all the tasking operations must either be entirely within
5372 GNAT compiled sections of the program, or entirely within HP Ada 83
5373 compiled sections of the program.
5376 @geindex Interfacing to Assembly
5378 @geindex Convention Assembler
5383 @item @code{Assembler}
5385 Specifies assembler as the convention. In practice this has the
5386 same effect as convention Ada (but is not equivalent in the sense of being
5387 considered the same convention).
5390 @geindex Convention Asm
5399 Equivalent to Assembler.
5401 @geindex Interfacing to COBOL
5403 @geindex Convention COBOL
5413 Data will be passed according to the conventions described
5414 in section B.4 of the Ada Reference Manual.
5419 @geindex Interfacing to C
5421 @geindex Convention C
5428 Data will be passed according to the conventions described
5429 in section B.3 of the Ada Reference Manual.
5431 A note on interfacing to a C ‘varargs’ function:
5435 @geindex C varargs function
5437 @geindex Interfacing to C varargs function
5439 @geindex varargs function interfaces
5441 In C, @code{varargs} allows a function to take a variable number of
5442 arguments. There is no direct equivalent in this to Ada. One
5443 approach that can be used is to create a C wrapper for each
5444 different profile and then interface to this C wrapper. For
5445 example, to print an @code{int} value using @code{printf},
5446 create a C function @code{printfi} that takes two arguments, a
5447 pointer to a string and an int, and calls @code{printf}.
5448 Then in the Ada program, use pragma @code{Import} to
5449 interface to @code{printfi}.
5451 It may work on some platforms to directly interface to
5452 a @code{varargs} function by providing a specific Ada profile
5453 for a particular call. However, this does not work on
5454 all platforms, since there is no guarantee that the
5455 calling sequence for a two argument normal C function
5456 is the same as for calling a @code{varargs} C function with
5457 the same two arguments.
5461 @geindex Convention Default
5468 @item @code{Default}
5473 @geindex Convention External
5480 @item @code{External}
5487 @geindex Interfacing to C++
5489 @geindex Convention C++
5494 @item @code{C_Plus_Plus} (or @code{CPP})
5496 This stands for C++. For most purposes this is identical to C.
5497 See the separate description of the specialized GNAT pragmas relating to
5498 C++ interfacing for further details.
5503 @geindex Interfacing to Fortran
5505 @geindex Convention Fortran
5510 @item @code{Fortran}
5512 Data will be passed according to the conventions described
5513 in section B.5 of the Ada Reference Manual.
5515 @item @code{Intrinsic}
5517 This applies to an intrinsic operation, as defined in the Ada
5518 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5519 this means that the body of the subprogram is provided by the compiler itself,
5520 usually by means of an efficient code sequence, and that the user does not
5521 supply an explicit body for it. In an application program, the pragma may
5522 be applied to the following sets of names:
5528 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5529 The corresponding subprogram declaration must have
5530 two formal parameters. The
5531 first one must be a signed integer type or a modular type with a binary
5532 modulus, and the second parameter must be of type Natural.
5533 The return type must be the same as the type of the first argument. The size
5534 of this type can only be 8, 16, 32, or 64.
5537 Binary arithmetic operators: ‘+’, ‘-’, ‘*’, ‘/’.
5538 The corresponding operator declaration must have parameters and result type
5539 that have the same root numeric type (for example, all three are long_float
5540 types). This simplifies the definition of operations that use type checking
5541 to perform dimensional checks:
5544 type Distance is new Long_Float;
5545 type Time is new Long_Float;
5546 type Velocity is new Long_Float;
5547 function "/" (D : Distance; T : Time)
5549 pragma Import (Intrinsic, "/");
5552 This common idiom is often programmed with a generic definition and an
5553 explicit body. The pragma makes it simpler to introduce such declarations.
5554 It incurs no overhead in compilation time or code size, because it is
5555 implemented as a single machine instruction.
5558 General subprogram entities. This is used to bind an Ada subprogram
5560 a compiler builtin by name with back-ends where such interfaces are
5561 available. A typical example is the set of @code{__builtin} functions
5562 exposed by the GCC back-end, as in the following example:
5565 function builtin_sqrt (F : Float) return Float;
5566 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5569 Most of the GCC builtins are accessible this way, and as for other
5570 import conventions (e.g. C), it is the user’s responsibility to ensure
5571 that the Ada subprogram profile matches the underlying builtin
5578 @geindex Convention Stdcall
5583 @item @code{Stdcall}
5585 This is relevant only to Windows implementations of GNAT,
5586 and specifies that the @code{Stdcall} calling sequence will be used,
5587 as defined by the NT API. Nevertheless, to ease building
5588 cross-platform bindings this convention will be handled as a @code{C} calling
5589 convention on non-Windows platforms.
5594 @geindex Convention DLL
5601 This is equivalent to @code{Stdcall}.
5606 @geindex Convention Win32
5613 This is equivalent to @code{Stdcall}.
5618 @geindex Convention Stubbed
5623 @item @code{Stubbed}
5625 This is a special convention that indicates that the compiler
5626 should provide a stub body that raises @code{Program_Error}.
5629 GNAT additionally provides a useful pragma @code{Convention_Identifier}
5630 that can be used to parameterize conventions and allow additional synonyms
5631 to be specified. For example if you have legacy code in which the convention
5632 identifier Fortran77 was used for Fortran, you can use the configuration
5636 pragma Convention_Identifier (Fortran77, Fortran);
5639 And from now on the identifier Fortran77 may be used as a convention
5640 identifier (for example in an @code{Import} pragma) with the same
5643 @node Building Mixed Ada and C++ Programs,Partition-Wide Settings,Calling Conventions,Mixed Language Programming
5644 @anchor{gnat_ugn/the_gnat_compilation_model building-mixed-ada-and-c-programs}@anchor{a3}@anchor{gnat_ugn/the_gnat_compilation_model id64}@anchor{a4}
5645 @subsection Building Mixed Ada and C++ Programs
5648 A programmer inexperienced with mixed-language development may find that
5649 building an application containing both Ada and C++ code can be a
5650 challenge. This section gives a few hints that should make this task easier.
5653 * Interfacing to C++::
5654 * Linking a Mixed C++ & Ada Program::
5655 * A Simple Example::
5656 * Interfacing with C++ constructors::
5657 * Interfacing with C++ at the Class Level::
5661 @node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5662 @anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{a6}
5663 @subsubsection Interfacing to C++
5666 GNAT supports interfacing with the G++ compiler (or any C++ compiler
5667 generating code that is compatible with the G++ Application Binary
5668 Interface —see @indicateurl{http://itanium-cxx-abi.github.io/cxx-abi/abi.html}).
5670 Interfacing can be done at 3 levels: simple data, subprograms, and
5671 classes. In the first two cases, GNAT offers a specific @code{Convention C_Plus_Plus}
5672 (or @code{CPP}) that behaves exactly like @code{Convention C}.
5673 Usually, C++ mangles the names of subprograms. To generate proper mangled
5674 names automatically, see @ref{a7,,Generating Ada Bindings for C and C++ headers}).
5675 This problem can also be addressed manually in two ways:
5681 by modifying the C++ code in order to force a C convention using
5682 the @code{extern "C"} syntax.
5685 by figuring out the mangled name (using e.g. @code{nm}) and using it as the
5686 Link_Name argument of the pragma import.
5689 Interfacing at the class level can be achieved by using the GNAT specific
5690 pragmas such as @code{CPP_Constructor}. See the @cite{GNAT_Reference_Manual} for additional information.
5692 @node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5693 @anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-ada-program}@anchor{a8}@anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-and-ada-program}@anchor{a9}
5694 @subsubsection Linking a Mixed C++ & Ada Program
5697 Usually the linker of the C++ development system must be used to link
5698 mixed applications because most C++ systems will resolve elaboration
5699 issues (such as calling constructors on global class instances)
5700 transparently during the link phase. GNAT has been adapted to ease the
5701 use of a foreign linker for the last phase. Three cases can be
5708 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5709 The C++ linker can simply be called by using the C++ specific driver
5712 Note that if the C++ code uses inline functions, you will need to
5713 compile your C++ code with the @code{-fkeep-inline-functions} switch in
5714 order to provide an existing function implementation that the Ada code can
5718 $ g++ -c -fkeep-inline-functions file1.C
5719 $ g++ -c -fkeep-inline-functions file2.C
5720 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5724 Using GNAT and G++ from two different GCC installations: If both
5725 compilers are on the
5727 @geindex environment variable; PATH
5728 @code{PATH}, the previous method may be used. It is
5729 important to note that environment variables such as
5730 @geindex C_INCLUDE_PATH
5731 @geindex environment variable; C_INCLUDE_PATH
5732 @code{C_INCLUDE_PATH},
5733 @geindex GCC_EXEC_PREFIX
5734 @geindex environment variable; GCC_EXEC_PREFIX
5735 @code{GCC_EXEC_PREFIX},
5736 @geindex BINUTILS_ROOT
5737 @geindex environment variable; BINUTILS_ROOT
5738 @code{BINUTILS_ROOT}, and
5740 @geindex environment variable; GCC_ROOT
5741 @code{GCC_ROOT} will affect both compilers
5742 at the same time and may make one of the two compilers operate
5743 improperly if set during invocation of the wrong compiler. It is also
5744 very important that the linker uses the proper @code{libgcc.a} GCC
5745 library – that is, the one from the C++ compiler installation. The
5746 implicit link command as suggested in the @code{gnatmake} command
5747 from the former example can be replaced by an explicit link command with
5748 the full-verbosity option in order to verify which library is used:
5752 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5755 If there is a problem due to interfering environment variables, it can
5756 be worked around by using an intermediate script. The following example
5757 shows the proper script to use when GNAT has not been installed at its
5758 default location and g++ has been installed at its default location:
5766 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5770 Using a non-GNU C++ compiler: The commands previously described can be
5771 used to insure that the C++ linker is used. Nonetheless, you need to add
5772 a few more parameters to the link command line, depending on the exception
5775 If the @code{setjmp} / @code{longjmp} exception mechanism is used, only the paths
5776 to the @code{libgcc} libraries are required:
5781 CC $* gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a
5782 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5785 where CC is the name of the non-GNU C++ compiler.
5787 If the “zero cost” exception mechanism is used, and the platform
5788 supports automatic registration of exception tables (e.g., Solaris),
5789 paths to more objects are required:
5794 CC gcc -print-file-name=crtbegin.o $* \\
5795 gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a \\
5796 gcc -print-file-name=crtend.o
5797 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5800 If the “zero cost exception” mechanism is used, and the platform
5801 doesn’t support automatic registration of exception tables (e.g., HP-UX
5802 or AIX), the simple approach described above will not work and
5803 a pre-linking phase using GNAT will be necessary.
5806 Another alternative is to use the @code{gprbuild} multi-language builder
5807 which has a large knowledge base and knows how to link Ada and C++ code
5808 together automatically in most cases.
5810 @node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
5811 @anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{aa}@anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{ab}
5812 @subsubsection A Simple Example
5815 The following example, provided as part of the GNAT examples, shows how
5816 to achieve procedural interfacing between Ada and C++ in both
5817 directions. The C++ class A has two methods. The first method is exported
5818 to Ada by the means of an extern C wrapper function. The second method
5819 calls an Ada subprogram. On the Ada side, the C++ calls are modelled by
5820 a limited record with a layout comparable to the C++ class. The Ada
5821 subprogram, in turn, calls the C++ method. So, starting from the C++
5822 main program, the process passes back and forth between the two
5825 Here are the compilation commands:
5828 $ gnatmake -c simple_cpp_interface
5831 $ gnatbind -n simple_cpp_interface
5832 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
5835 Here are the corresponding sources:
5843 void adainit (void);
5844 void adafinal (void);
5845 void method1 (A *t);
5869 class A : public Origin @{
5871 void method1 (void);
5872 void method2 (int v);
5884 extern "C" @{ void ada_method2 (A *t, int v);@}
5886 void A::method1 (void)
5889 printf ("in A::method1, a_value = %d \\n",a_value);
5892 void A::method2 (int v)
5894 ada_method2 (this, v);
5895 printf ("in A::method2, a_value = %d \\n",a_value);
5901 printf ("in A::A, a_value = %d \\n",a_value);
5906 -- simple_cpp_interface.ads
5908 package Simple_Cpp_Interface is
5911 Vptr : System.Address;
5915 pragma Convention (C, A);
5917 procedure Method1 (This : in out A);
5918 pragma Import (C, Method1);
5920 procedure Ada_Method2 (This : in out A; V : Integer);
5921 pragma Export (C, Ada_Method2);
5923 end Simple_Cpp_Interface;
5927 -- simple_cpp_interface.adb
5928 package body Simple_Cpp_Interface is
5930 procedure Ada_Method2 (This : in out A; V : Integer) is
5936 end Simple_Cpp_Interface;
5939 @node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
5940 @anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{ad}
5941 @subsubsection Interfacing with C++ constructors
5944 In order to interface with C++ constructors GNAT provides the
5945 @code{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
5946 for additional information).
5947 In this section we present some common uses of C++ constructors
5948 in mixed-languages programs in GNAT.
5950 Let us assume that we need to interface with the following
5958 virtual int Get_Value ();
5959 Root(); // Default constructor
5960 Root(int v); // 1st non-default constructor
5961 Root(int v, int w); // 2nd non-default constructor
5965 For this purpose we can write the following package spec (further
5966 information on how to build this spec is available in
5967 @ref{ae,,Interfacing with C++ at the Class Level} and
5968 @ref{a7,,Generating Ada Bindings for C and C++ headers}).
5971 with Interfaces.C; use Interfaces.C;
5973 type Root is tagged limited record
5977 pragma Import (CPP, Root);
5979 function Get_Value (Obj : Root) return int;
5980 pragma Import (CPP, Get_Value);
5982 function Constructor return Root;
5983 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
5985 function Constructor (v : Integer) return Root;
5986 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
5988 function Constructor (v, w : Integer) return Root;
5989 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
5993 On the Ada side the constructor is represented by a function (whose
5994 name is arbitrary) that returns the classwide type corresponding to
5995 the imported C++ class. Although the constructor is described as a
5996 function, it is typically a procedure with an extra implicit argument
5997 (the object being initialized) at the implementation level. GNAT
5998 issues the appropriate call, whatever it is, to get the object
5999 properly initialized.
6001 Constructors can only appear in the following contexts:
6007 On the right side of an initialization of an object of type @code{T}.
6010 On the right side of an initialization of a record component of type @code{T}.
6013 In an Ada 2005 limited aggregate.
6016 In an Ada 2005 nested limited aggregate.
6019 In an Ada 2005 limited aggregate that initializes an object built in
6020 place by an extended return statement.
6023 In a declaration of an object whose type is a class imported from C++,
6024 either the default C++ constructor is implicitly called by GNAT, or
6025 else the required C++ constructor must be explicitly called in the
6026 expression that initializes the object. For example:
6030 Obj2 : Root := Constructor;
6031 Obj3 : Root := Constructor (v => 10);
6032 Obj4 : Root := Constructor (30, 40);
6035 The first two declarations are equivalent: in both cases the default C++
6036 constructor is invoked (in the former case the call to the constructor is
6037 implicit, and in the latter case the call is explicit in the object
6038 declaration). @code{Obj3} is initialized by the C++ non-default constructor
6039 that takes an integer argument, and @code{Obj4} is initialized by the
6040 non-default C++ constructor that takes two integers.
6042 Let us derive the imported C++ class in the Ada side. For example:
6045 type DT is new Root with record
6046 C_Value : Natural := 2009;
6050 In this case the components DT inherited from the C++ side must be
6051 initialized by a C++ constructor, and the additional Ada components
6052 of type DT are initialized by GNAT. The initialization of such an
6053 object is done either by default, or by means of a function returning
6054 an aggregate of type DT, or by means of an extension aggregate.
6058 Obj6 : DT := Function_Returning_DT (50);
6059 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6062 The declaration of @code{Obj5} invokes the default constructors: the
6063 C++ default constructor of the parent type takes care of the initialization
6064 of the components inherited from Root, and GNAT takes care of the default
6065 initialization of the additional Ada components of type DT (that is,
6066 @code{C_Value} is initialized to value 2009). The order of invocation of
6067 the constructors is consistent with the order of elaboration required by
6068 Ada and C++. That is, the constructor of the parent type is always called
6069 before the constructor of the derived type.
6071 Let us now consider a record that has components whose type is imported
6072 from C++. For example:
6075 type Rec1 is limited record
6076 Data1 : Root := Constructor (10);
6077 Value : Natural := 1000;
6080 type Rec2 (D : Integer := 20) is limited record
6082 Data2 : Root := Constructor (D, 30);
6086 The initialization of an object of type @code{Rec2} will call the
6087 non-default C++ constructors specified for the imported components.
6094 Using Ada 2005 we can use limited aggregates to initialize an object
6095 invoking C++ constructors that differ from those specified in the type
6096 declarations. For example:
6099 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6104 The above declaration uses an Ada 2005 limited aggregate to
6105 initialize @code{Obj9}, and the C++ constructor that has two integer
6106 arguments is invoked to initialize the @code{Data1} component instead
6107 of the constructor specified in the declaration of type @code{Rec1}. In
6108 Ada 2005 the box in the aggregate indicates that unspecified components
6109 are initialized using the expression (if any) available in the component
6110 declaration. That is, in this case discriminant @code{D} is initialized
6111 to value @code{20}, @code{Value} is initialized to value 1000, and the
6112 non-default C++ constructor that handles two integers takes care of
6113 initializing component @code{Data2} with values @code{20,30}.
6115 In Ada 2005 we can use the extended return statement to build the Ada
6116 equivalent to C++ non-default constructors. For example:
6119 function Constructor (V : Integer) return Rec2 is
6121 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
6124 -- Further actions required for construction of
6125 -- objects of type Rec2
6131 In this example the extended return statement construct is used to
6132 build in place the returned object whose components are initialized
6133 by means of a limited aggregate. Any further action associated with
6134 the constructor can be placed inside the construct.
6136 @node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6137 @anchor{gnat_ugn/the_gnat_compilation_model id69}@anchor{af}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-at-the-class-level}@anchor{ae}
6138 @subsubsection Interfacing with C++ at the Class Level
6141 In this section we demonstrate the GNAT features for interfacing with
6142 C++ by means of an example making use of Ada 2005 abstract interface
6143 types. This example consists of a classification of animals; classes
6144 have been used to model our main classification of animals, and
6145 interfaces provide support for the management of secondary
6146 classifications. We first demonstrate a case in which the types and
6147 constructors are defined on the C++ side and imported from the Ada
6148 side, and latter the reverse case.
6150 The root of our derivation will be the @code{Animal} class, with a
6151 single private attribute (the @code{Age} of the animal), a constructor,
6152 and two public primitives to set and get the value of this attribute.
6157 virtual void Set_Age (int New_Age);
6159 Animal() @{Age_Count = 0;@};
6165 Abstract interface types are defined in C++ by means of classes with pure
6166 virtual functions and no data members. In our example we will use two
6167 interfaces that provide support for the common management of @code{Carnivore}
6168 and @code{Domestic} animals:
6173 virtual int Number_Of_Teeth () = 0;
6178 virtual void Set_Owner (char* Name) = 0;
6182 Using these declarations, we can now say that a @code{Dog} is an animal that is
6183 both Carnivore and Domestic, that is:
6186 class Dog : Animal, Carnivore, Domestic @{
6188 virtual int Number_Of_Teeth ();
6189 virtual void Set_Owner (char* Name);
6191 Dog(); // Constructor
6198 In the following examples we will assume that the previous declarations are
6199 located in a file named @code{animals.h}. The following package demonstrates
6200 how to import these C++ declarations from the Ada side:
6203 with Interfaces.C.Strings; use Interfaces.C.Strings;
6205 type Carnivore is limited interface;
6206 pragma Convention (C_Plus_Plus, Carnivore);
6207 function Number_Of_Teeth (X : Carnivore)
6208 return Natural is abstract;
6210 type Domestic is limited interface;
6211 pragma Convention (C_Plus_Plus, Domestic);
6213 (X : in out Domestic;
6214 Name : Chars_Ptr) is abstract;
6216 type Animal is tagged limited record
6219 pragma Import (C_Plus_Plus, Animal);
6221 procedure Set_Age (X : in out Animal; Age : Integer);
6222 pragma Import (C_Plus_Plus, Set_Age);
6224 function Age (X : Animal) return Integer;
6225 pragma Import (C_Plus_Plus, Age);
6227 function New_Animal return Animal;
6228 pragma CPP_Constructor (New_Animal);
6229 pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6231 type Dog is new Animal and Carnivore and Domestic with record
6232 Tooth_Count : Natural;
6235 pragma Import (C_Plus_Plus, Dog);
6237 function Number_Of_Teeth (A : Dog) return Natural;
6238 pragma Import (C_Plus_Plus, Number_Of_Teeth);
6240 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6241 pragma Import (C_Plus_Plus, Set_Owner);
6243 function New_Dog return Dog;
6244 pragma CPP_Constructor (New_Dog);
6245 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6249 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6250 interfacing with these C++ classes is easy. The only requirement is that all
6251 the primitives and components must be declared exactly in the same order in
6254 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6255 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
6256 the arguments to the called primitives will be the same as for C++. For the
6257 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
6258 to indicate that they have been defined on the C++ side; this is required
6259 because the dispatch table associated with these tagged types will be built
6260 in the C++ side and therefore will not contain the predefined Ada primitives
6261 which Ada would otherwise expect.
6263 As the reader can see there is no need to indicate the C++ mangled names
6264 associated with each subprogram because it is assumed that all the calls to
6265 these primitives will be dispatching calls. The only exception is the
6266 constructor, which must be registered with the compiler by means of
6267 @code{pragma CPP_Constructor} and needs to provide its associated C++
6268 mangled name because the Ada compiler generates direct calls to it.
6270 With the above packages we can now declare objects of type Dog on the Ada side
6271 and dispatch calls to the corresponding subprograms on the C++ side. We can
6272 also extend the tagged type Dog with further fields and primitives, and
6273 override some of its C++ primitives on the Ada side. For example, here we have
6274 a type derivation defined on the Ada side that inherits all the dispatching
6275 primitives of the ancestor from the C++ side.
6278 with Animals; use Animals;
6279 package Vaccinated_Animals is
6280 type Vaccinated_Dog is new Dog with null record;
6281 function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6282 end Vaccinated_Animals;
6285 It is important to note that, because of the ABI compatibility, the programmer
6286 does not need to add any further information to indicate either the object
6287 layout or the dispatch table entry associated with each dispatching operation.
6289 Now let us define all the types and constructors on the Ada side and export
6290 them to C++, using the same hierarchy of our previous example:
6293 with Interfaces.C.Strings;
6294 use Interfaces.C.Strings;
6296 type Carnivore is limited interface;
6297 pragma Convention (C_Plus_Plus, Carnivore);
6298 function Number_Of_Teeth (X : Carnivore)
6299 return Natural is abstract;
6301 type Domestic is limited interface;
6302 pragma Convention (C_Plus_Plus, Domestic);
6304 (X : in out Domestic;
6305 Name : Chars_Ptr) is abstract;
6307 type Animal is tagged record
6310 pragma Convention (C_Plus_Plus, Animal);
6312 procedure Set_Age (X : in out Animal; Age : Integer);
6313 pragma Export (C_Plus_Plus, Set_Age);
6315 function Age (X : Animal) return Integer;
6316 pragma Export (C_Plus_Plus, Age);
6318 function New_Animal return Animal'Class;
6319 pragma Export (C_Plus_Plus, New_Animal);
6321 type Dog is new Animal and Carnivore and Domestic with record
6322 Tooth_Count : Natural;
6323 Owner : String (1 .. 30);
6325 pragma Convention (C_Plus_Plus, Dog);
6327 function Number_Of_Teeth (A : Dog) return Natural;
6328 pragma Export (C_Plus_Plus, Number_Of_Teeth);
6330 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6331 pragma Export (C_Plus_Plus, Set_Owner);
6333 function New_Dog return Dog'Class;
6334 pragma Export (C_Plus_Plus, New_Dog);
6338 Compared with our previous example the only differences are the use of
6339 @code{pragma Convention} (instead of @code{pragma Import}), and the use of
6340 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
6341 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6342 nothing else to be done; as explained above, the only requirement is that all
6343 the primitives and components are declared in exactly the same order.
6345 For completeness, let us see a brief C++ main program that uses the
6346 declarations available in @code{animals.h} (presented in our first example) to
6347 import and use the declarations from the Ada side, properly initializing and
6348 finalizing the Ada run-time system along the way:
6351 #include "animals.h"
6353 using namespace std;
6355 void Check_Carnivore (Carnivore *obj) @{...@}
6356 void Check_Domestic (Domestic *obj) @{...@}
6357 void Check_Animal (Animal *obj) @{...@}
6358 void Check_Dog (Dog *obj) @{...@}
6361 void adainit (void);
6362 void adafinal (void);
6368 Dog *obj = new_dog(); // Ada constructor
6369 Check_Carnivore (obj); // Check secondary DT
6370 Check_Domestic (obj); // Check secondary DT
6371 Check_Animal (obj); // Check primary DT
6372 Check_Dog (obj); // Check primary DT
6377 adainit (); test(); adafinal ();
6382 @node Partition-Wide Settings,Generating Ada Bindings for C and C++ headers,Building Mixed Ada and C++ Programs,Mixed Language Programming
6383 @anchor{gnat_ugn/the_gnat_compilation_model id70}@anchor{b0}@anchor{gnat_ugn/the_gnat_compilation_model partition-wide-settings}@anchor{b1}
6384 @subsection Partition-Wide Settings
6387 When building a mixed-language application it is important to be aware that
6388 Ada enforces some partition-wide settings that may implicitly impact the
6389 behavior of the other languages.
6391 This is the case of certain signals that are reserved to the
6392 implementation to implement proper Ada semantics (such as the behavior
6393 of @code{abort} statements).
6395 It means that the Ada part of the application may override signal handlers
6396 that were previously installed by either the system or by other user code.
6398 If your application requires that either system or user signals be preserved
6399 then you need to instruct the Ada part not to install its own signal handler.
6400 This is done using @code{pragma Interrupt_State} that provides a general
6401 mechanism for overriding such uses of interrupts.
6403 The set of interrupts for which the Ada run-time library sets a specific signal
6404 handler is the following:
6410 Ada.Interrupts.Names.SIGSEGV
6413 Ada.Interrupts.Names.SIGBUS
6416 Ada.Interrupts.Names.SIGFPE
6419 Ada.Interrupts.Names.SIGILL
6422 Ada.Interrupts.Names.SIGABRT
6425 The run-time library can be instructed not to install its signal handler for a
6426 particular signal by using the configuration pragma @code{Interrupt_State} in the
6427 Ada code. For example:
6430 pragma Interrupt_State (Ada.Interrupts.Names.SIGSEGV, System);
6431 pragma Interrupt_State (Ada.Interrupts.Names.SIGBUS, System);
6432 pragma Interrupt_State (Ada.Interrupts.Names.SIGFPE, System);
6433 pragma Interrupt_State (Ada.Interrupts.Names.SIGILL, System);
6434 pragma Interrupt_State (Ada.Interrupts.Names.SIGABRT, System);
6437 Obviously, if the Ada run-time system cannot set these handlers it comes with the
6438 drawback of not fully preserving Ada semantics. @code{SIGSEGV}, @code{SIGBUS}, @code{SIGFPE}
6439 and @code{SIGILL} are used to raise corresponding Ada exceptions in the application,
6440 while @code{SIGABRT} is used to asynchronously abort an action or a task.
6442 @node Generating Ada Bindings for C and C++ headers,Generating C Headers for Ada Specifications,Partition-Wide Settings,Mixed Language Programming
6443 @anchor{gnat_ugn/the_gnat_compilation_model generating-ada-bindings-for-c-and-c-headers}@anchor{a7}@anchor{gnat_ugn/the_gnat_compilation_model id71}@anchor{b2}
6444 @subsection Generating Ada Bindings for C and C++ headers
6447 @geindex Binding generation (for C and C++ headers)
6449 @geindex C headers (binding generation)
6451 @geindex C++ headers (binding generation)
6453 GNAT includes a binding generator for C and C++ headers which is
6454 intended to do 95% of the tedious work of generating Ada specs from C
6455 or C++ header files.
6457 Note that this capability is not intended to generate 100% correct Ada specs,
6458 and will is some cases require manual adjustments, although it can often
6459 be used out of the box in practice.
6461 Some of the known limitations include:
6467 only very simple character constant macros are translated into Ada
6468 constants. Function macros (macros with arguments) are partially translated
6469 as comments, to be completed manually if needed.
6472 some extensions (e.g. vector types) are not supported
6475 pointers to pointers are mapped to System.Address
6478 identifiers with identical name (except casing) may generate compilation
6479 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
6482 The code is generated using Ada 2012 syntax, which makes it easier to interface
6483 with other languages. In most cases you can still use the generated binding
6484 even if your code is compiled using earlier versions of Ada (e.g. @code{-gnat95}).
6487 * Running the Binding Generator::
6488 * Generating Bindings for C++ Headers::
6493 @node Running the Binding Generator,Generating Bindings for C++ Headers,,Generating Ada Bindings for C and C++ headers
6494 @anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{b3}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{b4}
6495 @subsubsection Running the Binding Generator
6498 The binding generator is part of the @code{gcc} compiler and can be
6499 invoked via the @code{-fdump-ada-spec} switch, which will generate Ada
6500 spec files for the header files specified on the command line, and all
6501 header files needed by these files transitively. For example:
6504 $ gcc -c -fdump-ada-spec -C /usr/include/time.h
6508 will generate, under GNU/Linux, the following files: @code{time_h.ads},
6509 @code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6510 correspond to the files @code{/usr/include/time.h},
6511 @code{/usr/include/bits/time.h}, etc…, and then compile these Ada specs.
6512 That is to say, the name of the Ada specs is in keeping with the relative path
6513 under @code{/usr/include/} of the header files. This behavior is specific to
6514 paths ending with @code{/include/}; in all the other cases, the name of the
6515 Ada specs is derived from the simple name of the header files instead.
6517 The @code{-C} switch tells @code{gcc} to extract comments from headers,
6518 and will attempt to generate corresponding Ada comments.
6520 If you want to generate a single Ada file and not the transitive closure, you
6521 can use instead the @code{-fdump-ada-spec-slim} switch.
6523 You can optionally specify a parent unit, of which all generated units will
6524 be children, using @code{-fada-spec-parent=`unit'}.
6526 The simple @code{gcc}-based command works only for C headers. For C++ headers
6527 you need to use either the @code{g++} command or the combination @code{gcc -x c++}.
6529 In some cases, the generated bindings will be more complete or more meaningful
6530 when defining some macros, which you can do via the @code{-D} switch. This
6531 is for example the case with @code{Xlib.h} under GNU/Linux:
6534 $ gcc -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6537 The above will generate more complete bindings than a straight call without
6538 the @code{-DXLIB_ILLEGAL_ACCESS} switch.
6540 In other cases, it is not possible to parse a header file in a stand-alone
6541 manner, because other include files need to be included first. In this
6542 case, the solution is to create a small header file including the needed
6543 @code{#include} and possible @code{#define} directives. For example, to
6544 generate Ada bindings for @code{readline/readline.h}, you need to first
6545 include @code{stdio.h}, so you can create a file with the following two
6546 lines in e.g. @code{readline1.h}:
6550 #include <readline/readline.h>
6553 and then generate Ada bindings from this file:
6556 $ gcc -c -fdump-ada-spec readline1.h
6559 @node Generating Bindings for C++ Headers,Switches,Running the Binding Generator,Generating Ada Bindings for C and C++ headers
6560 @anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{b5}@anchor{gnat_ugn/the_gnat_compilation_model id73}@anchor{b6}
6561 @subsubsection Generating Bindings for C++ Headers
6564 Generating bindings for C++ headers is done using the same options, always
6565 with the `g++' compiler. Note that generating Ada spec from C++ headers is a
6566 much more complex job and support for C++ headers is much more limited that
6567 support for C headers. As a result, you will need to modify the resulting
6568 bindings by hand more extensively when using C++ headers.
6570 In this mode, C++ classes will be mapped to Ada tagged types, constructors
6571 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
6572 multiple inheritance of abstract classes will be mapped to Ada interfaces
6573 (see the `Interfacing to C++' section in the @cite{GNAT Reference Manual}
6574 for additional information on interfacing to C++).
6576 For example, given the following C++ header file:
6581 virtual int Number_Of_Teeth () = 0;
6586 virtual void Set_Owner (char* Name) = 0;
6592 virtual void Set_Age (int New_Age);
6595 class Dog : Animal, Carnivore, Domestic @{
6600 virtual int Number_Of_Teeth ();
6601 virtual void Set_Owner (char* Name);
6607 The corresponding Ada code is generated:
6610 package Class_Carnivore is
6611 type Carnivore is limited interface;
6612 pragma Import (CPP, Carnivore);
6614 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6616 use Class_Carnivore;
6618 package Class_Domestic is
6619 type Domestic is limited interface;
6620 pragma Import (CPP, Domestic);
6623 (this : access Domestic;
6624 Name : Interfaces.C.Strings.chars_ptr) is abstract;
6628 package Class_Animal is
6629 type Animal is tagged limited record
6630 Age_Count : aliased int;
6632 pragma Import (CPP, Animal);
6634 procedure Set_Age (this : access Animal; New_Age : int);
6635 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6639 package Class_Dog is
6640 type Dog is new Animal and Carnivore and Domestic with record
6641 Tooth_Count : aliased int;
6642 Owner : Interfaces.C.Strings.chars_ptr;
6644 pragma Import (CPP, Dog);
6646 function Number_Of_Teeth (this : access Dog) return int;
6647 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6650 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6651 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6653 function New_Dog return Dog;
6654 pragma CPP_Constructor (New_Dog);
6655 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6660 @node Switches,,Generating Bindings for C++ Headers,Generating Ada Bindings for C and C++ headers
6661 @anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{b7}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{b8}
6662 @subsubsection Switches
6665 @geindex -fdump-ada-spec (gcc)
6670 @item @code{-fdump-ada-spec}
6672 Generate Ada spec files for the given header files transitively (including
6673 all header files that these headers depend upon).
6676 @geindex -fdump-ada-spec-slim (gcc)
6681 @item @code{-fdump-ada-spec-slim}
6683 Generate Ada spec files for the header files specified on the command line
6687 @geindex -fada-spec-parent (gcc)
6692 @item @code{-fada-spec-parent=`unit'}
6694 Specifies that all files generated by @code{-fdump-ada-spec} are
6695 to be child units of the specified parent unit.
6705 Extract comments from headers and generate Ada comments in the Ada spec files.
6708 @node Generating C Headers for Ada Specifications,,Generating Ada Bindings for C and C++ headers,Mixed Language Programming
6709 @anchor{gnat_ugn/the_gnat_compilation_model generating-c-headers-for-ada-specifications}@anchor{b9}@anchor{gnat_ugn/the_gnat_compilation_model id74}@anchor{ba}
6710 @subsection Generating C Headers for Ada Specifications
6713 @geindex Binding generation (for Ada specs)
6715 @geindex C headers (binding generation)
6717 GNAT includes a C header generator for Ada specifications which supports
6718 Ada types that have a direct mapping to C types. This includes in particular
6734 Composition of the above types
6737 Constant declarations
6743 Subprogram declarations
6747 * Running the C Header Generator::
6751 @node Running the C Header Generator,,,Generating C Headers for Ada Specifications
6752 @anchor{gnat_ugn/the_gnat_compilation_model running-the-c-header-generator}@anchor{bb}
6753 @subsubsection Running the C Header Generator
6756 The C header generator is part of the GNAT compiler and can be invoked via
6757 the @code{-gnatceg} combination of switches, which will generate a @code{.h}
6758 file corresponding to the given input file (Ada spec or body). Note that
6759 only spec files are processed in any case, so giving a spec or a body file
6760 as input is equivalent. For example:
6763 $ gcc -c -gnatceg pack1.ads
6766 will generate a self-contained file called @code{pack1.h} including
6767 common definitions from the Ada Standard package, followed by the
6768 definitions included in @code{pack1.ads}, as well as all the other units
6769 withed by this file.
6771 For instance, given the following Ada files:
6775 type Int is range 1 .. 10;
6784 Field1, Field2 : Pack2.Int;
6787 Global : Rec := (1, 2);
6789 procedure Proc1 (R : Rec);
6790 procedure Proc2 (R : in out Rec);
6794 The above @code{gcc} command will generate the following @code{pack1.h} file:
6797 /* Standard definitions skipped */
6800 typedef short_short_integer pack2__TintB;
6801 typedef pack2__TintB pack2__int;
6802 #endif /* PACK2_ADS */
6806 typedef struct _pack1__rec @{
6810 extern pack1__rec pack1__global;
6811 extern void pack1__proc1(const pack1__rec r);
6812 extern void pack1__proc2(pack1__rec *r);
6813 #endif /* PACK1_ADS */
6816 You can then @code{include} @code{pack1.h} from a C source file and use the types,
6817 call subprograms, reference objects, and constants.
6819 @node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
6820 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{2d}@anchor{gnat_ugn/the_gnat_compilation_model id75}@anchor{bc}
6821 @section GNAT and Other Compilation Models
6824 This section compares the GNAT model with the approaches taken in
6825 other environments, first the C/C++ model and then the mechanism that
6826 has been used in other Ada systems, in particular those traditionally
6830 * Comparison between GNAT and C/C++ Compilation Models::
6831 * Comparison between GNAT and Conventional Ada Library Models::
6835 @node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
6836 @anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-c-c-compilation-models}@anchor{bd}@anchor{gnat_ugn/the_gnat_compilation_model id76}@anchor{be}
6837 @subsection Comparison between GNAT and C/C++ Compilation Models
6840 The GNAT model of compilation is close to the C and C++ models. You can
6841 think of Ada specs as corresponding to header files in C. As in C, you
6842 don’t need to compile specs; they are compiled when they are used. The
6843 Ada `with' is similar in effect to the @code{#include} of a C
6846 One notable difference is that, in Ada, you may compile specs separately
6847 to check them for semantic and syntactic accuracy. This is not always
6848 possible with C headers because they are fragments of programs that have
6849 less specific syntactic or semantic rules.
6851 The other major difference is the requirement for running the binder,
6852 which performs two important functions. First, it checks for
6853 consistency. In C or C++, the only defense against assembling
6854 inconsistent programs lies outside the compiler, in a makefile, for
6855 example. The binder satisfies the Ada requirement that it be impossible
6856 to construct an inconsistent program when the compiler is used in normal
6859 @geindex Elaboration order control
6861 The other important function of the binder is to deal with elaboration
6862 issues. There are also elaboration issues in C++ that are handled
6863 automatically. This automatic handling has the advantage of being
6864 simpler to use, but the C++ programmer has no control over elaboration.
6865 Where @code{gnatbind} might complain there was no valid order of
6866 elaboration, a C++ compiler would simply construct a program that
6867 malfunctioned at run time.
6869 @node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
6870 @anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-conventional-ada-library-models}@anchor{bf}@anchor{gnat_ugn/the_gnat_compilation_model id77}@anchor{c0}
6871 @subsection Comparison between GNAT and Conventional Ada Library Models
6874 This section is intended for Ada programmers who have
6875 used an Ada compiler implementing the traditional Ada library
6876 model, as described in the Ada Reference Manual.
6878 @geindex GNAT library
6880 In GNAT, there is no ‘library’ in the normal sense. Instead, the set of
6881 source files themselves acts as the library. Compiling Ada programs does
6882 not generate any centralized information, but rather an object file and
6883 a ALI file, which are of interest only to the binder and linker.
6884 In a traditional system, the compiler reads information not only from
6885 the source file being compiled, but also from the centralized library.
6886 This means that the effect of a compilation depends on what has been
6887 previously compiled. In particular:
6893 When a unit is `with'ed, the unit seen by the compiler corresponds
6894 to the version of the unit most recently compiled into the library.
6897 Inlining is effective only if the necessary body has already been
6898 compiled into the library.
6901 Compiling a unit may obsolete other units in the library.
6904 In GNAT, compiling one unit never affects the compilation of any other
6905 units because the compiler reads only source files. Only changes to source
6906 files can affect the results of a compilation. In particular:
6912 When a unit is `with'ed, the unit seen by the compiler corresponds
6913 to the source version of the unit that is currently accessible to the
6919 Inlining requires the appropriate source files for the package or
6920 subprogram bodies to be available to the compiler. Inlining is always
6921 effective, independent of the order in which units are compiled.
6924 Compiling a unit never affects any other compilations. The editing of
6925 sources may cause previous compilations to be out of date if they
6926 depended on the source file being modified.
6929 The most important result of these differences is that order of compilation
6930 is never significant in GNAT. There is no situation in which one is
6931 required to do one compilation before another. What shows up as order of
6932 compilation requirements in the traditional Ada library becomes, in
6933 GNAT, simple source dependencies; in other words, there is only a set
6934 of rules saying what source files must be present when a file is
6937 @node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
6938 @anchor{gnat_ugn/the_gnat_compilation_model id78}@anchor{c1}@anchor{gnat_ugn/the_gnat_compilation_model using-gnat-files-with-external-tools}@anchor{2e}
6939 @section Using GNAT Files with External Tools
6942 This section explains how files that are produced by GNAT may be
6943 used with tools designed for other languages.
6946 * Using Other Utility Programs with GNAT::
6947 * The External Symbol Naming Scheme of GNAT::
6951 @node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
6952 @anchor{gnat_ugn/the_gnat_compilation_model id79}@anchor{c2}@anchor{gnat_ugn/the_gnat_compilation_model using-other-utility-programs-with-gnat}@anchor{c3}
6953 @subsection Using Other Utility Programs with GNAT
6956 The object files generated by GNAT are in standard system format and in
6957 particular the debugging information uses this format. This means
6958 programs generated by GNAT can be used with existing utilities that
6959 depend on these formats.
6961 In general, any utility program that works with C will also often work with
6962 Ada programs generated by GNAT. This includes software utilities such as
6963 gprof (a profiling program), gdb (the FSF debugger), and utilities such
6966 @node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
6967 @anchor{gnat_ugn/the_gnat_compilation_model id80}@anchor{c4}@anchor{gnat_ugn/the_gnat_compilation_model the-external-symbol-naming-scheme-of-gnat}@anchor{c5}
6968 @subsection The External Symbol Naming Scheme of GNAT
6971 In order to interpret the output from GNAT, when using tools that are
6972 originally intended for use with other languages, it is useful to
6973 understand the conventions used to generate link names from the Ada
6976 All link names are in all lowercase letters. With the exception of library
6977 procedure names, the mechanism used is simply to use the full expanded
6978 Ada name with dots replaced by double underscores. For example, suppose
6979 we have the following package spec:
6987 @geindex pragma Export
6989 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
6990 the corresponding link name is @code{qrs__mn}.
6991 Of course if a @code{pragma Export} is used this may be overridden:
6996 pragma Export (Var1, C, External_Name => "var1_name");
6998 pragma Export (Var2, C, Link_Name => "var2_link_name");
7002 In this case, the link name for @code{Var1} is whatever link name the
7003 C compiler would assign for the C function @code{var1_name}. This typically
7004 would be either @code{var1_name} or @code{_var1_name}, depending on operating
7005 system conventions, but other possibilities exist. The link name for
7006 @code{Var2} is @code{var2_link_name}, and this is not operating system
7009 One exception occurs for library level procedures. A potential ambiguity
7010 arises between the required name @code{_main} for the C main program,
7011 and the name we would otherwise assign to an Ada library level procedure
7012 called @code{Main} (which might well not be the main program).
7014 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
7015 names. So if we have a library level procedure such as:
7018 procedure Hello (S : String);
7021 the external name of this procedure will be @code{_ada_hello}.
7023 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7025 @node Building Executable Programs with GNAT,GNAT Utility Programs,The GNAT Compilation Model,Top
7026 @anchor{gnat_ugn/building_executable_programs_with_gnat doc}@anchor{c6}@anchor{gnat_ugn/building_executable_programs_with_gnat building-executable-programs-with-gnat}@anchor{a}@anchor{gnat_ugn/building_executable_programs_with_gnat id1}@anchor{c7}
7027 @chapter Building Executable Programs with GNAT
7030 This chapter describes first the gnatmake tool
7031 (@ref{c8,,Building with gnatmake}),
7032 which automatically determines the set of sources
7033 needed by an Ada compilation unit and executes the necessary
7034 (re)compilations, binding and linking.
7035 It also explains how to use each tool individually: the
7036 compiler (gcc, see @ref{c9,,Compiling with gcc}),
7037 binder (gnatbind, see @ref{ca,,Binding with gnatbind}),
7038 and linker (gnatlink, see @ref{cb,,Linking with gnatlink})
7039 to build executable programs.
7040 Finally, this chapter provides examples of
7041 how to make use of the general GNU make mechanism
7042 in a GNAT context (see @ref{70,,Using the GNU make Utility}).
7046 * Building with gnatmake::
7047 * Compiling with gcc::
7048 * Compiler Switches::
7050 * Binding with gnatbind::
7051 * Linking with gnatlink::
7052 * Using the GNU make Utility::
7056 @node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
7057 @anchor{gnat_ugn/building_executable_programs_with_gnat building-with-gnatmake}@anchor{cc}@anchor{gnat_ugn/building_executable_programs_with_gnat the-gnat-make-program-gnatmake}@anchor{c8}
7058 @section Building with @code{gnatmake}
7063 A typical development cycle when working on an Ada program consists of
7064 the following steps:
7070 Edit some sources to fix bugs;
7076 Compile all sources affected;
7079 Rebind and relink; and
7085 @geindex Dependency rules (compilation)
7087 The third step in particular can be tricky, because not only do the modified
7088 files have to be compiled, but any files depending on these files must also be
7089 recompiled. The dependency rules in Ada can be quite complex, especially
7090 in the presence of overloading, @code{use} clauses, generics and inlined
7093 @code{gnatmake} automatically takes care of the third and fourth steps
7094 of this process. It determines which sources need to be compiled,
7095 compiles them, and binds and links the resulting object files.
7097 Unlike some other Ada make programs, the dependencies are always
7098 accurately recomputed from the new sources. The source based approach of
7099 the GNAT compilation model makes this possible. This means that if
7100 changes to the source program cause corresponding changes in
7101 dependencies, they will always be tracked exactly correctly by
7104 Note that for advanced forms of project structure, we recommend creating
7105 a project file as explained in the `GNAT_Project_Manager' chapter in the
7106 `GPRbuild User’s Guide', and using the
7107 @code{gprbuild} tool which supports building with project files and works similarly
7111 * Running gnatmake::
7112 * Switches for gnatmake::
7113 * Mode Switches for gnatmake::
7114 * Notes on the Command Line::
7115 * How gnatmake Works::
7116 * Examples of gnatmake Usage::
7120 @node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7121 @anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{cd}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{ce}
7122 @subsection Running @code{gnatmake}
7125 The usual form of the @code{gnatmake} command is
7128 $ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7131 The only required argument is one @code{file_name}, which specifies
7132 a compilation unit that is a main program. Several @code{file_names} can be
7133 specified: this will result in several executables being built.
7134 If @code{switches} are present, they can be placed before the first
7135 @code{file_name}, between @code{file_names} or after the last @code{file_name}.
7136 If @code{mode_switches} are present, they must always be placed after
7137 the last @code{file_name} and all @code{switches}.
7139 If you are using standard file extensions (@code{.adb} and
7140 @code{.ads}), then the
7141 extension may be omitted from the @code{file_name} arguments. However, if
7142 you are using non-standard extensions, then it is required that the
7143 extension be given. A relative or absolute directory path can be
7144 specified in a @code{file_name}, in which case, the input source file will
7145 be searched for in the specified directory only. Otherwise, the input
7146 source file will first be searched in the directory where
7147 @code{gnatmake} was invoked and if it is not found, it will be search on
7148 the source path of the compiler as described in
7149 @ref{73,,Search Paths and the Run-Time Library (RTL)}.
7151 All @code{gnatmake} output (except when you specify @code{-M}) is sent to
7152 @code{stderr}. The output produced by the
7153 @code{-M} switch is sent to @code{stdout}.
7155 @node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7156 @anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{cf}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{d0}
7157 @subsection Switches for @code{gnatmake}
7160 You may specify any of the following switches to @code{gnatmake}:
7162 @geindex --version (gnatmake)
7167 @item @code{--version}
7169 Display Copyright and version, then exit disregarding all other options.
7172 @geindex --help (gnatmake)
7179 If @code{--version} was not used, display usage, then exit disregarding
7183 @geindex -P (gnatmake)
7188 @item @code{-P`project'}
7190 Build GNAT project file @code{project} using GPRbuild. When this switch is
7191 present, all other command-line switches are treated as GPRbuild switches
7192 and not @code{gnatmake} switches.
7196 @c :ref:`gnatmake_and_Project_Files`.
7198 @geindex --GCC=compiler_name (gnatmake)
7203 @item @code{--GCC=`compiler_name'}
7205 Program used for compiling. The default is @code{gcc}. You need to use
7206 quotes around @code{compiler_name} if @code{compiler_name} contains
7207 spaces or other separator characters.
7208 As an example @code{--GCC="foo -x -y"}
7209 will instruct @code{gnatmake} to use @code{foo -x -y} as your
7210 compiler. A limitation of this syntax is that the name and path name of
7211 the executable itself must not include any embedded spaces. Note that
7212 switch @code{-c} is always inserted after your command name. Thus in the
7213 above example the compiler command that will be used by @code{gnatmake}
7214 will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7215 used, only the last @code{compiler_name} is taken into account. However,
7216 all the additional switches are also taken into account. Thus,
7217 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7218 @code{--GCC="bar -x -y -z -t"}.
7221 @geindex --GNATBIND=binder_name (gnatmake)
7226 @item @code{--GNATBIND=`binder_name'}
7228 Program used for binding. The default is @code{gnatbind}. You need to
7229 use quotes around @code{binder_name} if @code{binder_name} contains spaces
7230 or other separator characters.
7231 As an example @code{--GNATBIND="bar -x -y"}
7232 will instruct @code{gnatmake} to use @code{bar -x -y} as your
7233 binder. Binder switches that are normally appended by @code{gnatmake}
7234 to @code{gnatbind} are now appended to the end of @code{bar -x -y}.
7235 A limitation of this syntax is that the name and path name of the executable
7236 itself must not include any embedded spaces.
7239 @geindex --GNATLINK=linker_name (gnatmake)
7244 @item @code{--GNATLINK=`linker_name'}
7246 Program used for linking. The default is @code{gnatlink}. You need to
7247 use quotes around @code{linker_name} if @code{linker_name} contains spaces
7248 or other separator characters.
7249 As an example @code{--GNATLINK="lan -x -y"}
7250 will instruct @code{gnatmake} to use @code{lan -x -y} as your
7251 linker. Linker switches that are normally appended by @code{gnatmake} to
7252 @code{gnatlink} are now appended to the end of @code{lan -x -y}.
7253 A limitation of this syntax is that the name and path name of the executable
7254 itself must not include any embedded spaces.
7256 @item @code{--create-map-file}
7258 When linking an executable, create a map file. The name of the map file
7259 has the same name as the executable with extension “.map”.
7261 @item @code{--create-map-file=`mapfile'}
7263 When linking an executable, create a map file with the specified name.
7266 @geindex --create-missing-dirs (gnatmake)
7271 @item @code{--create-missing-dirs}
7273 When using project files (@code{-P`project'}), automatically create
7274 missing object directories, library directories and exec
7277 @item @code{--single-compile-per-obj-dir}
7279 Disallow simultaneous compilations in the same object directory when
7280 project files are used.
7282 @item @code{--subdirs=`subdir'}
7284 Actual object directory of each project file is the subdirectory subdir of the
7285 object directory specified or defaulted in the project file.
7287 @item @code{--unchecked-shared-lib-imports}
7289 By default, shared library projects are not allowed to import static library
7290 projects. When this switch is used on the command line, this restriction is
7293 @item @code{--source-info=`source info file'}
7295 Specify a source info file. This switch is active only when project files
7296 are used. If the source info file is specified as a relative path, then it is
7297 relative to the object directory of the main project. If the source info file
7298 does not exist, then after the Project Manager has successfully parsed and
7299 processed the project files and found the sources, it creates the source info
7300 file. If the source info file already exists and can be read successfully,
7301 then the Project Manager will get all the needed information about the sources
7302 from the source info file and will not look for them. This reduces the time
7303 to process the project files, especially when looking for sources that take a
7304 long time. If the source info file exists but cannot be parsed successfully,
7305 the Project Manager will attempt to recreate it. If the Project Manager fails
7306 to create the source info file, a message is issued, but gnatmake does not
7307 fail. @code{gnatmake} “trusts” the source info file. This means that
7308 if the source files have changed (addition, deletion, moving to a different
7309 source directory), then the source info file need to be deleted and recreated.
7312 @geindex -a (gnatmake)
7319 Consider all files in the make process, even the GNAT internal system
7320 files (for example, the predefined Ada library files), as well as any
7321 locked files. Locked files are files whose ALI file is write-protected.
7323 @code{gnatmake} does not check these files,
7324 because the assumption is that the GNAT internal files are properly up
7325 to date, and also that any write protected ALI files have been properly
7326 installed. Note that if there is an installation problem, such that one
7327 of these files is not up to date, it will be properly caught by the
7329 You may have to specify this switch if you are working on GNAT
7330 itself. The switch @code{-a} is also useful
7331 in conjunction with @code{-f}
7332 if you need to recompile an entire application,
7333 including run-time files, using special configuration pragmas,
7334 such as a @code{Normalize_Scalars} pragma.
7337 @code{gnatmake -a} compiles all GNAT
7339 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7342 @geindex -b (gnatmake)
7349 Bind only. Can be combined with @code{-c} to do
7350 compilation and binding, but no link.
7351 Can be combined with @code{-l}
7352 to do binding and linking. When not combined with
7354 all the units in the closure of the main program must have been previously
7355 compiled and must be up to date. The root unit specified by @code{file_name}
7356 may be given without extension, with the source extension or, if no GNAT
7357 Project File is specified, with the ALI file extension.
7360 @geindex -c (gnatmake)
7367 Compile only. Do not perform binding, except when @code{-b}
7368 is also specified. Do not perform linking, except if both
7370 @code{-l} are also specified.
7371 If the root unit specified by @code{file_name} is not a main unit, this is the
7372 default. Otherwise @code{gnatmake} will attempt binding and linking
7373 unless all objects are up to date and the executable is more recent than
7377 @geindex -C (gnatmake)
7384 Use a temporary mapping file. A mapping file is a way to communicate
7385 to the compiler two mappings: from unit names to file names (without
7386 any directory information) and from file names to path names (with
7387 full directory information). A mapping file can make the compiler’s
7388 file searches faster, especially if there are many source directories,
7389 or the sources are read over a slow network connection. If
7390 @code{-P} is used, a mapping file is always used, so
7391 @code{-C} is unnecessary; in this case the mapping file
7392 is initially populated based on the project file. If
7393 @code{-C} is used without
7395 the mapping file is initially empty. Each invocation of the compiler
7396 will add any newly accessed sources to the mapping file.
7399 @geindex -C= (gnatmake)
7404 @item @code{-C=`file'}
7406 Use a specific mapping file. The file, specified as a path name (absolute or
7407 relative) by this switch, should already exist, otherwise the switch is
7408 ineffective. The specified mapping file will be communicated to the compiler.
7409 This switch is not compatible with a project file
7410 (-P`file`) or with multiple compiling processes
7411 (-jnnn, when nnn is greater than 1).
7414 @geindex -d (gnatmake)
7421 Display progress for each source, up to date or not, as a single line:
7424 completed x out of y (zz%)
7427 If the file needs to be compiled this is displayed after the invocation of
7428 the compiler. These lines are displayed even in quiet output mode.
7431 @geindex -D (gnatmake)
7436 @item @code{-D `dir'}
7438 Put all object files and ALI file in directory @code{dir}.
7439 If the @code{-D} switch is not used, all object files
7440 and ALI files go in the current working directory.
7442 This switch cannot be used when using a project file.
7445 @geindex -eI (gnatmake)
7450 @item @code{-eI`nnn'}
7452 Indicates that the main source is a multi-unit source and the rank of the unit
7453 in the source file is nnn. nnn needs to be a positive number and a valid
7454 index in the source. This switch cannot be used when @code{gnatmake} is
7455 invoked for several mains.
7458 @geindex -eL (gnatmake)
7460 @geindex symbolic links
7467 Follow all symbolic links when processing project files.
7468 This should be used if your project uses symbolic links for files or
7469 directories, but is not needed in other cases.
7471 @geindex naming scheme
7473 This also assumes that no directory matches the naming scheme for files (for
7474 instance that you do not have a directory called “sources.ads” when using the
7475 default GNAT naming scheme).
7477 When you do not have to use this switch (i.e., by default), gnatmake is able to
7478 save a lot of system calls (several per source file and object file), which
7479 can result in a significant speed up to load and manipulate a project file,
7480 especially when using source files from a remote system.
7483 @geindex -eS (gnatmake)
7490 Output the commands for the compiler, the binder and the linker
7492 instead of standard error.
7495 @geindex -f (gnatmake)
7502 Force recompilations. Recompile all sources, even though some object
7503 files may be up to date, but don’t recompile predefined or GNAT internal
7504 files or locked files (files with a write-protected ALI file),
7505 unless the @code{-a} switch is also specified.
7508 @geindex -F (gnatmake)
7515 When using project files, if some errors or warnings are detected during
7516 parsing and verbose mode is not in effect (no use of switch
7517 -v), then error lines start with the full path name of the project
7518 file, rather than its simple file name.
7521 @geindex -g (gnatmake)
7528 Enable debugging. This switch is simply passed to the compiler and to the
7532 @geindex -i (gnatmake)
7539 In normal mode, @code{gnatmake} compiles all object files and ALI files
7540 into the current directory. If the @code{-i} switch is used,
7541 then instead object files and ALI files that already exist are overwritten
7542 in place. This means that once a large project is organized into separate
7543 directories in the desired manner, then @code{gnatmake} will automatically
7544 maintain and update this organization. If no ALI files are found on the
7545 Ada object path (see @ref{73,,Search Paths and the Run-Time Library (RTL)}),
7546 the new object and ALI files are created in the
7547 directory containing the source being compiled. If another organization
7548 is desired, where objects and sources are kept in different directories,
7549 a useful technique is to create dummy ALI files in the desired directories.
7550 When detecting such a dummy file, @code{gnatmake} will be forced to
7551 recompile the corresponding source file, and it will be put the resulting
7552 object and ALI files in the directory where it found the dummy file.
7555 @geindex -j (gnatmake)
7557 @geindex Parallel make
7564 Use @code{n} processes to carry out the (re)compilations. On a multiprocessor
7565 machine compilations will occur in parallel. If @code{n} is 0, then the
7566 maximum number of parallel compilations is the number of core processors
7567 on the platform. In the event of compilation errors, messages from various
7568 compilations might get interspersed (but @code{gnatmake} will give you the
7569 full ordered list of failing compiles at the end). If this is problematic,
7570 rerun the make process with n set to 1 to get a clean list of messages.
7573 @geindex -k (gnatmake)
7580 Keep going. Continue as much as possible after a compilation error. To
7581 ease the programmer’s task in case of compilation errors, the list of
7582 sources for which the compile fails is given when @code{gnatmake}
7585 If @code{gnatmake} is invoked with several @code{file_names} and with this
7586 switch, if there are compilation errors when building an executable,
7587 @code{gnatmake} will not attempt to build the following executables.
7590 @geindex -l (gnatmake)
7597 Link only. Can be combined with @code{-b} to binding
7598 and linking. Linking will not be performed if combined with
7600 but not with @code{-b}.
7601 When not combined with @code{-b}
7602 all the units in the closure of the main program must have been previously
7603 compiled and must be up to date, and the main program needs to have been bound.
7604 The root unit specified by @code{file_name}
7605 may be given without extension, with the source extension or, if no GNAT
7606 Project File is specified, with the ALI file extension.
7609 @geindex -m (gnatmake)
7616 Specify that the minimum necessary amount of recompilations
7617 be performed. In this mode @code{gnatmake} ignores time
7618 stamp differences when the only
7619 modifications to a source file consist in adding/removing comments,
7620 empty lines, spaces or tabs. This means that if you have changed the
7621 comments in a source file or have simply reformatted it, using this
7622 switch will tell @code{gnatmake} not to recompile files that depend on it
7623 (provided other sources on which these files depend have undergone no
7624 semantic modifications). Note that the debugging information may be
7625 out of date with respect to the sources if the @code{-m} switch causes
7626 a compilation to be switched, so the use of this switch represents a
7627 trade-off between compilation time and accurate debugging information.
7630 @geindex Dependencies
7631 @geindex producing list
7633 @geindex -M (gnatmake)
7640 Check if all objects are up to date. If they are, output the object
7641 dependences to @code{stdout} in a form that can be directly exploited in
7642 a @code{Makefile}. By default, each source file is prefixed with its
7643 (relative or absolute) directory name. This name is whatever you
7644 specified in the various @code{-aI}
7645 and @code{-I} switches. If you use
7646 @code{gnatmake -M} @code{-q}
7647 (see below), only the source file names,
7648 without relative paths, are output. If you just specify the @code{-M}
7649 switch, dependencies of the GNAT internal system files are omitted. This
7650 is typically what you want. If you also specify
7651 the @code{-a} switch,
7652 dependencies of the GNAT internal files are also listed. Note that
7653 dependencies of the objects in external Ada libraries (see
7654 switch @code{-aL`dir'} in the following list)
7658 @geindex -n (gnatmake)
7665 Don’t compile, bind, or link. Checks if all objects are up to date.
7666 If they are not, the full name of the first file that needs to be
7667 recompiled is printed.
7668 Repeated use of this option, followed by compiling the indicated source
7669 file, will eventually result in recompiling all required units.
7672 @geindex -o (gnatmake)
7677 @item @code{-o `exec_name'}
7679 Output executable name. The name of the final executable program will be
7680 @code{exec_name}. If the @code{-o} switch is omitted the default
7681 name for the executable will be the name of the input file in appropriate form
7682 for an executable file on the host system.
7684 This switch cannot be used when invoking @code{gnatmake} with several
7688 @geindex -p (gnatmake)
7695 Same as @code{--create-missing-dirs}
7698 @geindex -q (gnatmake)
7705 Quiet. When this flag is not set, the commands carried out by
7706 @code{gnatmake} are displayed.
7709 @geindex -s (gnatmake)
7716 Recompile if compiler switches have changed since last compilation.
7717 All compiler switches but -I and -o are taken into account in the
7719 orders between different ‘first letter’ switches are ignored, but
7720 orders between same switches are taken into account. For example,
7721 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O}
7722 is equivalent to @code{-O -g}.
7724 This switch is recommended when Integrated Preprocessing is used.
7727 @geindex -u (gnatmake)
7734 Unique. Recompile at most the main files. It implies -c. Combined with
7735 -f, it is equivalent to calling the compiler directly. Note that using
7736 -u with a project file and no main has a special meaning.
7740 @c (See :ref:`Project_Files_and_Main_Subprograms`.)
7742 @geindex -U (gnatmake)
7749 When used without a project file or with one or several mains on the command
7750 line, is equivalent to -u. When used with a project file and no main
7751 on the command line, all sources of all project files are checked and compiled
7752 if not up to date, and libraries are rebuilt, if necessary.
7755 @geindex -v (gnatmake)
7762 Verbose. Display the reason for all recompilations @code{gnatmake}
7763 decides are necessary, with the highest verbosity level.
7766 @geindex -vl (gnatmake)
7773 Verbosity level Low. Display fewer lines than in verbosity Medium.
7776 @geindex -vm (gnatmake)
7783 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7786 @geindex -vm (gnatmake)
7793 Verbosity level High. Equivalent to -v.
7797 Indicate the verbosity of the parsing of GNAT project files.
7798 See @ref{d1,,Switches Related to Project Files}.
7801 @geindex -x (gnatmake)
7808 Indicate that sources that are not part of any Project File may be compiled.
7809 Normally, when using Project Files, only sources that are part of a Project
7810 File may be compile. When this switch is used, a source outside of all Project
7811 Files may be compiled. The ALI file and the object file will be put in the
7812 object directory of the main Project. The compilation switches used will only
7813 be those specified on the command line. Even when
7814 @code{-x} is used, mains specified on the
7815 command line need to be sources of a project file.
7817 @item @code{-X`name'=`value'}
7819 Indicate that external variable @code{name} has the value @code{value}.
7820 The Project Manager will use this value for occurrences of
7821 @code{external(name)} when parsing the project file.
7822 @ref{d1,,Switches Related to Project Files}.
7825 @geindex -z (gnatmake)
7832 No main subprogram. Bind and link the program even if the unit name
7833 given on the command line is a package name. The resulting executable
7834 will execute the elaboration routines of the package and its closure,
7835 then the finalization routines.
7838 @subsubheading GCC switches
7841 Any uppercase or multi-character switch that is not a @code{gnatmake} switch
7842 is passed to @code{gcc} (e.g., @code{-O}, @code{-gnato,} etc.)
7844 @subsubheading Source and library search path switches
7847 @geindex -aI (gnatmake)
7852 @item @code{-aI`dir'}
7854 When looking for source files also look in directory @code{dir}.
7855 The order in which source files search is undertaken is
7856 described in @ref{73,,Search Paths and the Run-Time Library (RTL)}.
7859 @geindex -aL (gnatmake)
7864 @item @code{-aL`dir'}
7866 Consider @code{dir} as being an externally provided Ada library.
7867 Instructs @code{gnatmake} to skip compilation units whose @code{.ALI}
7868 files have been located in directory @code{dir}. This allows you to have
7869 missing bodies for the units in @code{dir} and to ignore out of date bodies
7870 for the same units. You still need to specify
7871 the location of the specs for these units by using the switches
7872 @code{-aI`dir'} or @code{-I`dir'}.
7873 Note: this switch is provided for compatibility with previous versions
7874 of @code{gnatmake}. The easier method of causing standard libraries
7875 to be excluded from consideration is to write-protect the corresponding
7879 @geindex -aO (gnatmake)
7884 @item @code{-aO`dir'}
7886 When searching for library and object files, look in directory
7887 @code{dir}. The order in which library files are searched is described in
7888 @ref{76,,Search Paths for gnatbind}.
7891 @geindex Search paths
7892 @geindex for gnatmake
7894 @geindex -A (gnatmake)
7899 @item @code{-A`dir'}
7901 Equivalent to @code{-aL`dir'} @code{-aI`dir'}.
7903 @geindex -I (gnatmake)
7905 @item @code{-I`dir'}
7907 Equivalent to @code{-aO`dir' -aI`dir'}.
7910 @geindex -I- (gnatmake)
7912 @geindex Source files
7913 @geindex suppressing search
7920 Do not look for source files in the directory containing the source
7921 file named in the command line.
7922 Do not look for ALI or object files in the directory
7923 where @code{gnatmake} was invoked.
7926 @geindex -L (gnatmake)
7928 @geindex Linker libraries
7933 @item @code{-L`dir'}
7935 Add directory @code{dir} to the list of directories in which the linker
7936 will search for libraries. This is equivalent to
7937 @code{-largs} @code{-L`dir'}.
7938 Furthermore, under Windows, the sources pointed to by the libraries path
7939 set in the registry are not searched for.
7942 @geindex -nostdinc (gnatmake)
7947 @item @code{-nostdinc}
7949 Do not look for source files in the system default directory.
7952 @geindex -nostdlib (gnatmake)
7957 @item @code{-nostdlib}
7959 Do not look for library files in the system default directory.
7962 @geindex --RTS (gnatmake)
7967 @item @code{--RTS=`rts-path'}
7969 Specifies the default location of the run-time library. GNAT looks for the
7971 in the following directories, and stops as soon as a valid run-time is found
7972 (@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
7973 @code{ada_object_path} present):
7979 `<current directory>/$rts_path'
7982 `<default-search-dir>/$rts_path'
7985 `<default-search-dir>/rts-$rts_path'
7988 The selected path is handled like a normal RTS path.
7992 @node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
7993 @anchor{gnat_ugn/building_executable_programs_with_gnat id4}@anchor{d2}@anchor{gnat_ugn/building_executable_programs_with_gnat mode-switches-for-gnatmake}@anchor{d3}
7994 @subsection Mode Switches for @code{gnatmake}
7997 The mode switches (referred to as @code{mode_switches}) allow the
7998 inclusion of switches that are to be passed to the compiler itself, the
7999 binder or the linker. The effect of a mode switch is to cause all
8000 subsequent switches up to the end of the switch list, or up to the next
8001 mode switch, to be interpreted as switches to be passed on to the
8002 designated component of GNAT.
8004 @geindex -cargs (gnatmake)
8009 @item @code{-cargs `switches'}
8011 Compiler switches. Here @code{switches} is a list of switches
8012 that are valid switches for @code{gcc}. They will be passed on to
8013 all compile steps performed by @code{gnatmake}.
8016 @geindex -bargs (gnatmake)
8021 @item @code{-bargs `switches'}
8023 Binder switches. Here @code{switches} is a list of switches
8024 that are valid switches for @code{gnatbind}. They will be passed on to
8025 all bind steps performed by @code{gnatmake}.
8028 @geindex -largs (gnatmake)
8033 @item @code{-largs `switches'}
8035 Linker switches. Here @code{switches} is a list of switches
8036 that are valid switches for @code{gnatlink}. They will be passed on to
8037 all link steps performed by @code{gnatmake}.
8040 @geindex -margs (gnatmake)
8045 @item @code{-margs `switches'}
8047 Make switches. The switches are directly interpreted by @code{gnatmake},
8048 regardless of any previous occurrence of @code{-cargs}, @code{-bargs}
8052 @node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
8053 @anchor{gnat_ugn/building_executable_programs_with_gnat id5}@anchor{d4}@anchor{gnat_ugn/building_executable_programs_with_gnat notes-on-the-command-line}@anchor{d5}
8054 @subsection Notes on the Command Line
8057 This section contains some additional useful notes on the operation
8058 of the @code{gnatmake} command.
8060 @geindex Recompilation (by gnatmake)
8066 If @code{gnatmake} finds no ALI files, it recompiles the main program
8067 and all other units required by the main program.
8068 This means that @code{gnatmake}
8069 can be used for the initial compile, as well as during subsequent steps of
8070 the development cycle.
8073 If you enter @code{gnatmake foo.adb}, where @code{foo}
8074 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8075 @code{foo.adb} (because it finds no ALI) and stops, issuing a
8079 In @code{gnatmake} the switch @code{-I}
8080 is used to specify both source and
8081 library file paths. Use @code{-aI}
8082 instead if you just want to specify
8083 source paths only and @code{-aO}
8084 if you want to specify library paths
8088 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8089 This may conveniently be used to exclude standard libraries from
8090 consideration and in particular it means that the use of the
8091 @code{-f} switch will not recompile these files
8092 unless @code{-a} is also specified.
8095 @code{gnatmake} has been designed to make the use of Ada libraries
8096 particularly convenient. Assume you have an Ada library organized
8097 as follows: `obj-dir' contains the objects and ALI files for
8098 of your Ada compilation units,
8099 whereas `include-dir' contains the
8100 specs of these units, but no bodies. Then to compile a unit
8101 stored in @code{main.adb}, which uses this Ada library you would just type:
8104 $ gnatmake -aI`include-dir` -aL`obj-dir` main
8108 Using @code{gnatmake} along with the @code{-m (minimal recompilation)}
8109 switch provides a mechanism for avoiding unnecessary recompilations. Using
8111 you can update the comments/format of your
8112 source files without having to recompile everything. Note, however, that
8113 adding or deleting lines in a source files may render its debugging
8114 info obsolete. If the file in question is a spec, the impact is rather
8115 limited, as that debugging info will only be useful during the
8116 elaboration phase of your program. For bodies the impact can be more
8117 significant. In all events, your debugger will warn you if a source file
8118 is more recent than the corresponding object, and alert you to the fact
8119 that the debugging information may be out of date.
8122 @node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8123 @anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{d6}@anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{d7}
8124 @subsection How @code{gnatmake} Works
8127 Generally @code{gnatmake} automatically performs all necessary
8128 recompilations and you don’t need to worry about how it works. However,
8129 it may be useful to have some basic understanding of the @code{gnatmake}
8130 approach and in particular to understand how it uses the results of
8131 previous compilations without incorrectly depending on them.
8133 First a definition: an object file is considered `up to date' if the
8134 corresponding ALI file exists and if all the source files listed in the
8135 dependency section of this ALI file have time stamps matching those in
8136 the ALI file. This means that neither the source file itself nor any
8137 files that it depends on have been modified, and hence there is no need
8138 to recompile this file.
8140 @code{gnatmake} works by first checking if the specified main unit is up
8141 to date. If so, no compilations are required for the main unit. If not,
8142 @code{gnatmake} compiles the main program to build a new ALI file that
8143 reflects the latest sources. Then the ALI file of the main unit is
8144 examined to find all the source files on which the main program depends,
8145 and @code{gnatmake} recursively applies the above procedure on all these
8148 This process ensures that @code{gnatmake} only trusts the dependencies
8149 in an existing ALI file if they are known to be correct. Otherwise it
8150 always recompiles to determine a new, guaranteed accurate set of
8151 dependencies. As a result the program is compiled ‘upside down’ from what may
8152 be more familiar as the required order of compilation in some other Ada
8153 systems. In particular, clients are compiled before the units on which
8154 they depend. The ability of GNAT to compile in any order is critical in
8155 allowing an order of compilation to be chosen that guarantees that
8156 @code{gnatmake} will recompute a correct set of new dependencies if
8159 When invoking @code{gnatmake} with several @code{file_names}, if a unit is
8160 imported by several of the executables, it will be recompiled at most once.
8162 Note: when using non-standard naming conventions
8163 (@ref{1c,,Using Other File Names}), changing through a configuration pragmas
8164 file the version of a source and invoking @code{gnatmake} to recompile may
8165 have no effect, if the previous version of the source is still accessible
8166 by @code{gnatmake}. It may be necessary to use the switch
8169 @node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8170 @anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatmake-usage}@anchor{d8}@anchor{gnat_ugn/building_executable_programs_with_gnat id7}@anchor{d9}
8171 @subsection Examples of @code{gnatmake} Usage
8177 @item @code{gnatmake hello.adb}
8179 Compile all files necessary to bind and link the main program
8180 @code{hello.adb} (containing unit @code{Hello}) and bind and link the
8181 resulting object files to generate an executable file @code{hello}.
8183 @item @code{gnatmake main1 main2 main3}
8185 Compile all files necessary to bind and link the main programs
8186 @code{main1.adb} (containing unit @code{Main1}), @code{main2.adb}
8187 (containing unit @code{Main2}) and @code{main3.adb}
8188 (containing unit @code{Main3}) and bind and link the resulting object files
8189 to generate three executable files @code{main1},
8190 @code{main2} and @code{main3}.
8192 @item @code{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8194 Compile all files necessary to bind and link the main program unit
8195 @code{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8196 be done with optimization level 2 and the order of elaboration will be
8197 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8198 displaying commands it is executing.
8201 @node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8202 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{c9}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{da}
8203 @section Compiling with @code{gcc}
8206 This section discusses how to compile Ada programs using the @code{gcc}
8207 command. It also describes the set of switches
8208 that can be used to control the behavior of the compiler.
8211 * Compiling Programs::
8212 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL.
8213 * Order of Compilation Issues::
8218 @node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8219 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{db}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{dc}
8220 @subsection Compiling Programs
8223 The first step in creating an executable program is to compile the units
8224 of the program using the @code{gcc} command. You must compile the
8231 the body file (@code{.adb}) for a library level subprogram or generic
8235 the spec file (@code{.ads}) for a library level package or generic
8236 package that has no body
8239 the body file (@code{.adb}) for a library level package
8240 or generic package that has a body
8243 You need `not' compile the following files
8249 the spec of a library unit which has a body
8255 because they are compiled as part of compiling related units. GNAT compiles
8257 when the corresponding body is compiled, and subunits when the parent is
8260 @geindex cannot generate code
8262 If you attempt to compile any of these files, you will get one of the
8263 following error messages (where @code{fff} is the name of the file you
8269 cannot generate code for file `@w{`}fff`@w{`} (package spec)
8270 to check package spec, use -gnatc
8272 cannot generate code for file `@w{`}fff`@w{`} (missing subunits)
8273 to check parent unit, use -gnatc
8275 cannot generate code for file `@w{`}fff`@w{`} (subprogram spec)
8276 to check subprogram spec, use -gnatc
8278 cannot generate code for file `@w{`}fff`@w{`} (subunit)
8279 to check subunit, use -gnatc
8283 As indicated by the above error messages, if you want to submit
8284 one of these files to the compiler to check for correct semantics
8285 without generating code, then use the @code{-gnatc} switch.
8287 The basic command for compiling a file containing an Ada unit is:
8290 $ gcc -c [switches] <file name>
8293 where @code{file name} is the name of the Ada file (usually
8294 having an extension @code{.ads} for a spec or @code{.adb} for a body).
8296 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
8297 The result of a successful compilation is an object file, which has the
8298 same name as the source file but an extension of @code{.o} and an Ada
8299 Library Information (ALI) file, which also has the same name as the
8300 source file, but with @code{.ali} as the extension. GNAT creates these
8301 two output files in the current directory, but you may specify a source
8302 file in any directory using an absolute or relative path specification
8303 containing the directory information.
8307 @code{gcc} is actually a driver program that looks at the extensions of
8308 the file arguments and loads the appropriate compiler. For example, the
8309 GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8310 These programs are in directories known to the driver program (in some
8311 configurations via environment variables you set), but need not be in
8312 your path. The @code{gcc} driver also calls the assembler and any other
8313 utilities needed to complete the generation of the required object
8316 It is possible to supply several file names on the same @code{gcc}
8317 command. This causes @code{gcc} to call the appropriate compiler for
8318 each file. For example, the following command lists two separate
8319 files to be compiled:
8322 $ gcc -c x.adb y.adb
8325 calls @code{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8327 The compiler generates two object files @code{x.o} and @code{y.o}
8328 and the two ALI files @code{x.ali} and @code{y.ali}.
8330 Any switches apply to all the files listed, see @ref{dd,,Compiler Switches} for a
8331 list of available @code{gcc} switches.
8333 @node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8334 @anchor{gnat_ugn/building_executable_programs_with_gnat id10}@anchor{de}@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-and-the-run-time-library-rtl}@anchor{73}
8335 @subsection Search Paths and the Run-Time Library (RTL)
8338 With the GNAT source-based library system, the compiler must be able to
8339 find source files for units that are needed by the unit being compiled.
8340 Search paths are used to guide this process.
8342 The compiler compiles one source file whose name must be given
8343 explicitly on the command line. In other words, no searching is done
8344 for this file. To find all other source files that are needed (the most
8345 common being the specs of units), the compiler examines the following
8346 directories, in the following order:
8352 The directory containing the source file of the main unit being compiled
8353 (the file name on the command line).
8356 Each directory named by an @code{-I} switch given on the @code{gcc}
8357 command line, in the order given.
8359 @geindex ADA_PRJ_INCLUDE_FILE
8362 Each of the directories listed in the text file whose name is given
8364 @geindex ADA_PRJ_INCLUDE_FILE
8365 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8366 @code{ADA_PRJ_INCLUDE_FILE} environment variable.
8367 @geindex ADA_PRJ_INCLUDE_FILE
8368 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8369 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8370 driver when project files are used. It should not normally be set
8373 @geindex ADA_INCLUDE_PATH
8376 Each of the directories listed in the value of the
8377 @geindex ADA_INCLUDE_PATH
8378 @geindex environment variable; ADA_INCLUDE_PATH
8379 @code{ADA_INCLUDE_PATH} environment variable.
8380 Construct this value
8383 @geindex environment variable; PATH
8384 @code{PATH} environment variable: a list of directory
8385 names separated by colons (semicolons when working with the NT version).
8388 The content of the @code{ada_source_path} file which is part of the GNAT
8389 installation tree and is used to store standard libraries such as the
8390 GNAT Run Time Library (RTL) source files.
8391 See also @ref{72,,Installing a library}.
8394 Specifying the switch @code{-I-}
8395 inhibits the use of the directory
8396 containing the source file named in the command line. You can still
8397 have this directory on your search path, but in this case it must be
8398 explicitly requested with a @code{-I} switch.
8400 Specifying the switch @code{-nostdinc}
8401 inhibits the search of the default location for the GNAT Run Time
8402 Library (RTL) source files.
8404 The compiler outputs its object files and ALI files in the current
8406 Caution: The object file can be redirected with the @code{-o} switch;
8407 however, @code{gcc} and @code{gnat1} have not been coordinated on this
8408 so the @code{ALI} file will not go to the right place. Therefore, you should
8409 avoid using the @code{-o} switch.
8413 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8414 children make up the GNAT RTL, together with the simple @code{System.IO}
8415 package used in the @code{"Hello World"} example. The sources for these units
8416 are needed by the compiler and are kept together in one directory. Not
8417 all of the bodies are needed, but all of the sources are kept together
8418 anyway. In a normal installation, you need not specify these directory
8419 names when compiling or binding. Either the environment variables or
8420 the built-in defaults cause these files to be found.
8422 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8423 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8424 consisting of child units of @code{GNAT}. This is a collection of generally
8425 useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8426 for further details.
8428 Besides simplifying access to the RTL, a major use of search paths is
8429 in compiling sources from multiple directories. This can make
8430 development environments much more flexible.
8432 @node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8433 @anchor{gnat_ugn/building_executable_programs_with_gnat id11}@anchor{df}@anchor{gnat_ugn/building_executable_programs_with_gnat order-of-compilation-issues}@anchor{e0}
8434 @subsection Order of Compilation Issues
8437 If, in our earlier example, there was a spec for the @code{hello}
8438 procedure, it would be contained in the file @code{hello.ads}; yet this
8439 file would not have to be explicitly compiled. This is the result of the
8440 model we chose to implement library management. Some of the consequences
8441 of this model are as follows:
8447 There is no point in compiling specs (except for package
8448 specs with no bodies) because these are compiled as needed by clients. If
8449 you attempt a useless compilation, you will receive an error message.
8450 It is also useless to compile subunits because they are compiled as needed
8454 There are no order of compilation requirements: performing a
8455 compilation never obsoletes anything. The only way you can obsolete
8456 something and require recompilations is to modify one of the
8457 source files on which it depends.
8460 There is no library as such, apart from the ALI files
8461 (@ref{28,,The Ada Library Information Files}, for information on the format
8462 of these files). For now we find it convenient to create separate ALI files,
8463 but eventually the information therein may be incorporated into the object
8467 When you compile a unit, the source files for the specs of all units
8468 that it `with's, all its subunits, and the bodies of any generics it
8469 instantiates must be available (reachable by the search-paths mechanism
8470 described above), or you will receive a fatal error message.
8473 @node Examples,,Order of Compilation Issues,Compiling with gcc
8474 @anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{e1}@anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{e2}
8475 @subsection Examples
8478 The following are some typical Ada compilation command line examples:
8484 Compile body in file @code{xyz.adb} with all default options.
8487 $ gcc -c -O2 -gnata xyz-def.adb
8490 Compile the child unit package in file @code{xyz-def.adb} with extensive
8491 optimizations, and pragma @code{Assert}/@code{Debug} statements
8495 $ gcc -c -gnatc abc-def.adb
8498 Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8501 @node Compiler Switches,Linker Switches,Compiling with gcc,Building Executable Programs with GNAT
8502 @anchor{gnat_ugn/building_executable_programs_with_gnat compiler-switches}@anchor{e3}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gcc}@anchor{dd}
8503 @section Compiler Switches
8506 The @code{gcc} command accepts switches that control the
8507 compilation process. These switches are fully described in this section:
8508 first an alphabetical listing of all switches with a brief description,
8509 and then functionally grouped sets of switches with more detailed
8512 More switches exist for GCC than those documented here, especially
8513 for specific targets. However, their use is not recommended as
8514 they may change code generation in ways that are incompatible with
8515 the Ada run-time library, or can cause inconsistencies between
8519 * Alphabetical List of All Switches::
8520 * Output and Error Message Control::
8521 * Warning Message Control::
8522 * Debugging and Assertion Control::
8523 * Validity Checking::
8526 * Using gcc for Syntax Checking::
8527 * Using gcc for Semantic Checking::
8528 * Compiling Different Versions of Ada::
8529 * Character Set Control::
8530 * File Naming Control::
8531 * Subprogram Inlining Control::
8532 * Auxiliary Output Control::
8533 * Debugging Control::
8534 * Exception Handling Control::
8535 * Units to Sources Mapping Files::
8536 * Code Generation Control::
8540 @node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8541 @anchor{gnat_ugn/building_executable_programs_with_gnat alphabetical-list-of-all-switches}@anchor{e4}@anchor{gnat_ugn/building_executable_programs_with_gnat id13}@anchor{e5}
8542 @subsection Alphabetical List of All Switches
8550 @item @code{-b `target'}
8552 Compile your program to run on @code{target}, which is the name of a
8553 system configuration. You must have a GNAT cross-compiler built if
8554 @code{target} is not the same as your host system.
8562 @item @code{-B`dir'}
8564 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8565 from @code{dir} instead of the default location. Only use this switch
8566 when multiple versions of the GNAT compiler are available.
8567 See the “Options for Directory Search” section in the
8568 @cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8569 You would normally use the @code{-b} or @code{-V} switch instead.
8579 Compile. Always use this switch when compiling Ada programs.
8581 Note: for some other languages when using @code{gcc}, notably in
8582 the case of C and C++, it is possible to use
8583 use @code{gcc} without a @code{-c} switch to
8584 compile and link in one step. In the case of GNAT, you
8585 cannot use this approach, because the binder must be run
8586 and @code{gcc} cannot be used to run the GNAT binder.
8589 @geindex -fcallgraph-info (gcc)
8594 @item @code{-fcallgraph-info[=su,da]}
8596 Makes the compiler output callgraph information for the program, on a
8597 per-file basis. The information is generated in the VCG format. It can
8598 be decorated with additional, per-node and/or per-edge information, if a
8599 list of comma-separated markers is additionally specified. When the
8600 @code{su} marker is specified, the callgraph is decorated with stack usage
8601 information; it is equivalent to @code{-fstack-usage}. When the @code{da}
8602 marker is specified, the callgraph is decorated with information about
8603 dynamically allocated objects.
8606 @geindex -fdiagnostics-format (gcc)
8611 @item @code{-fdiagnostics-format=json}
8613 Makes GNAT emit warning and error messages as JSON. Inhibits printing of
8614 text warning and errors messages except if @code{-gnatv} or
8615 @code{-gnatl} are present. Uses absolute file paths when used along
8619 @geindex -fdump-scos (gcc)
8624 @item @code{-fdump-scos}
8626 Generates SCO (Source Coverage Obligation) information in the ALI file.
8627 This information is used by advanced coverage tools. See unit @code{SCOs}
8628 in the compiler sources for details in files @code{scos.ads} and
8632 @geindex -fgnat-encodings (gcc)
8637 @item @code{-fgnat-encodings=[all|gdb|minimal]}
8639 This switch controls the balance between GNAT encodings and standard DWARF
8640 emitted in the debug information.
8643 @geindex -flto (gcc)
8648 @item @code{-flto[=`n']}
8650 Enables Link Time Optimization. This switch must be used in conjunction
8651 with the @code{-Ox} switches (but not with the @code{-gnatn} switch
8652 since it is a full replacement for the latter) and instructs the compiler
8653 to defer most optimizations until the link stage. The advantage of this
8654 approach is that the compiler can do a whole-program analysis and choose
8655 the best interprocedural optimization strategy based on a complete view
8656 of the program, instead of a fragmentary view with the usual approach.
8657 This can also speed up the compilation of big programs and reduce the
8658 size of the executable, compared with a traditional per-unit compilation
8659 with inlining across units enabled by the @code{-gnatn} switch.
8660 The drawback of this approach is that it may require more memory and that
8661 the debugging information generated by @code{-g} with it might be hardly usable.
8662 The switch, as well as the accompanying @code{-Ox} switches, must be
8663 specified both for the compilation and the link phases.
8664 If the @code{n} parameter is specified, the optimization and final code
8665 generation at link time are executed using @code{n} parallel jobs by
8666 means of an installed @code{make} program.
8669 @geindex -fno-inline (gcc)
8674 @item @code{-fno-inline}
8676 Suppresses all inlining, unless requested with pragma @code{Inline_Always}. The
8677 effect is enforced regardless of other optimization or inlining switches.
8678 Note that inlining can also be suppressed on a finer-grained basis with
8679 pragma @code{No_Inline}.
8682 @geindex -fno-inline-functions (gcc)
8687 @item @code{-fno-inline-functions}
8689 Suppresses automatic inlining of subprograms, which is enabled
8690 if @code{-O3} is used.
8693 @geindex -fno-inline-small-functions (gcc)
8698 @item @code{-fno-inline-small-functions}
8700 Suppresses automatic inlining of small subprograms, which is enabled
8701 if @code{-O2} is used.
8704 @geindex -fno-inline-functions-called-once (gcc)
8709 @item @code{-fno-inline-functions-called-once}
8711 Suppresses inlining of subprograms local to the unit and called once
8712 from within it, which is enabled if @code{-O1} is used.
8715 @geindex -fno-ivopts (gcc)
8720 @item @code{-fno-ivopts}
8722 Suppresses high-level loop induction variable optimizations, which are
8723 enabled if @code{-O1} is used. These optimizations are generally
8724 profitable but, for some specific cases of loops with numerous uses
8725 of the iteration variable that follow a common pattern, they may end
8726 up destroying the regularity that could be exploited at a lower level
8727 and thus producing inferior code.
8730 @geindex -fno-strict-aliasing (gcc)
8735 @item @code{-fno-strict-aliasing}
8737 Causes the compiler to avoid assumptions regarding non-aliasing
8738 of objects of different types. See
8739 @ref{e6,,Optimization and Strict Aliasing} for details.
8742 @geindex -fno-strict-overflow (gcc)
8747 @item @code{-fno-strict-overflow}
8749 Causes the compiler to avoid assumptions regarding the rules of signed
8750 integer overflow. These rules specify that signed integer overflow will
8751 result in a Constraint_Error exception at run time and are enforced in
8752 default mode by the compiler, so this switch should not be necessary in
8753 normal operating mode. It might be useful in conjunction with @code{-gnato0}
8754 for very peculiar cases of low-level programming.
8757 @geindex -fstack-check (gcc)
8762 @item @code{-fstack-check}
8764 Activates stack checking.
8765 See @ref{e7,,Stack Overflow Checking} for details.
8768 @geindex -fstack-usage (gcc)
8773 @item @code{-fstack-usage}
8775 Makes the compiler output stack usage information for the program, on a
8776 per-subprogram basis. See @ref{e8,,Static Stack Usage Analysis} for details.
8786 Generate debugging information. This information is stored in the object
8787 file and copied from there to the final executable file by the linker,
8788 where it can be read by the debugger. You must use the
8789 @code{-g} switch if you plan on using the debugger.
8792 @geindex -gnat05 (gcc)
8797 @item @code{-gnat05}
8799 Allow full Ada 2005 features.
8802 @geindex -gnat12 (gcc)
8807 @item @code{-gnat12}
8809 Allow full Ada 2012 features.
8812 @geindex -gnat83 (gcc)
8814 @geindex -gnat2005 (gcc)
8819 @item @code{-gnat2005}
8821 Allow full Ada 2005 features (same as @code{-gnat05})
8824 @geindex -gnat2012 (gcc)
8829 @item @code{-gnat2012}
8831 Allow full Ada 2012 features (same as @code{-gnat12})
8834 @geindex -gnat2022 (gcc)
8839 @item @code{-gnat2022}
8841 Allow full Ada 2022 features
8843 @item @code{-gnat83}
8845 Enforce Ada 83 restrictions.
8848 @geindex -gnat95 (gcc)
8853 @item @code{-gnat95}
8855 Enforce Ada 95 restrictions.
8857 Note: for compatibility with some Ada 95 compilers which support only
8858 the @code{overriding} keyword of Ada 2005, the @code{-gnatd.D} switch can
8859 be used along with @code{-gnat95} to achieve a similar effect with GNAT.
8861 @code{-gnatd.D} instructs GNAT to consider @code{overriding} as a keyword
8862 and handle its associated semantic checks, even in Ada 95 mode.
8865 @geindex -gnata (gcc)
8872 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
8873 activated. Note that these pragmas can also be controlled using the
8874 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
8875 It also activates pragmas @code{Check}, @code{Precondition}, and
8876 @code{Postcondition}. Note that these pragmas can also be controlled
8877 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
8878 also activates all assertions defined in the RM as aspects: preconditions,
8879 postconditions, type invariants and (sub)type predicates. In all Ada modes,
8880 corresponding pragmas for type invariants and (sub)type predicates are
8881 also activated. The default is that all these assertions are disabled,
8882 and have no effect, other than being checked for syntactic validity, and
8883 in the case of subtype predicates, constructions such as membership tests
8884 still test predicates even if assertions are turned off.
8887 @geindex -gnatA (gcc)
8894 Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
8898 @geindex -gnatb (gcc)
8905 Generate brief messages to @code{stderr} even if verbose mode set.
8908 @geindex -gnatB (gcc)
8915 Assume no invalid (bad) values except for ‘Valid attribute use
8916 (@ref{e9,,Validity Checking}).
8919 @geindex -gnatc (gcc)
8926 Check syntax and semantics only (no code generation attempted). When the
8927 compiler is invoked by @code{gnatmake}, if the switch @code{-gnatc} is
8928 only given to the compiler (after @code{-cargs} or in package Compiler of
8929 the project file), @code{gnatmake} will fail because it will not find the
8930 object file after compilation. If @code{gnatmake} is called with
8931 @code{-gnatc} as a builder switch (before @code{-cargs} or in package
8932 Builder of the project file) then @code{gnatmake} will not fail because
8933 it will not look for the object files after compilation, and it will not try
8937 @geindex -gnatC (gcc)
8944 Generate CodePeer intermediate format (no code generation attempted).
8945 This switch will generate an intermediate representation suitable for
8946 use by CodePeer (@code{.scil} files). This switch is not compatible with
8947 code generation (it will, among other things, disable some switches such
8948 as @code{-gnatn}, and enable others such as @code{-gnata}).
8951 @geindex -gnatd (gcc)
8958 Specify debug options for the compiler. The string of characters after
8959 the @code{-gnatd} specifies the specific debug options. The possible
8960 characters are 0-9, a-z, A-Z, optionally preceded by a dot or underscore.
8961 See compiler source file @code{debug.adb} for details of the implemented
8962 debug options. Certain debug options are relevant to application
8963 programmers, and these are documented at appropriate points in this
8967 @geindex -gnatD[nn] (gcc)
8974 Create expanded source files for source level debugging. This switch
8975 also suppresses generation of cross-reference information
8976 (see @code{-gnatx}). Note that this switch is not allowed if a previous
8977 @code{-gnatR} switch has been given, since these two switches are not compatible.
8980 @geindex -gnateA (gcc)
8985 @item @code{-gnateA}
8987 Check that the actual parameters of a subprogram call are not aliases of one
8988 another. To qualify as aliasing, their memory locations must be identical or
8989 overlapping, at least one of the corresponding formal parameters must be of
8990 mode OUT or IN OUT, and at least one of the corresponding formal parameters
8991 must have its parameter passing mechanism not specified.
8994 type Rec_Typ is record
8995 Data : Integer := 0;
8998 function Self (Val : Rec_Typ) return Rec_Typ is
9003 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
9006 end Detect_Aliasing;
9010 Detect_Aliasing (Obj, Obj);
9011 Detect_Aliasing (Obj, Self (Obj));
9014 In the example above, the first call to @code{Detect_Aliasing} fails with a
9015 @code{Program_Error} at run time because the actuals for @code{Val_1} and
9016 @code{Val_2} denote the same object. The second call executes without raising
9017 an exception because @code{Self(Obj)} produces an anonymous object which does
9018 not share the memory location of @code{Obj}.
9021 @geindex -gnateb (gcc)
9026 @item @code{-gnateb}
9028 Store configuration files by their basename in ALI files. This switch is
9029 used for instance by gprbuild for distributed builds in order to prevent
9030 issues where machine-specific absolute paths could end up being stored in
9034 @geindex -gnatec (gcc)
9039 @item @code{-gnatec=`path'}
9041 Specify a configuration pragma file
9042 (the equal sign is optional)
9043 (@ref{63,,The Configuration Pragmas Files}).
9046 @geindex -gnateC (gcc)
9051 @item @code{-gnateC}
9053 Generate CodePeer messages in a compiler-like format. This switch is only
9054 effective if @code{-gnatcC} is also specified and requires an installation
9058 @geindex -gnated (gcc)
9063 @item @code{-gnated}
9065 Disable atomic synchronization
9068 @geindex -gnateD (gcc)
9073 @item @code{-gnateDsymbol[=`value']}
9075 Defines a symbol, associated with @code{value}, for preprocessing.
9076 (@ref{90,,Integrated Preprocessing}).
9079 @geindex -gnateE (gcc)
9084 @item @code{-gnateE}
9086 Generate extra information in exception messages. In particular, display
9087 extra column information and the value and range associated with index and
9088 range check failures, and extra column information for access checks.
9089 In cases where the compiler is able to determine at compile time that
9090 a check will fail, it gives a warning, and the extra information is not
9091 produced at run time.
9094 @geindex -gnatef (gcc)
9099 @item @code{-gnatef}
9101 Display full source path name in brief error messages and absolute paths in
9102 @code{-fdiagnostics-format=json}’s output.
9105 @geindex -gnateF (gcc)
9110 @item @code{-gnateF}
9112 Check for overflow on all floating-point operations, including those
9113 for unconstrained predefined types. See description of pragma
9114 @code{Check_Float_Overflow} in GNAT RM.
9117 @geindex -gnateg (gcc)
9124 The @code{-gnatc} switch must always be specified before this switch, e.g.
9125 @code{-gnatceg}. Generate a C header from the Ada input file. See
9126 @ref{b9,,Generating C Headers for Ada Specifications} for more
9130 @geindex -gnateG (gcc)
9135 @item @code{-gnateG}
9137 Save result of preprocessing in a text file.
9140 @geindex -gnateH (gcc)
9145 @item @code{-gnateH}
9147 Set the threshold from which the RM 13.5.1(13.3/2) clause applies to 64.
9148 This is useful only on 64-bit plaforms where this threshold is 128, but
9149 used to be 64 in earlier versions of the compiler.
9152 @geindex -gnatei (gcc)
9157 @item @code{-gnatei`nnn'}
9159 Set maximum number of instantiations during compilation of a single unit to
9160 @code{nnn}. This may be useful in increasing the default maximum of 8000 for
9161 the rare case when a single unit legitimately exceeds this limit.
9164 @geindex -gnateI (gcc)
9169 @item @code{-gnateI`nnn'}
9171 Indicates that the source is a multi-unit source and that the index of the
9172 unit to compile is @code{nnn}. @code{nnn} needs to be a positive number and need
9173 to be a valid index in the multi-unit source.
9176 @geindex -gnatel (gcc)
9181 @item @code{-gnatel}
9183 This switch can be used with the static elaboration model to issue info
9185 where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
9186 are generated. This is useful in diagnosing elaboration circularities
9187 caused by these implicit pragmas when using the static elaboration
9188 model. See the section in this guide on elaboration checking for
9189 further details. These messages are not generated by default, and are
9190 intended only for temporary use when debugging circularity problems.
9193 @geindex -gnatel (gcc)
9198 @item @code{-gnateL}
9200 This switch turns off the info messages about implicit elaboration pragmas.
9203 @geindex -gnatem (gcc)
9208 @item @code{-gnatem=`path'}
9210 Specify a mapping file
9211 (the equal sign is optional)
9212 (@ref{ea,,Units to Sources Mapping Files}).
9215 @geindex -gnatep (gcc)
9220 @item @code{-gnatep=`file'}
9222 Specify a preprocessing data file
9223 (the equal sign is optional)
9224 (@ref{90,,Integrated Preprocessing}).
9227 @geindex -gnateP (gcc)
9232 @item @code{-gnateP}
9234 Turn categorization dependency errors into warnings.
9235 Ada requires that units that WITH one another have compatible categories, for
9236 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9237 these errors become warnings (which can be ignored, or suppressed in the usual
9238 manner). This can be useful in some specialized circumstances such as the
9239 temporary use of special test software.
9242 @geindex -gnateS (gcc)
9247 @item @code{-gnateS}
9249 Synonym of @code{-fdump-scos}, kept for backwards compatibility.
9252 @geindex -gnatet=file (gcc)
9257 @item @code{-gnatet=`path'}
9259 Generate target dependent information. The format of the output file is
9260 described in the section about switch @code{-gnateT}.
9263 @geindex -gnateT (gcc)
9268 @item @code{-gnateT=`path'}
9270 Read target dependent information, such as endianness or sizes and alignments
9271 of base type. If this switch is passed, the default target dependent
9272 information of the compiler is replaced by the one read from the input file.
9273 This is used by tools other than the compiler, e.g. to do
9274 semantic analysis of programs that will run on some other target than
9275 the machine on which the tool is run.
9277 The following target dependent values should be defined,
9278 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
9279 positive integer value, and fields marked with a question mark are
9280 boolean fields, where a value of 0 is False, and a value of 1 is True:
9283 Bits_BE : Nat; -- Bits stored big-endian?
9284 Bits_Per_Unit : Pos; -- Bits in a storage unit
9285 Bits_Per_Word : Pos; -- Bits in a word
9286 Bytes_BE : Nat; -- Bytes stored big-endian?
9287 Char_Size : Pos; -- Standard.Character'Size
9288 Double_Float_Alignment : Nat; -- Alignment of double float
9289 Double_Scalar_Alignment : Nat; -- Alignment of double length scalar
9290 Double_Size : Pos; -- Standard.Long_Float'Size
9291 Float_Size : Pos; -- Standard.Float'Size
9292 Float_Words_BE : Nat; -- Float words stored big-endian?
9293 Int_Size : Pos; -- Standard.Integer'Size
9294 Long_Double_Size : Pos; -- Standard.Long_Long_Float'Size
9295 Long_Long_Long_Size : Pos; -- Standard.Long_Long_Long_Integer'Size
9296 Long_Long_Size : Pos; -- Standard.Long_Long_Integer'Size
9297 Long_Size : Pos; -- Standard.Long_Integer'Size
9298 Maximum_Alignment : Pos; -- Maximum permitted alignment
9299 Max_Unaligned_Field : Pos; -- Maximum size for unaligned bit field
9300 Pointer_Size : Pos; -- System.Address'Size
9301 Short_Enums : Nat; -- Foreign enums use short size?
9302 Short_Size : Pos; -- Standard.Short_Integer'Size
9303 Strict_Alignment : Nat; -- Strict alignment?
9304 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9305 Wchar_T_Size : Pos; -- Interfaces.C.wchar_t'Size
9306 Words_BE : Nat; -- Words stored big-endian?
9309 @code{Bits_Per_Unit} is the number of bits in a storage unit, the equivalent of
9310 GCC macro @code{BITS_PER_UNIT} documented as follows: @cite{Define this macro to be the number of bits in an addressable storage unit (byte); normally 8.}
9312 @code{Bits_Per_Word} is the number of bits in a machine word, the equivalent of
9313 GCC macro @code{BITS_PER_WORD} documented as follows: @cite{Number of bits in a word; normally 32.}
9315 @code{Double_Float_Alignment}, if not zero, is the maximum alignment that the
9316 compiler can choose by default for a 64-bit floating-point type or object.
9318 @code{Double_Scalar_Alignment}, if not zero, is the maximum alignment that the
9319 compiler can choose by default for a 64-bit or larger scalar type or object.
9321 @code{Maximum_Alignment} is the maximum alignment that the compiler can choose
9322 by default for a type or object, which is also the maximum alignment that can
9323 be specified in GNAT. It is computed for GCC backends as @code{BIGGEST_ALIGNMENT
9324 / BITS_PER_UNIT} where GCC macro @code{BIGGEST_ALIGNMENT} is documented as
9325 follows: @cite{Biggest alignment that any data type can require on this machine@comma{} in bits.}
9327 @code{Max_Unaligned_Field} is the maximum size for unaligned bit field, which is
9328 64 for the majority of GCC targets (but can be different on some targets).
9330 @code{Strict_Alignment} is the equivalent of GCC macro @code{STRICT_ALIGNMENT}
9331 documented as follows: @cite{Define this macro to be the value 1 if instructions will fail to work if given data not on the nominal alignment. If instructions will merely go slower in that case@comma{} define this macro as 0.}
9333 @code{System_Allocator_Alignment} is the guaranteed alignment of data returned
9334 by calls to @code{malloc}.
9336 The format of the input file is as follows. First come the values of
9337 the variables defined above, with one line per value:
9343 where @code{name} is the name of the parameter, spelled out in full,
9344 and cased as in the above list, and @code{value} is an unsigned decimal
9345 integer. Two or more blanks separates the name from the value.
9347 All the variables must be present, in alphabetical order (i.e. the
9348 same order as the list above).
9350 Then there is a blank line to separate the two parts of the file. Then
9351 come the lines showing the floating-point types to be registered, with
9352 one line per registered mode:
9355 name digs float_rep size alignment
9358 where @code{name} is the string name of the type (which can have
9359 single spaces embedded in the name, e.g. long double), @code{digs} is
9360 the number of digits for the floating-point type, @code{float_rep} is
9361 the float representation (I for IEEE-754-Binary, which is
9362 the only one supported at this time),
9363 @code{size} is the size in bits, @code{alignment} is the
9364 alignment in bits. The name is followed by at least two blanks, fields
9365 are separated by at least one blank, and a LF character immediately
9366 follows the alignment field.
9368 Here is an example of a target parameterization file:
9376 Double_Float_Alignment 0
9377 Double_Scalar_Alignment 0
9382 Long_Double_Size 128
9383 Long_Long_Long_Size 128
9386 Maximum_Alignment 16
9387 Max_Unaligned_Field 64
9391 System_Allocator_Alignment 16
9397 long double 18 I 80 128
9402 @geindex -gnateu (gcc)
9407 @item @code{-gnateu}
9409 Ignore unrecognized validity, warning, and style switches that
9410 appear after this switch is given. This may be useful when
9411 compiling sources developed on a later version of the compiler
9412 with an earlier version. Of course the earlier version must
9413 support this switch.
9416 @geindex -gnateV (gcc)
9421 @item @code{-gnateV}
9423 Check that all actual parameters of a subprogram call are valid according to
9424 the rules of validity checking (@ref{e9,,Validity Checking}).
9427 @geindex -gnateY (gcc)
9432 @item @code{-gnateY}
9434 Ignore all STYLE_CHECKS pragmas. Full legality checks
9435 are still carried out, but the pragmas have no effect
9436 on what style checks are active. This allows all style
9437 checking options to be controlled from the command line.
9440 @geindex -gnatE (gcc)
9447 Dynamic elaboration checking mode enabled. For further details see
9448 @ref{f,,Elaboration Order Handling in GNAT}.
9451 @geindex -gnatf (gcc)
9458 Full errors. Multiple errors per line, all undefined references, do not
9459 attempt to suppress cascaded errors.
9462 @geindex -gnatF (gcc)
9469 Externals names are folded to all uppercase.
9472 @geindex -gnatg (gcc)
9479 Internal GNAT implementation mode. This should not be used for applications
9480 programs, it is intended only for use by the compiler and its run-time
9481 library. For documentation, see the GNAT sources. Note that @code{-gnatg}
9482 implies @code{-gnatw.ge} and @code{-gnatyg} so that all standard
9483 warnings and all standard style options are turned on. All warnings and style
9484 messages are treated as errors.
9487 @geindex -gnatG[nn] (gcc)
9492 @item @code{-gnatG=nn}
9494 List generated expanded code in source form.
9497 @geindex -gnath (gcc)
9504 Output usage information. The output is written to @code{stdout}.
9507 @geindex -gnatH (gcc)
9514 Legacy elaboration-checking mode enabled. When this switch is in effect,
9515 the pre-18.x access-before-elaboration model becomes the de facto model.
9516 For further details see @ref{f,,Elaboration Order Handling in GNAT}.
9519 @geindex -gnati (gcc)
9524 @item @code{-gnati`c'}
9526 Identifier character set (@code{c} = 1/2/3/4/5/9/p/8/f/n/w).
9527 For details of the possible selections for @code{c},
9528 see @ref{31,,Character Set Control}.
9531 @geindex -gnatI (gcc)
9538 Ignore representation clauses. When this switch is used,
9539 representation clauses are treated as comments. This is useful
9540 when initially porting code where you want to ignore rep clause
9541 problems, and also for compiling foreign code (particularly
9542 for use with ASIS). The representation clauses that are ignored
9543 are: enumeration_representation_clause, record_representation_clause,
9544 and attribute_definition_clause for the following attributes:
9545 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9546 Object_Size, Scalar_Storage_Order, Size, Small, Stream_Size,
9547 and Value_Size. Pragma Default_Scalar_Storage_Order is also ignored.
9548 Note that this option should be used only for compiling – the
9549 code is likely to malfunction at run time.
9552 @geindex -gnatjnn (gcc)
9557 @item @code{-gnatj`nn'}
9559 Reformat error messages to fit on @code{nn} character lines
9562 @geindex -gnatJ (gcc)
9569 Permissive elaboration-checking mode enabled. When this switch is in effect,
9570 the post-18.x access-before-elaboration model ignores potential issues with:
9579 Activations of tasks defined in instances
9585 Calls from within an instance to its enclosing context
9588 Calls through generic formal parameters
9591 Calls to subprograms defined in instances
9597 Indirect calls using ‘Access
9606 Synchronous task suspension
9609 and does not emit compile-time diagnostics or run-time checks. For further
9610 details see @ref{f,,Elaboration Order Handling in GNAT}.
9613 @geindex -gnatk (gcc)
9618 @item @code{-gnatk=`n'}
9620 Limit file names to @code{n} (1-999) characters (@code{k} = krunch).
9623 @geindex -gnatl (gcc)
9630 Output full source listing with embedded error messages.
9633 @geindex -gnatL (gcc)
9640 Used in conjunction with -gnatG or -gnatD to intersperse original
9641 source lines (as comment lines with line numbers) in the expanded
9645 @geindex -gnatm (gcc)
9650 @item @code{-gnatm=`n'}
9652 Limit number of detected error or warning messages to @code{n}
9653 where @code{n} is in the range 1..999999. The default setting if
9654 no switch is given is 9999. If the number of warnings reaches this
9655 limit, then a message is output and further warnings are suppressed,
9656 but the compilation is continued. If the number of error messages
9657 reaches this limit, then a message is output and the compilation
9658 is abandoned. The equal sign here is optional. A value of zero
9659 means that no limit applies.
9662 @geindex -gnatn (gcc)
9667 @item @code{-gnatn[12]}
9669 Activate inlining across units for subprograms for which pragma @code{Inline}
9670 is specified. This inlining is performed by the GCC back-end. An optional
9671 digit sets the inlining level: 1 for moderate inlining across units
9672 or 2 for full inlining across units. If no inlining level is specified,
9673 the compiler will pick it based on the optimization level.
9676 @geindex -gnatN (gcc)
9683 Activate front end inlining for subprograms for which
9684 pragma @code{Inline} is specified. This inlining is performed
9685 by the front end and will be visible in the
9686 @code{-gnatG} output.
9688 When using a gcc-based back end, then the use of
9689 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
9690 Historically front end inlining was more extensive than the gcc back end
9691 inlining, but that is no longer the case.
9694 @geindex -gnato0 (gcc)
9699 @item @code{-gnato0}
9701 Suppresses overflow checking. This causes the behavior of the compiler to
9702 match the default for older versions where overflow checking was suppressed
9703 by default. This is equivalent to having
9704 @code{pragma Suppress (Overflow_Check)} in a configuration pragma file.
9707 @geindex -gnato?? (gcc)
9712 @item @code{-gnato??}
9714 Set default mode for handling generation of code to avoid intermediate
9715 arithmetic overflow. Here @code{??} is two digits, a
9716 single digit, or nothing. Each digit is one of the digits @code{1}
9720 @multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
9735 All intermediate overflows checked against base type (@code{STRICT})
9743 Minimize intermediate overflows (@code{MINIMIZED})
9751 Eliminate intermediate overflows (@code{ELIMINATED})
9756 If only one digit appears, then it applies to all
9757 cases; if two digits are given, then the first applies outside
9758 assertions, pre/postconditions, and type invariants, and the second
9759 applies within assertions, pre/postconditions, and type invariants.
9761 If no digits follow the @code{-gnato}, then it is equivalent to
9763 causing all intermediate overflows to be handled in strict
9766 This switch also causes arithmetic overflow checking to be performed
9767 (as though @code{pragma Unsuppress (Overflow_Check)} had been specified).
9769 The default if no option @code{-gnato} is given is that overflow handling
9770 is in @code{STRICT} mode (computations done using the base type), and that
9771 overflow checking is enabled.
9773 Note that division by zero is a separate check that is not
9774 controlled by this switch (divide-by-zero checking is on by default).
9776 See also @ref{eb,,Specifying the Desired Mode}.
9779 @geindex -gnatp (gcc)
9786 Suppress all checks. See @ref{ec,,Run-Time Checks} for details. This switch
9787 has no effect if cancelled by a subsequent @code{-gnat-p} switch.
9790 @geindex -gnat-p (gcc)
9795 @item @code{-gnat-p}
9797 Cancel effect of previous @code{-gnatp} switch.
9800 @geindex -gnatq (gcc)
9807 Don’t quit. Try semantics, even if parse errors.
9810 @geindex -gnatQ (gcc)
9817 Don’t quit. Generate @code{ALI} and tree files even if illegalities.
9818 Note that code generation is still suppressed in the presence of any
9819 errors, so even with @code{-gnatQ} no object file is generated.
9822 @geindex -gnatr (gcc)
9829 Treat pragma Restrictions as Restriction_Warnings.
9832 @geindex -gnatR (gcc)
9837 @item @code{-gnatR[0|1|2|3|4][e][j][m][s]}
9839 Output representation information for declared types, objects and
9840 subprograms. Note that this switch is not allowed if a previous
9841 @code{-gnatD} switch has been given, since these two switches
9845 @geindex -gnats (gcc)
9855 @geindex -gnatS (gcc)
9862 Print package Standard.
9865 @geindex -gnatT (gcc)
9870 @item @code{-gnatT`nnn'}
9872 All compiler tables start at @code{nnn} times usual starting size.
9875 @geindex -gnatu (gcc)
9882 List units for this compilation.
9885 @geindex -gnatU (gcc)
9892 Tag all error messages with the unique string ‘error:’
9895 @geindex -gnatv (gcc)
9902 Verbose mode. Full error output with source lines to @code{stdout}.
9905 @geindex -gnatV (gcc)
9912 Control level of validity checking (@ref{e9,,Validity Checking}).
9915 @geindex -gnatw (gcc)
9920 @item @code{-gnatw`xxx'}
9923 @code{xxx} is a string of option letters that denotes
9924 the exact warnings that
9925 are enabled or disabled (@ref{ed,,Warning Message Control}).
9928 @geindex -gnatW (gcc)
9933 @item @code{-gnatW`e'}
9935 Wide character encoding method
9936 (@code{e}=n/h/u/s/e/8).
9939 @geindex -gnatx (gcc)
9946 Suppress generation of cross-reference information.
9949 @geindex -gnatX (gcc)
9956 Enable core GNAT implementation extensions and latest Ada version.
9959 @geindex -gnatX0 (gcc)
9964 @item @code{-gnatX0}
9966 Enable all GNAT implementation extensions and latest Ada version.
9969 @geindex -gnaty (gcc)
9976 Enable built-in style checks (@ref{ee,,Style Checking}).
9979 @geindex -gnatz (gcc)
9984 @item @code{-gnatz`m'}
9986 Distribution stub generation and compilation
9987 (@code{m}=r/c for receiver/caller stubs).
9995 @item @code{-I`dir'}
9999 Direct GNAT to search the @code{dir} directory for source files needed by
10000 the current compilation
10001 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
10013 Except for the source file named in the command line, do not look for source
10014 files in the directory containing the source file named in the command line
10015 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
10023 @item @code{-o `file'}
10025 This switch is used in @code{gcc} to redirect the generated object file
10026 and its associated ALI file. Beware of this switch with GNAT, because it may
10027 cause the object file and ALI file to have different names which in turn
10028 may confuse the binder and the linker.
10031 @geindex -nostdinc (gcc)
10036 @item @code{-nostdinc}
10038 Inhibit the search of the default location for the GNAT Run Time
10039 Library (RTL) source files.
10042 @geindex -nostdlib (gcc)
10047 @item @code{-nostdlib}
10049 Inhibit the search of the default location for the GNAT Run Time
10050 Library (RTL) ALI files.
10058 @item @code{-O[`n']}
10060 @code{n} controls the optimization level:
10063 @multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
10078 No optimization, the default setting if no @code{-O} appears
10086 Normal optimization, the default if you specify @code{-O} without an
10087 operand. A good compromise between code quality and compilation
10096 Extensive optimization, may improve execution time, possibly at
10097 the cost of substantially increased compilation time.
10105 Same as @code{-O2}, and also includes inline expansion for small
10106 subprograms in the same unit.
10114 Optimize space usage
10119 See also @ref{ef,,Optimization Levels}.
10122 @geindex -pass-exit-codes (gcc)
10127 @item @code{-pass-exit-codes}
10129 Catch exit codes from the compiler and use the most meaningful as
10133 @geindex --RTS (gcc)
10138 @item @code{--RTS=`rts-path'}
10140 Specifies the default location of the run-time library. Same meaning as the
10141 equivalent @code{gnatmake} flag (@ref{d0,,Switches for gnatmake}).
10151 Used in place of @code{-c} to
10152 cause the assembler source file to be
10153 generated, using @code{.s} as the extension,
10154 instead of the object file.
10155 This may be useful if you need to examine the generated assembly code.
10158 @geindex -fverbose-asm (gcc)
10163 @item @code{-fverbose-asm}
10165 Used in conjunction with @code{-S}
10166 to cause the generated assembly code file to be annotated with variable
10167 names, making it significantly easier to follow.
10177 Show commands generated by the @code{gcc} driver. Normally used only for
10178 debugging purposes or if you need to be sure what version of the
10179 compiler you are executing.
10187 @item @code{-V `ver'}
10189 Execute @code{ver} version of the compiler. This is the @code{gcc}
10190 version, not the GNAT version.
10200 Turn off warnings generated by the back end of the compiler. Use of
10201 this switch also causes the default for front end warnings to be set
10202 to suppress (as though @code{-gnatws} had appeared at the start of
10206 @geindex Combining GNAT switches
10208 You may combine a sequence of GNAT switches into a single switch. For
10209 example, the combined switch
10218 is equivalent to specifying the following sequence of switches:
10223 -gnato -gnatf -gnati3
10227 The following restrictions apply to the combination of switches
10234 The switch @code{-gnatc} if combined with other switches must come
10235 first in the string.
10238 The switch @code{-gnats} if combined with other switches must come
10239 first in the string.
10243 @code{-gnatzc} and @code{-gnatzr} may not be combined with any other
10244 switches, and only one of them may appear in the command line.
10247 The switch @code{-gnat-p} may not be combined with any other switch.
10250 Once a ‘y’ appears in the string (that is a use of the @code{-gnaty}
10251 switch), then all further characters in the switch are interpreted
10252 as style modifiers (see description of @code{-gnaty}).
10255 Once a ‘d’ appears in the string (that is a use of the @code{-gnatd}
10256 switch), then all further characters in the switch are interpreted
10257 as debug flags (see description of @code{-gnatd}).
10260 Once a ‘w’ appears in the string (that is a use of the @code{-gnatw}
10261 switch), then all further characters in the switch are interpreted
10262 as warning mode modifiers (see description of @code{-gnatw}).
10265 Once a ‘V’ appears in the string (that is a use of the @code{-gnatV}
10266 switch), then all further characters in the switch are interpreted
10267 as validity checking options (@ref{e9,,Validity Checking}).
10270 Option ‘em’, ‘ec’, ‘ep’, ‘l=’ and ‘R’ must be the last options in
10271 a combined list of options.
10274 @node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10275 @anchor{gnat_ugn/building_executable_programs_with_gnat id14}@anchor{f0}@anchor{gnat_ugn/building_executable_programs_with_gnat output-and-error-message-control}@anchor{f1}
10276 @subsection Output and Error Message Control
10281 The standard default format for error messages is called ‘brief format’.
10282 Brief format messages are written to @code{stderr} (the standard error
10283 file) and have the following form:
10286 e.adb:3:04: Incorrect spelling of keyword "function"
10287 e.adb:4:20: ";" should be "is"
10290 The first integer after the file name is the line number in the file,
10291 and the second integer is the column number within the line.
10292 @code{GNAT Studio} can parse the error messages
10293 and point to the referenced character.
10294 The following switches provide control over the error message
10297 @geindex -gnatv (gcc)
10302 @item @code{-gnatv}
10304 The @code{v} stands for verbose.
10305 The effect of this setting is to write long-format error
10306 messages to @code{stdout} (the standard output file).
10307 The same program compiled with the
10308 @code{-gnatv} switch would generate:
10311 3. funcion X (Q : Integer)
10313 >>> Incorrect spelling of keyword "function"
10316 >>> ";" should be "is"
10319 The vertical bar indicates the location of the error, and the @code{>>>}
10320 prefix can be used to search for error messages. When this switch is
10321 used the only source lines output are those with errors.
10324 @geindex -gnatl (gcc)
10329 @item @code{-gnatl}
10331 The @code{l} stands for list.
10332 This switch causes a full listing of
10333 the file to be generated. In the case where a body is
10334 compiled, the corresponding spec is also listed, along
10335 with any subunits. Typical output from compiling a package
10336 body @code{p.adb} might look like:
10341 1. package body p is
10343 3. procedure a is separate;
10354 2. pragma Elaborate_Body
10375 When you specify the @code{-gnatv} or @code{-gnatl} switches and
10376 standard output is redirected, a brief summary is written to
10377 @code{stderr} (standard error) giving the number of error messages and
10378 warning messages generated.
10381 @geindex -gnatl=fname (gcc)
10386 @item @code{-gnatl=`fname'}
10388 This has the same effect as @code{-gnatl} except that the output is
10389 written to a file instead of to standard output. If the given name
10390 @code{fname} does not start with a period, then it is the full name
10391 of the file to be written. If @code{fname} is an extension, it is
10392 appended to the name of the file being compiled. For example, if
10393 file @code{xyz.adb} is compiled with @code{-gnatl=.lst},
10394 then the output is written to file xyz.adb.lst.
10397 @geindex -gnatU (gcc)
10402 @item @code{-gnatU}
10404 This switch forces all error messages to be preceded by the unique
10405 string ‘error:’. This means that error messages take a few more
10406 characters in space, but allows easy searching for and identification
10410 @geindex -gnatb (gcc)
10415 @item @code{-gnatb}
10417 The @code{b} stands for brief.
10418 This switch causes GNAT to generate the
10419 brief format error messages to @code{stderr} (the standard error
10420 file) as well as the verbose
10421 format message or full listing (which as usual is written to
10422 @code{stdout}, the standard output file).
10425 @geindex -gnatm (gcc)
10430 @item @code{-gnatm=`n'}
10432 The @code{m} stands for maximum.
10433 @code{n} is a decimal integer in the
10434 range of 1 to 999999 and limits the number of error or warning
10435 messages to be generated. For example, using
10436 @code{-gnatm2} might yield
10439 e.adb:3:04: Incorrect spelling of keyword "function"
10440 e.adb:5:35: missing ".."
10441 fatal error: maximum number of errors detected
10442 compilation abandoned
10445 The default setting if
10446 no switch is given is 9999. If the number of warnings reaches this
10447 limit, then a message is output and further warnings are suppressed,
10448 but the compilation is continued. If the number of error messages
10449 reaches this limit, then a message is output and the compilation
10450 is abandoned. A value of zero means that no limit applies.
10452 Note that the equal sign is optional, so the switches
10453 @code{-gnatm2} and @code{-gnatm=2} are equivalent.
10456 @geindex -gnatf (gcc)
10461 @item @code{-gnatf}
10463 @geindex Error messages
10464 @geindex suppressing
10466 The @code{f} stands for full.
10467 Normally, the compiler suppresses error messages that are likely to be
10468 redundant. This switch causes all error
10469 messages to be generated. In particular, in the case of
10470 references to undefined variables. If a given variable is referenced
10471 several times, the normal format of messages is
10474 e.adb:7:07: "V" is undefined (more references follow)
10477 where the parenthetical comment warns that there are additional
10478 references to the variable @code{V}. Compiling the same program with the
10479 @code{-gnatf} switch yields
10482 e.adb:7:07: "V" is undefined
10483 e.adb:8:07: "V" is undefined
10484 e.adb:8:12: "V" is undefined
10485 e.adb:8:16: "V" is undefined
10486 e.adb:9:07: "V" is undefined
10487 e.adb:9:12: "V" is undefined
10490 The @code{-gnatf} switch also generates additional information for
10491 some error messages. Some examples are:
10497 Details on possibly non-portable unchecked conversion
10500 List possible interpretations for ambiguous calls
10503 Additional details on incorrect parameters
10507 @geindex -gnatjnn (gcc)
10512 @item @code{-gnatjnn}
10514 In normal operation mode (or if @code{-gnatj0} is used), then error messages
10515 with continuation lines are treated as though the continuation lines were
10516 separate messages (and so a warning with two continuation lines counts as
10517 three warnings, and is listed as three separate messages).
10519 If the @code{-gnatjnn} switch is used with a positive value for nn, then
10520 messages are output in a different manner. A message and all its continuation
10521 lines are treated as a unit, and count as only one warning or message in the
10522 statistics totals. Furthermore, the message is reformatted so that no line
10523 is longer than nn characters.
10526 @geindex -gnatq (gcc)
10531 @item @code{-gnatq}
10533 The @code{q} stands for quit (really ‘don’t quit’).
10534 In normal operation mode, the compiler first parses the program and
10535 determines if there are any syntax errors. If there are, appropriate
10536 error messages are generated and compilation is immediately terminated.
10538 GNAT to continue with semantic analysis even if syntax errors have been
10539 found. This may enable the detection of more errors in a single run. On
10540 the other hand, the semantic analyzer is more likely to encounter some
10541 internal fatal error when given a syntactically invalid tree.
10544 @geindex -gnatQ (gcc)
10549 @item @code{-gnatQ}
10551 In normal operation mode, the @code{ALI} file is not generated if any
10552 illegalities are detected in the program. The use of @code{-gnatQ} forces
10553 generation of the @code{ALI} file. This file is marked as being in
10554 error, so it cannot be used for binding purposes, but it does contain
10555 reasonably complete cross-reference information, and thus may be useful
10556 for use by tools (e.g., semantic browsing tools or integrated development
10557 environments) that are driven from the @code{ALI} file. This switch
10558 implies @code{-gnatq}, since the semantic phase must be run to get a
10559 meaningful ALI file.
10561 When @code{-gnatQ} is used and the generated @code{ALI} file is marked as
10562 being in error, @code{gnatmake} will attempt to recompile the source when it
10563 finds such an @code{ALI} file, including with switch @code{-gnatc}.
10565 Note that @code{-gnatQ} has no effect if @code{-gnats} is specified,
10566 since ALI files are never generated if @code{-gnats} is set.
10569 @node Warning Message Control,Debugging and Assertion Control,Output and Error Message Control,Compiler Switches
10570 @anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{f2}@anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{ed}
10571 @subsection Warning Message Control
10574 @geindex Warning messages
10576 In addition to error messages, which correspond to illegalities as defined
10577 in the Ada Reference Manual, the compiler detects two kinds of warning
10580 First, the compiler considers some constructs suspicious and generates a
10581 warning message to alert you to a possible error. Second, if the
10582 compiler detects a situation that is sure to raise an exception at
10583 run time, it generates a warning message. The following shows an example
10584 of warning messages:
10587 e.adb:4:24: warning: creation of object may raise Storage_Error
10588 e.adb:10:17: warning: static value out of range
10589 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10592 GNAT considers a large number of situations as appropriate
10593 for the generation of warning messages. As always, warnings are not
10594 definite indications of errors. For example, if you do an out-of-range
10595 assignment with the deliberate intention of raising a
10596 @code{Constraint_Error} exception, then the warning that may be
10597 issued does not indicate an error. Some of the situations for which GNAT
10598 issues warnings (at least some of the time) are given in the following
10599 list. This list is not complete, and new warnings are often added to
10600 subsequent versions of GNAT. The list is intended to give a general idea
10601 of the kinds of warnings that are generated.
10607 Possible infinitely recursive calls
10610 Out-of-range values being assigned
10613 Possible order of elaboration problems
10616 Size not a multiple of alignment for a record type
10619 Assertions (pragma Assert) that are sure to fail
10625 Address clauses with possibly unaligned values, or where an attempt is
10626 made to overlay a smaller variable with a larger one.
10629 Fixed-point type declarations with a null range
10632 Direct_IO or Sequential_IO instantiated with a type that has access values
10635 Variables that are never assigned a value
10638 Variables that are referenced before being initialized
10641 Task entries with no corresponding @code{accept} statement
10644 Duplicate accepts for the same task entry in a @code{select}
10647 Objects that take too much storage
10650 Unchecked conversion between types of differing sizes
10653 Missing @code{return} statement along some execution path in a function
10656 Incorrect (unrecognized) pragmas
10659 Incorrect external names
10662 Allocation from empty storage pool
10665 Potentially blocking operation in protected type
10668 Suspicious parenthesization of expressions
10671 Mismatching bounds in an aggregate
10674 Attempt to return local value by reference
10677 Premature instantiation of a generic body
10680 Attempt to pack aliased components
10683 Out of bounds array subscripts
10686 Wrong length on string assignment
10689 Violations of style rules if style checking is enabled
10692 Unused `with' clauses
10695 @code{Bit_Order} usage that does not have any effect
10698 @code{Standard.Duration} used to resolve universal fixed expression
10701 Dereference of possibly null value
10704 Declaration that is likely to cause storage error
10707 Internal GNAT unit `with'ed by application unit
10710 Values known to be out of range at compile time
10713 Unreferenced or unmodified variables. Note that a special
10714 exemption applies to variables which contain any of the substrings
10715 @code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
10716 are considered likely to be intentionally used in a situation where
10717 otherwise a warning would be given, so warnings of this kind are
10718 always suppressed for such variables.
10721 Address overlays that could clobber memory
10724 Unexpected initialization when address clause present
10727 Bad alignment for address clause
10730 Useless type conversions
10733 Redundant assignment statements and other redundant constructs
10736 Useless exception handlers
10739 Accidental hiding of name by child unit
10742 Access before elaboration detected at compile time
10745 A range in a @code{for} loop that is known to be null or might be null
10748 The following section lists compiler switches that are available
10749 to control the handling of warning messages. It is also possible
10750 to exercise much finer control over what warnings are issued and
10751 suppressed using the GNAT pragma Warnings (see the description
10752 of the pragma in the @cite{GNAT_Reference_manual}).
10754 @geindex -gnatwa (gcc)
10759 @item @code{-gnatwa}
10761 `Activate most optional warnings.'
10763 This switch activates most optional warning messages. See the remaining list
10764 in this section for details on optional warning messages that can be
10765 individually controlled. The warnings that are not turned on by this
10772 @code{-gnatwd} (implicit dereferencing)
10775 @code{-gnatw.d} (tag warnings with -gnatw switch)
10778 @code{-gnatwh} (hiding)
10781 @code{-gnatw.h} (holes in record layouts)
10784 @code{-gnatw.j} (late primitives of tagged types)
10787 @code{-gnatw.k} (redefinition of names in standard)
10790 @code{-gnatwl} (elaboration warnings)
10793 @code{-gnatw.l} (inherited aspects)
10796 @code{-gnatw.n} (atomic synchronization)
10799 @code{-gnatwo} (address clause overlay)
10802 @code{-gnatw.o} (values set by out parameters ignored)
10805 @code{-gnatw.q} (questionable layout of record types)
10808 @code{-gnatw_q} (ignored equality)
10811 @code{-gnatw_r} (out-of-order record representation clauses)
10814 @code{-gnatw.s} (overridden size clause)
10817 @code{-gnatw_s} (ineffective predicate test)
10820 @code{-gnatwt} (tracking of deleted conditional code)
10823 @code{-gnatw.u} (unordered enumeration)
10826 @code{-gnatw.w} (use of Warnings Off)
10829 @code{-gnatw.y} (reasons for package needing body)
10832 All other optional warnings are turned on.
10835 @geindex -gnatwA (gcc)
10840 @item @code{-gnatwA}
10842 `Suppress all optional errors.'
10844 This switch suppresses all optional warning messages, see remaining list
10845 in this section for details on optional warning messages that can be
10846 individually controlled. Note that unlike switch @code{-gnatws}, the
10847 use of switch @code{-gnatwA} does not suppress warnings that are
10848 normally given unconditionally and cannot be individually controlled
10849 (for example, the warning about a missing exit path in a function).
10850 Also, again unlike switch @code{-gnatws}, warnings suppressed by
10851 the use of switch @code{-gnatwA} can be individually turned back
10852 on. For example the use of switch @code{-gnatwA} followed by
10853 switch @code{-gnatwd} will suppress all optional warnings except
10854 the warnings for implicit dereferencing.
10857 @geindex -gnatw.a (gcc)
10862 @item @code{-gnatw.a}
10864 `Activate warnings on failing assertions.'
10866 @geindex Assert failures
10868 This switch activates warnings for assertions where the compiler can tell at
10869 compile time that the assertion will fail. Note that this warning is given
10870 even if assertions are disabled. The default is that such warnings are
10874 @geindex -gnatw.A (gcc)
10879 @item @code{-gnatw.A}
10881 `Suppress warnings on failing assertions.'
10883 @geindex Assert failures
10885 This switch suppresses warnings for assertions where the compiler can tell at
10886 compile time that the assertion will fail.
10894 @item @code{-gnatw_a}
10896 `Activate warnings on anonymous allocators.'
10898 @geindex Anonymous allocators
10900 This switch activates warnings for allocators of anonymous access types,
10901 which can involve run-time accessibility checks and lead to unexpected
10902 accessibility violations. For more details on the rules involved, see
10911 @item @code{-gnatw_A}
10913 `Suppress warnings on anonymous allocators.'
10915 @geindex Anonymous allocators
10917 This switch suppresses warnings for anonymous access type allocators.
10920 @geindex -gnatwb (gcc)
10925 @item @code{-gnatwb}
10927 `Activate warnings on bad fixed values.'
10929 @geindex Bad fixed values
10931 @geindex Fixed-point Small value
10933 @geindex Small value
10935 This switch activates warnings for static fixed-point expressions whose
10936 value is not an exact multiple of Small. Such values are implementation
10937 dependent, since an implementation is free to choose either of the multiples
10938 that surround the value. GNAT always chooses the closer one, but this is not
10939 required behavior, and it is better to specify a value that is an exact
10940 multiple, ensuring predictable execution. The default is that such warnings
10944 @geindex -gnatwB (gcc)
10949 @item @code{-gnatwB}
10951 `Suppress warnings on bad fixed values.'
10953 This switch suppresses warnings for static fixed-point expressions whose
10954 value is not an exact multiple of Small.
10957 @geindex -gnatw.b (gcc)
10962 @item @code{-gnatw.b}
10964 `Activate warnings on biased representation.'
10966 @geindex Biased representation
10968 This switch activates warnings when a size clause, value size clause, component
10969 clause, or component size clause forces the use of biased representation for an
10970 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
10971 to represent 10/11). The default is that such warnings are generated.
10974 @geindex -gnatwB (gcc)
10979 @item @code{-gnatw.B}
10981 `Suppress warnings on biased representation.'
10983 This switch suppresses warnings for representation clauses that force the use
10984 of biased representation.
10987 @geindex -gnatwc (gcc)
10992 @item @code{-gnatwc}
10994 `Activate warnings on conditionals.'
10996 @geindex Conditionals
10999 This switch activates warnings for conditional expressions used in
11000 tests that are known to be True or False at compile time. The default
11001 is that such warnings are not generated.
11002 Note that this warning does
11003 not get issued for the use of boolean constants whose
11004 values are known at compile time, since this is a standard technique
11005 for conditional compilation in Ada, and this would generate too many
11006 false positive warnings.
11008 This warning option also activates a special test for comparisons using
11009 the operators ‘>=’ and’ <=’.
11010 If the compiler can tell that only the equality condition is possible,
11011 then it will warn that the ‘>’ or ‘<’ part of the test
11012 is useless and that the operator could be replaced by ‘=’.
11013 An example would be comparing a @code{Natural} variable <= 0.
11015 This warning option also generates warnings if
11016 one or both tests is optimized away in a membership test for integer
11017 values if the result can be determined at compile time. Range tests on
11018 enumeration types are not included, since it is common for such tests
11019 to include an end point.
11021 This warning can also be turned on using @code{-gnatwa}.
11024 @geindex -gnatwC (gcc)
11029 @item @code{-gnatwC}
11031 `Suppress warnings on conditionals.'
11033 This switch suppresses warnings for conditional expressions used in
11034 tests that are known to be True or False at compile time.
11037 @geindex -gnatw.c (gcc)
11042 @item @code{-gnatw.c}
11044 `Activate warnings on missing component clauses.'
11046 @geindex Component clause
11049 This switch activates warnings for record components where a record
11050 representation clause is present and has component clauses for the
11051 majority, but not all, of the components. A warning is given for each
11052 component for which no component clause is present.
11055 @geindex -gnatw.C (gcc)
11060 @item @code{-gnatw.C}
11062 `Suppress warnings on missing component clauses.'
11064 This switch suppresses warnings for record components that are
11065 missing a component clause in the situation described above.
11068 @geindex -gnatw_c (gcc)
11073 @item @code{-gnatw_c}
11075 `Activate warnings on unknown condition in Compile_Time_Warning.'
11077 @geindex Compile_Time_Warning
11079 @geindex Compile_Time_Error
11081 This switch activates warnings on a pragma Compile_Time_Warning
11082 or Compile_Time_Error whose condition has a value that is not
11083 known at compile time.
11084 The default is that such warnings are generated.
11087 @geindex -gnatw_C (gcc)
11092 @item @code{-gnatw_C}
11094 `Suppress warnings on unknown condition in Compile_Time_Warning.'
11096 This switch suppresses warnings on a pragma Compile_Time_Warning
11097 or Compile_Time_Error whose condition has a value that is not
11098 known at compile time.
11101 @geindex -gnatwd (gcc)
11106 @item @code{-gnatwd}
11108 `Activate warnings on implicit dereferencing.'
11110 If this switch is set, then the use of a prefix of an access type
11111 in an indexed component, slice, or selected component without an
11112 explicit @code{.all} will generate a warning. With this warning
11113 enabled, access checks occur only at points where an explicit
11114 @code{.all} appears in the source code (assuming no warnings are
11115 generated as a result of this switch). The default is that such
11116 warnings are not generated.
11119 @geindex -gnatwD (gcc)
11124 @item @code{-gnatwD}
11126 `Suppress warnings on implicit dereferencing.'
11128 @geindex Implicit dereferencing
11130 @geindex Dereferencing
11133 This switch suppresses warnings for implicit dereferences in
11134 indexed components, slices, and selected components.
11137 @geindex -gnatw.d (gcc)
11142 @item @code{-gnatw.d}
11144 `Activate tagging of warning and info messages.'
11146 If this switch is set, then warning messages are tagged, with one of the
11156 Used to tag warnings controlled by the switch @code{-gnatwx} where x
11161 Used to tag warnings controlled by the switch @code{-gnatw.x} where x
11166 Used to tag elaboration information (info) messages generated when the
11167 static model of elaboration is used and the @code{-gnatel} switch is set.
11170 `[restriction warning]'
11171 Used to tag warning messages for restriction violations, activated by use
11172 of the pragma @code{Restriction_Warnings}.
11175 `[warning-as-error]'
11176 Used to tag warning messages that have been converted to error messages by
11177 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
11178 the string “error: ” rather than “warning: “.
11181 `[enabled by default]'
11182 Used to tag all other warnings that are always given by default, unless
11183 warnings are completely suppressed using pragma `Warnings(Off)' or
11184 the switch @code{-gnatws}.
11189 @geindex -gnatw.d (gcc)
11194 @item @code{-gnatw.D}
11196 `Deactivate tagging of warning and info messages messages.'
11198 If this switch is set, then warning messages return to the default
11199 mode in which warnings and info messages are not tagged as described above for
11203 @geindex -gnatwe (gcc)
11206 @geindex treat as error
11211 @item @code{-gnatwe}
11213 `Treat warnings and style checks as errors.'
11215 This switch causes warning messages and style check messages to be
11217 The warning string still appears, but the warning messages are counted
11218 as errors, and prevent the generation of an object file. Note that this
11219 is the only -gnatw switch that affects the handling of style check messages.
11220 Note also that this switch has no effect on info (information) messages, which
11221 are not treated as errors if this switch is present.
11224 @geindex -gnatw.e (gcc)
11229 @item @code{-gnatw.e}
11231 `Activate every optional warning.'
11234 @geindex activate every optional warning
11236 This switch activates all optional warnings, including those which
11237 are not activated by @code{-gnatwa}. The use of this switch is not
11238 recommended for normal use. If you turn this switch on, it is almost
11239 certain that you will get large numbers of useless warnings. The
11240 warnings that are excluded from @code{-gnatwa} are typically highly
11241 specialized warnings that are suitable for use only in code that has
11242 been specifically designed according to specialized coding rules.
11245 @geindex -gnatwE (gcc)
11248 @geindex treat as error
11253 @item @code{-gnatwE}
11255 `Treat all run-time exception warnings as errors.'
11257 This switch causes warning messages regarding errors that will be raised
11258 during run-time execution to be treated as errors.
11261 @geindex -gnatwf (gcc)
11266 @item @code{-gnatwf}
11268 `Activate warnings on unreferenced formals.'
11271 @geindex unreferenced
11273 This switch causes a warning to be generated if a formal parameter
11274 is not referenced in the body of the subprogram. This warning can
11275 also be turned on using @code{-gnatwu}. The
11276 default is that these warnings are not generated.
11279 @geindex -gnatwF (gcc)
11284 @item @code{-gnatwF}
11286 `Suppress warnings on unreferenced formals.'
11288 This switch suppresses warnings for unreferenced formal
11289 parameters. Note that the
11290 combination @code{-gnatwu} followed by @code{-gnatwF} has the
11291 effect of warning on unreferenced entities other than subprogram
11295 @geindex -gnatwg (gcc)
11300 @item @code{-gnatwg}
11302 `Activate warnings on unrecognized pragmas.'
11305 @geindex unrecognized
11307 This switch causes a warning to be generated if an unrecognized
11308 pragma is encountered. Apart from issuing this warning, the
11309 pragma is ignored and has no effect. The default
11310 is that such warnings are issued (satisfying the Ada Reference
11311 Manual requirement that such warnings appear).
11314 @geindex -gnatwG (gcc)
11319 @item @code{-gnatwG}
11321 `Suppress warnings on unrecognized pragmas.'
11323 This switch suppresses warnings for unrecognized pragmas.
11326 @geindex -gnatw.g (gcc)
11331 @item @code{-gnatw.g}
11333 `Warnings used for GNAT sources.'
11335 This switch sets the warning categories that are used by the standard
11336 GNAT style. Currently this is equivalent to
11337 @code{-gnatwAao.q.s.CI.V.X.Z}
11338 but more warnings may be added in the future without advanced notice.
11341 @geindex -gnatwh (gcc)
11346 @item @code{-gnatwh}
11348 `Activate warnings on hiding.'
11350 @geindex Hiding of Declarations
11352 This switch activates warnings on hiding declarations that are considered
11353 potentially confusing. Not all cases of hiding cause warnings; for example an
11354 overriding declaration hides an implicit declaration, which is just normal
11355 code. The default is that warnings on hiding are not generated.
11358 @geindex -gnatwH (gcc)
11363 @item @code{-gnatwH}
11365 `Suppress warnings on hiding.'
11367 This switch suppresses warnings on hiding declarations.
11370 @geindex -gnatw.h (gcc)
11375 @item @code{-gnatw.h}
11377 `Activate warnings on holes/gaps in records.'
11379 @geindex Record Representation (gaps)
11381 This switch activates warnings on component clauses in record
11382 representation clauses that leave holes (gaps) in the record layout.
11383 If a record representation clause does not specify a location for
11384 every component of the record type, then the warnings generated (or not
11385 generated) are unspecified. For example, there may be gaps for which
11386 either no warning is generated or a warning is generated that
11387 incorrectly describes the location of the gap. This undesirable situation
11388 can sometimes be avoided by adding (and specifying the location for) unused
11392 @geindex -gnatw.H (gcc)
11397 @item @code{-gnatw.H}
11399 `Suppress warnings on holes/gaps in records.'
11401 This switch suppresses warnings on component clauses in record
11402 representation clauses that leave holes (haps) in the record layout.
11405 @geindex -gnatwi (gcc)
11410 @item @code{-gnatwi}
11412 `Activate warnings on implementation units.'
11414 This switch activates warnings for a `with' of an internal GNAT
11415 implementation unit, defined as any unit from the @code{Ada},
11416 @code{Interfaces}, @code{GNAT},
11418 hierarchies that is not
11419 documented in either the Ada Reference Manual or the GNAT
11420 Programmer’s Reference Manual. Such units are intended only
11421 for internal implementation purposes and should not be `with'ed
11422 by user programs. The default is that such warnings are generated
11425 @geindex -gnatwI (gcc)
11430 @item @code{-gnatwI}
11432 `Disable warnings on implementation units.'
11434 This switch disables warnings for a `with' of an internal GNAT
11435 implementation unit.
11438 @geindex -gnatw.i (gcc)
11443 @item @code{-gnatw.i}
11445 `Activate warnings on overlapping actuals.'
11447 This switch enables a warning on statically detectable overlapping actuals in
11448 a subprogram call, when one of the actuals is an in-out parameter, and the
11449 types of the actuals are not by-copy types. This warning is off by default.
11452 @geindex -gnatw.I (gcc)
11457 @item @code{-gnatw.I}
11459 `Disable warnings on overlapping actuals.'
11461 This switch disables warnings on overlapping actuals in a call.
11464 @geindex -gnatwj (gcc)
11469 @item @code{-gnatwj}
11471 `Activate warnings on obsolescent features (Annex J).'
11474 @geindex obsolescent
11476 @geindex Obsolescent features
11478 If this warning option is activated, then warnings are generated for
11479 calls to subprograms marked with @code{pragma Obsolescent} and
11480 for use of features in Annex J of the Ada Reference Manual. In the
11481 case of Annex J, not all features are flagged. In particular, uses of package
11482 @code{ASCII} are not flagged, since these are very common and
11483 would generate many annoying positive warnings. The default is that
11484 such warnings are not generated.
11486 In addition to the above cases, warnings are also generated for
11487 GNAT features that have been provided in past versions but which
11488 have been superseded (typically by features in the new Ada standard).
11489 For example, @code{pragma Ravenscar} will be flagged since its
11490 function is replaced by @code{pragma Profile(Ravenscar)}, and
11491 @code{pragma Interface_Name} will be flagged since its function
11492 is replaced by @code{pragma Import}.
11494 Note that this warning option functions differently from the
11495 restriction @code{No_Obsolescent_Features} in two respects.
11496 First, the restriction applies only to annex J features.
11497 Second, the restriction does flag uses of package @code{ASCII}.
11500 @geindex -gnatwJ (gcc)
11505 @item @code{-gnatwJ}
11507 `Suppress warnings on obsolescent features (Annex J).'
11509 This switch disables warnings on use of obsolescent features.
11512 @geindex -gnatw.j (gcc)
11517 @item @code{-gnatw.j}
11519 `Activate warnings on late declarations of tagged type primitives.'
11521 This switch activates warnings on visible primitives added to a
11522 tagged type after deriving a private extension from it.
11525 @geindex -gnatw.J (gcc)
11530 @item @code{-gnatw.J}
11532 `Suppress warnings on late declarations of tagged type primitives.'
11534 This switch suppresses warnings on visible primitives added to a
11535 tagged type after deriving a private extension from it.
11538 @geindex -gnatwk (gcc)
11543 @item @code{-gnatwk}
11545 `Activate warnings on variables that could be constants.'
11547 This switch activates warnings for variables that are initialized but
11548 never modified, and then could be declared constants. The default is that
11549 such warnings are not given.
11552 @geindex -gnatwK (gcc)
11557 @item @code{-gnatwK}
11559 `Suppress warnings on variables that could be constants.'
11561 This switch disables warnings on variables that could be declared constants.
11564 @geindex -gnatw.k (gcc)
11569 @item @code{-gnatw.k}
11571 `Activate warnings on redefinition of names in standard.'
11573 This switch activates warnings for declarations that declare a name that
11574 is defined in package Standard. Such declarations can be confusing,
11575 especially since the names in package Standard continue to be directly
11576 visible, meaning that use visibility on such redeclared names does not
11577 work as expected. Names of discriminants and components in records are
11578 not included in this check.
11581 @geindex -gnatwK (gcc)
11586 @item @code{-gnatw.K}
11588 `Suppress warnings on redefinition of names in standard.'
11590 This switch disables warnings for declarations that declare a name that
11591 is defined in package Standard.
11594 @geindex -gnatwl (gcc)
11599 @item @code{-gnatwl}
11601 `Activate warnings for elaboration pragmas.'
11603 @geindex Elaboration
11606 This switch activates warnings for possible elaboration problems,
11607 including suspicious use
11608 of @code{Elaborate} pragmas, when using the static elaboration model, and
11609 possible situations that may raise @code{Program_Error} when using the
11610 dynamic elaboration model.
11611 See the section in this guide on elaboration checking for further details.
11612 The default is that such warnings
11616 @geindex -gnatwL (gcc)
11621 @item @code{-gnatwL}
11623 `Suppress warnings for elaboration pragmas.'
11625 This switch suppresses warnings for possible elaboration problems.
11628 @geindex -gnatw.l (gcc)
11633 @item @code{-gnatw.l}
11635 `List inherited aspects.'
11637 This switch causes the compiler to list inherited invariants,
11638 preconditions, and postconditions from Type_Invariant’Class, Invariant’Class,
11639 Pre’Class, and Post’Class aspects. Also list inherited subtype predicates.
11642 @geindex -gnatw.L (gcc)
11647 @item @code{-gnatw.L}
11649 `Suppress listing of inherited aspects.'
11651 This switch suppresses listing of inherited aspects.
11654 @geindex -gnatwm (gcc)
11659 @item @code{-gnatwm}
11661 `Activate warnings on modified but unreferenced variables.'
11663 This switch activates warnings for variables that are assigned (using
11664 an initialization value or with one or more assignment statements) but
11665 whose value is never read. The warning is suppressed for volatile
11666 variables and also for variables that are renamings of other variables
11667 or for which an address clause is given.
11668 The default is that these warnings are not given.
11671 @geindex -gnatwM (gcc)
11676 @item @code{-gnatwM}
11678 `Disable warnings on modified but unreferenced variables.'
11680 This switch disables warnings for variables that are assigned or
11681 initialized, but never read.
11684 @geindex -gnatw.m (gcc)
11689 @item @code{-gnatw.m}
11691 `Activate warnings on suspicious modulus values.'
11693 This switch activates warnings for modulus values that seem suspicious.
11694 The cases caught are where the size is the same as the modulus (e.g.
11695 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11696 with no size clause. The guess in both cases is that 2**x was intended
11697 rather than x. In addition expressions of the form 2*x for small x
11698 generate a warning (the almost certainly accurate guess being that
11699 2**x was intended). This switch also activates warnings for negative
11700 literal values of a modular type, which are interpreted as large positive
11701 integers after wrap-around. The default is that these warnings are given.
11704 @geindex -gnatw.M (gcc)
11709 @item @code{-gnatw.M}
11711 `Disable warnings on suspicious modulus values.'
11713 This switch disables warnings for suspicious modulus values.
11716 @geindex -gnatwn (gcc)
11721 @item @code{-gnatwn}
11723 `Set normal warnings mode.'
11725 This switch sets normal warning mode, in which enabled warnings are
11726 issued and treated as warnings rather than errors. This is the default
11727 mode. the switch @code{-gnatwn} can be used to cancel the effect of
11728 an explicit @code{-gnatws} or
11729 @code{-gnatwe}. It also cancels the effect of the
11730 implicit @code{-gnatwe} that is activated by the
11731 use of @code{-gnatg}.
11734 @geindex -gnatw.n (gcc)
11736 @geindex Atomic Synchronization
11742 @item @code{-gnatw.n}
11744 `Activate warnings on atomic synchronization.'
11746 This switch actives warnings when an access to an atomic variable
11747 requires the generation of atomic synchronization code. These
11748 warnings are off by default.
11751 @geindex -gnatw.N (gcc)
11756 @item @code{-gnatw.N}
11758 `Suppress warnings on atomic synchronization.'
11760 @geindex Atomic Synchronization
11763 This switch suppresses warnings when an access to an atomic variable
11764 requires the generation of atomic synchronization code.
11767 @geindex -gnatwo (gcc)
11769 @geindex Address Clauses
11775 @item @code{-gnatwo}
11777 `Activate warnings on address clause overlays.'
11779 This switch activates warnings for possibly unintended initialization
11780 effects of defining address clauses that cause one variable to overlap
11781 another. The default is that such warnings are generated.
11784 @geindex -gnatwO (gcc)
11789 @item @code{-gnatwO}
11791 `Suppress warnings on address clause overlays.'
11793 This switch suppresses warnings on possibly unintended initialization
11794 effects of defining address clauses that cause one variable to overlap
11798 @geindex -gnatw.o (gcc)
11803 @item @code{-gnatw.o}
11805 `Activate warnings on modified but unreferenced out parameters.'
11807 This switch activates warnings for variables that are modified by using
11808 them as actuals for a call to a procedure with an out mode formal, where
11809 the resulting assigned value is never read. It is applicable in the case
11810 where there is more than one out mode formal. If there is only one out
11811 mode formal, the warning is issued by default (controlled by -gnatwu).
11812 The warning is suppressed for volatile
11813 variables and also for variables that are renamings of other variables
11814 or for which an address clause is given.
11815 The default is that these warnings are not given.
11818 @geindex -gnatw.O (gcc)
11823 @item @code{-gnatw.O}
11825 `Disable warnings on modified but unreferenced out parameters.'
11827 This switch suppresses warnings for variables that are modified by using
11828 them as actuals for a call to a procedure with an out mode formal, where
11829 the resulting assigned value is never read.
11832 @geindex -gnatwp (gcc)
11840 @item @code{-gnatwp}
11842 `Activate warnings on ineffective pragma Inlines.'
11844 This switch activates warnings for failure of front end inlining
11845 (activated by @code{-gnatN}) to inline a particular call. There are
11846 many reasons for not being able to inline a call, including most
11847 commonly that the call is too complex to inline. The default is
11848 that such warnings are not given.
11849 Warnings on ineffective inlining by the gcc back-end can be activated
11850 separately, using the gcc switch -Winline.
11853 @geindex -gnatwP (gcc)
11858 @item @code{-gnatwP}
11860 `Suppress warnings on ineffective pragma Inlines.'
11862 This switch suppresses warnings on ineffective pragma Inlines. If the
11863 inlining mechanism cannot inline a call, it will simply ignore the
11867 @geindex -gnatw.p (gcc)
11869 @geindex Parameter order
11875 @item @code{-gnatw.p}
11877 `Activate warnings on parameter ordering.'
11879 This switch activates warnings for cases of suspicious parameter
11880 ordering when the list of arguments are all simple identifiers that
11881 match the names of the formals, but are in a different order. The
11882 warning is suppressed if any use of named parameter notation is used,
11883 so this is the appropriate way to suppress a false positive (and
11884 serves to emphasize that the “misordering” is deliberate). The
11885 default is that such warnings are not given.
11888 @geindex -gnatw.P (gcc)
11893 @item @code{-gnatw.P}
11895 `Suppress warnings on parameter ordering.'
11897 This switch suppresses warnings on cases of suspicious parameter
11901 @geindex -gnatw_p (gcc)
11906 @item @code{-gnatw_p}
11908 `Activate warnings for pedantic checks.'
11910 This switch activates warnings for the failure of certain pedantic checks.
11911 The only case currently supported is a check that the subtype_marks given
11912 for corresponding formal parameter and function results in a subprogram
11913 declaration and its body denote the same subtype declaration. The default
11914 is that such warnings are not given.
11917 @geindex -gnatw_P (gcc)
11922 @item @code{-gnatw_P}
11924 `Suppress warnings for pedantic checks.'
11926 This switch suppresses warnings on violations of pedantic checks.
11929 @geindex -gnatwq (gcc)
11931 @geindex Parentheses
11937 @item @code{-gnatwq}
11939 `Activate warnings on questionable missing parentheses.'
11941 This switch activates warnings for cases where parentheses are not used and
11942 the result is potential ambiguity from a readers point of view. For example
11943 (not a > b) when a and b are modular means ((not a) > b) and very likely the
11944 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
11945 quite likely ((-x) mod 5) was intended. In such situations it seems best to
11946 follow the rule of always parenthesizing to make the association clear, and
11947 this warning switch warns if such parentheses are not present. The default
11948 is that these warnings are given.
11951 @geindex -gnatwQ (gcc)
11956 @item @code{-gnatwQ}
11958 `Suppress warnings on questionable missing parentheses.'
11960 This switch suppresses warnings for cases where the association is not
11961 clear and the use of parentheses is preferred.
11964 @geindex -gnatw.q (gcc)
11972 @item @code{-gnatw.q}
11974 `Activate warnings on questionable layout of record types.'
11976 This switch activates warnings for cases where the default layout of
11977 a record type, that is to say the layout of its components in textual
11978 order of the source code, would very likely cause inefficiencies in
11979 the code generated by the compiler, both in terms of space and speed
11980 during execution. One warning is issued for each problematic component
11981 without representation clause in the nonvariant part and then in each
11982 variant recursively, if any.
11984 The purpose of these warnings is neither to prescribe an optimal layout
11985 nor to force the use of representation clauses, but rather to get rid of
11986 the most blatant inefficiencies in the layout. Therefore, the default
11987 layout is matched against the following synthetic ordered layout and
11988 the deviations are flagged on a component-by-component basis:
11994 first all components or groups of components whose length is fixed
11995 and a multiple of the storage unit,
11998 then the remaining components whose length is fixed and not a multiple
11999 of the storage unit,
12002 then the remaining components whose length doesn’t depend on discriminants
12003 (that is to say, with variable but uniform length for all objects),
12006 then all components whose length depends on discriminants,
12009 finally the variant part (if any),
12012 for the nonvariant part and for each variant recursively, if any.
12014 The exact wording of the warning depends on whether the compiler is allowed
12015 to reorder the components in the record type or precluded from doing it by
12016 means of pragma @code{No_Component_Reordering}.
12018 The default is that these warnings are not given.
12021 @geindex -gnatw.Q (gcc)
12026 @item @code{-gnatw.Q}
12028 `Suppress warnings on questionable layout of record types.'
12030 This switch suppresses warnings for cases where the default layout of
12031 a record type would very likely cause inefficiencies.
12034 @geindex -gnatw_q (gcc)
12039 @item @code{-gnatw_q}
12041 `Activate warnings for ignored equality operators.'
12043 This switch activates warnings for a user-defined “=” function that does
12044 not compose (i.e. is ignored for a predefined “=” for a composite type
12045 containing a component whose type has the user-defined “=” as
12046 primitive). Note that the user-defined “=” must be a primitive operator
12047 in order to trigger the warning.
12048 See RM-4.5.2(14/3-15/5, 21, 24/3, 32.1/1)
12049 for the exact Ada rules on composability of “=”.
12051 The default is that these warnings are not given.
12054 @geindex -gnatw_Q (gcc)
12059 @item @code{-gnatw_Q}
12061 `Suppress warnings for ignored equality operators.'
12064 @geindex -gnatwr (gcc)
12069 @item @code{-gnatwr}
12071 `Activate warnings on redundant constructs.'
12073 This switch activates warnings for redundant constructs. The following
12074 is the current list of constructs regarded as redundant:
12080 Assignment of an item to itself.
12083 Type conversion that converts an expression to its own type.
12086 Use of the attribute @code{Base} where @code{typ'Base} is the same
12090 Use of pragma @code{Pack} when all components are placed by a record
12091 representation clause.
12094 Exception handler containing only a reraise statement (raise with no
12095 operand) which has no effect.
12098 Use of the operator abs on an operand that is known at compile time
12102 Comparison of an object or (unary or binary) operation of boolean type to
12103 an explicit True value.
12106 Import of parent package.
12109 The default is that warnings for redundant constructs are not given.
12112 @geindex -gnatwR (gcc)
12117 @item @code{-gnatwR}
12119 `Suppress warnings on redundant constructs.'
12121 This switch suppresses warnings for redundant constructs.
12124 @geindex -gnatw.r (gcc)
12129 @item @code{-gnatw.r}
12131 `Activate warnings for object renaming function.'
12133 This switch activates warnings for an object renaming that renames a
12134 function call, which is equivalent to a constant declaration (as
12135 opposed to renaming the function itself). The default is that these
12136 warnings are given.
12139 @geindex -gnatw.R (gcc)
12144 @item @code{-gnatw.R}
12146 `Suppress warnings for object renaming function.'
12148 This switch suppresses warnings for object renaming function.
12151 @geindex -gnatw_r (gcc)
12156 @item @code{-gnatw_r}
12158 `Activate warnings for out-of-order record representation clauses.'
12160 This switch activates warnings for record representation clauses,
12161 if the order of component declarations, component clauses,
12162 and bit-level layout do not all agree.
12163 The default is that these warnings are not given.
12166 @geindex -gnatw_R (gcc)
12171 @item @code{-gnatw_R}
12173 `Suppress warnings for out-of-order record representation clauses.'
12176 @geindex -gnatws (gcc)
12181 @item @code{-gnatws}
12183 `Suppress all warnings.'
12185 This switch completely suppresses the
12186 output of all warning messages from the GNAT front end, including
12187 both warnings that can be controlled by switches described in this
12188 section, and those that are normally given unconditionally. The
12189 effect of this suppress action can only be cancelled by a subsequent
12190 use of the switch @code{-gnatwn}.
12192 Note that switch @code{-gnatws} does not suppress
12193 warnings from the @code{gcc} back end.
12194 To suppress these back end warnings as well, use the switch @code{-w}
12195 in addition to @code{-gnatws}. Also this switch has no effect on the
12196 handling of style check messages.
12199 @geindex -gnatw.s (gcc)
12201 @geindex Record Representation (component sizes)
12206 @item @code{-gnatw.s}
12208 `Activate warnings on overridden size clauses.'
12210 This switch activates warnings on component clauses in record
12211 representation clauses where the length given overrides that
12212 specified by an explicit size clause for the component type. A
12213 warning is similarly given in the array case if a specified
12214 component size overrides an explicit size clause for the array
12218 @geindex -gnatw.S (gcc)
12223 @item @code{-gnatw.S}
12225 `Suppress warnings on overridden size clauses.'
12227 This switch suppresses warnings on component clauses in record
12228 representation clauses that override size clauses, and similar
12229 warnings when an array component size overrides a size clause.
12232 @geindex -gnatw_s (gcc)
12239 @item @code{-gnatw_s}
12241 `Activate warnings on ineffective predicate tests.'
12243 This switch activates warnings on Static_Predicate aspect
12244 specifications that test for values that do not belong to
12245 the parent subtype. Not all such ineffective tests are detected.
12248 @geindex -gnatw_S (gcc)
12253 @item @code{-gnatw_S}
12255 `Suppress warnings on ineffective predicate tests.'
12257 This switch suppresses warnings on Static_Predicate aspect
12258 specifications that test for values that do not belong to
12259 the parent subtype.
12262 @geindex -gnatwt (gcc)
12264 @geindex Deactivated code
12267 @geindex Deleted code
12273 @item @code{-gnatwt}
12275 `Activate warnings for tracking of deleted conditional code.'
12277 This switch activates warnings for tracking of code in conditionals (IF and
12278 CASE statements) that is detected to be dead code which cannot be executed, and
12279 which is removed by the front end. This warning is off by default. This may be
12280 useful for detecting deactivated code in certified applications.
12283 @geindex -gnatwT (gcc)
12288 @item @code{-gnatwT}
12290 `Suppress warnings for tracking of deleted conditional code.'
12292 This switch suppresses warnings for tracking of deleted conditional code.
12295 @geindex -gnatw.t (gcc)
12300 @item @code{-gnatw.t}
12302 `Activate warnings on suspicious contracts.'
12304 This switch activates warnings on suspicious contracts. This includes
12305 warnings on suspicious postconditions (whether a pragma @code{Postcondition} or a
12306 @code{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
12307 @code{Contract_Cases}). A function postcondition or contract case is suspicious
12308 when no postcondition or contract case for this function mentions the result
12309 of the function. A procedure postcondition or contract case is suspicious
12310 when it only refers to the pre-state of the procedure, because in that case
12311 it should rather be expressed as a precondition. This switch also controls
12312 warnings on suspicious cases of expressions typically found in contracts like
12313 quantified expressions and uses of Update attribute. The default is that such
12314 warnings are generated.
12317 @geindex -gnatw.T (gcc)
12322 @item @code{-gnatw.T}
12324 `Suppress warnings on suspicious contracts.'
12326 This switch suppresses warnings on suspicious contracts.
12329 @geindex -gnatwu (gcc)
12334 @item @code{-gnatwu}
12336 `Activate warnings on unused entities.'
12338 This switch activates warnings to be generated for entities that
12339 are declared but not referenced, and for units that are `with'ed
12341 referenced. In the case of packages, a warning is also generated if
12342 no entities in the package are referenced. This means that if a with’ed
12343 package is referenced but the only references are in @code{use}
12344 clauses or @code{renames}
12345 declarations, a warning is still generated. A warning is also generated
12346 for a generic package that is `with'ed but never instantiated.
12347 In the case where a package or subprogram body is compiled, and there
12348 is a `with' on the corresponding spec
12349 that is only referenced in the body,
12350 a warning is also generated, noting that the
12351 `with' can be moved to the body. The default is that
12352 such warnings are not generated.
12353 This switch also activates warnings on unreferenced formals
12354 (it includes the effect of @code{-gnatwf}).
12357 @geindex -gnatwU (gcc)
12362 @item @code{-gnatwU}
12364 `Suppress warnings on unused entities.'
12366 This switch suppresses warnings for unused entities and packages.
12367 It also turns off warnings on unreferenced formals (and thus includes
12368 the effect of @code{-gnatwF}).
12371 @geindex -gnatw.u (gcc)
12376 @item @code{-gnatw.u}
12378 `Activate warnings on unordered enumeration types.'
12380 This switch causes enumeration types to be considered as conceptually
12381 unordered, unless an explicit pragma @code{Ordered} is given for the type.
12382 The effect is to generate warnings in clients that use explicit comparisons
12383 or subranges, since these constructs both treat objects of the type as
12384 ordered. (A `client' is defined as a unit that is other than the unit in
12385 which the type is declared, or its body or subunits.) Please refer to
12386 the description of pragma @code{Ordered} in the
12387 @cite{GNAT Reference Manual} for further details.
12388 The default is that such warnings are not generated.
12391 @geindex -gnatw.U (gcc)
12396 @item @code{-gnatw.U}
12398 `Deactivate warnings on unordered enumeration types.'
12400 This switch causes all enumeration types to be considered as ordered, so
12401 that no warnings are given for comparisons or subranges for any type.
12404 @geindex -gnatwv (gcc)
12406 @geindex Unassigned variable warnings
12411 @item @code{-gnatwv}
12413 `Activate warnings on unassigned variables.'
12415 This switch activates warnings for access to variables which
12416 may not be properly initialized. The default is that
12417 such warnings are generated. This switch will also be emitted when
12418 initializing an array or record object via the following aggregate:
12421 Array_Or_Record : XXX := (others => <>);
12424 unless the relevant type fully initializes all components.
12427 @geindex -gnatwV (gcc)
12432 @item @code{-gnatwV}
12434 `Suppress warnings on unassigned variables.'
12436 This switch suppresses warnings for access to variables which
12437 may not be properly initialized.
12440 @geindex -gnatw.v (gcc)
12442 @geindex bit order warnings
12447 @item @code{-gnatw.v}
12449 `Activate info messages for non-default bit order.'
12451 This switch activates messages (labeled “info”, they are not warnings,
12452 just informational messages) about the effects of non-default bit-order
12453 on records to which a component clause is applied. The effect of specifying
12454 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
12455 these messages, which are given by default, are useful in understanding the
12456 exact consequences of using this feature.
12459 @geindex -gnatw.V (gcc)
12464 @item @code{-gnatw.V}
12466 `Suppress info messages for non-default bit order.'
12468 This switch suppresses information messages for the effects of specifying
12469 non-default bit order on record components with component clauses.
12472 @geindex -gnatww (gcc)
12474 @geindex String indexing warnings
12479 @item @code{-gnatww}
12481 `Activate warnings on wrong low bound assumption.'
12483 This switch activates warnings for indexing an unconstrained string parameter
12484 with a literal or S’Length. This is a case where the code is assuming that the
12485 low bound is one, which is in general not true (for example when a slice is
12486 passed). The default is that such warnings are generated.
12489 @geindex -gnatwW (gcc)
12494 @item @code{-gnatwW}
12496 `Suppress warnings on wrong low bound assumption.'
12498 This switch suppresses warnings for indexing an unconstrained string parameter
12499 with a literal or S’Length. Note that this warning can also be suppressed
12500 in a particular case by adding an assertion that the lower bound is 1,
12501 as shown in the following example:
12504 procedure K (S : String) is
12505 pragma Assert (S'First = 1);
12510 @geindex -gnatw.w (gcc)
12512 @geindex Warnings Off control
12517 @item @code{-gnatw.w}
12519 `Activate warnings on Warnings Off pragmas.'
12521 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
12522 where either the pragma is entirely useless (because it suppresses no
12523 warnings), or it could be replaced by @code{pragma Unreferenced} or
12524 @code{pragma Unmodified}.
12525 Also activates warnings for the case of
12526 Warnings (Off, String), where either there is no matching
12527 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12528 The default is that these warnings are not given.
12531 @geindex -gnatw.W (gcc)
12536 @item @code{-gnatw.W}
12538 `Suppress warnings on unnecessary Warnings Off pragmas.'
12540 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
12543 @geindex -gnatwx (gcc)
12545 @geindex Export/Import pragma warnings
12550 @item @code{-gnatwx}
12552 `Activate warnings on Export/Import pragmas.'
12554 This switch activates warnings on Export/Import pragmas when
12555 the compiler detects a possible conflict between the Ada and
12556 foreign language calling sequences. For example, the use of
12557 default parameters in a convention C procedure is dubious
12558 because the C compiler cannot supply the proper default, so
12559 a warning is issued. The default is that such warnings are
12563 @geindex -gnatwX (gcc)
12568 @item @code{-gnatwX}
12570 `Suppress warnings on Export/Import pragmas.'
12572 This switch suppresses warnings on Export/Import pragmas.
12573 The sense of this is that you are telling the compiler that
12574 you know what you are doing in writing the pragma, and it
12575 should not complain at you.
12578 @geindex -gnatwm (gcc)
12583 @item @code{-gnatw.x}
12585 `Activate warnings for No_Exception_Propagation mode.'
12587 This switch activates warnings for exception usage when pragma Restrictions
12588 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
12589 explicit exception raises which are not covered by a local handler, and for
12590 exception handlers which do not cover a local raise. The default is that
12591 these warnings are given for units that contain exception handlers.
12593 @item @code{-gnatw.X}
12595 `Disable warnings for No_Exception_Propagation mode.'
12597 This switch disables warnings for exception usage when pragma Restrictions
12598 (No_Exception_Propagation) is in effect.
12601 @geindex -gnatwy (gcc)
12603 @geindex Ada compatibility issues warnings
12608 @item @code{-gnatwy}
12610 `Activate warnings for Ada compatibility issues.'
12612 For the most part, newer versions of Ada are upwards compatible
12613 with older versions. For example, Ada 2005 programs will almost
12614 always work when compiled as Ada 2012.
12615 However there are some exceptions (for example the fact that
12616 @code{some} is now a reserved word in Ada 2012). This
12617 switch activates several warnings to help in identifying
12618 and correcting such incompatibilities. The default is that
12619 these warnings are generated. Note that at one point Ada 2005
12620 was called Ada 0Y, hence the choice of character.
12623 @geindex -gnatwY (gcc)
12625 @geindex Ada compatibility issues warnings
12630 @item @code{-gnatwY}
12632 `Disable warnings for Ada compatibility issues.'
12634 This switch suppresses the warnings intended to help in identifying
12635 incompatibilities between Ada language versions.
12638 @geindex -gnatw.y (gcc)
12640 @geindex Package spec needing body
12645 @item @code{-gnatw.y}
12647 `Activate information messages for why package spec needs body.'
12649 There are a number of cases in which a package spec needs a body.
12650 For example, the use of pragma Elaborate_Body, or the declaration
12651 of a procedure specification requiring a completion. This switch
12652 causes information messages to be output showing why a package
12653 specification requires a body. This can be useful in the case of
12654 a large package specification which is unexpectedly requiring a
12655 body. The default is that such information messages are not output.
12658 @geindex -gnatw.Y (gcc)
12660 @geindex No information messages for why package spec needs body
12665 @item @code{-gnatw.Y}
12667 `Disable information messages for why package spec needs body.'
12669 This switch suppresses the output of information messages showing why
12670 a package specification needs a body.
12673 @geindex -gnatwz (gcc)
12675 @geindex Unchecked_Conversion warnings
12680 @item @code{-gnatwz}
12682 `Activate warnings on unchecked conversions.'
12684 This switch activates warnings for unchecked conversions
12685 where the types are known at compile time to have different
12686 sizes. The default is that such warnings are generated. Warnings are also
12687 generated for subprogram pointers with different conventions.
12690 @geindex -gnatwZ (gcc)
12695 @item @code{-gnatwZ}
12697 `Suppress warnings on unchecked conversions.'
12699 This switch suppresses warnings for unchecked conversions
12700 where the types are known at compile time to have different
12701 sizes or conventions.
12704 @geindex -gnatw.z (gcc)
12706 @geindex Size/Alignment warnings
12711 @item @code{-gnatw.z}
12713 `Activate warnings for size not a multiple of alignment.'
12715 This switch activates warnings for cases of array and record types
12716 with specified @code{Size} and @code{Alignment} attributes where the
12717 size is not a multiple of the alignment, resulting in an object
12718 size that is greater than the specified size. The default
12719 is that such warnings are generated.
12722 @geindex -gnatw.Z (gcc)
12724 @geindex Size/Alignment warnings
12729 @item @code{-gnatw.Z}
12731 `Suppress warnings for size not a multiple of alignment.'
12733 This switch suppresses warnings for cases of array and record types
12734 with specified @code{Size} and @code{Alignment} attributes where the
12735 size is not a multiple of the alignment, resulting in an object
12736 size that is greater than the specified size. The warning can also
12737 be suppressed by giving an explicit @code{Object_Size} value.
12740 @geindex -Wunused (gcc)
12745 @item @code{-Wunused}
12747 The warnings controlled by the @code{-gnatw} switch are generated by
12748 the front end of the compiler. The GCC back end can provide
12749 additional warnings and they are controlled by the @code{-W} switch.
12750 For example, @code{-Wunused} activates back end
12751 warnings for entities that are declared but not referenced.
12754 @geindex -Wuninitialized (gcc)
12759 @item @code{-Wuninitialized}
12761 Similarly, @code{-Wuninitialized} activates
12762 the back end warning for uninitialized variables. This switch must be
12763 used in conjunction with an optimization level greater than zero.
12766 @geindex -Wstack-usage (gcc)
12771 @item @code{-Wstack-usage=`len'}
12773 Warn if the stack usage of a subprogram might be larger than @code{len} bytes.
12774 See @ref{e8,,Static Stack Usage Analysis} for details.
12777 @geindex -Wall (gcc)
12784 This switch enables most warnings from the GCC back end.
12785 The code generator detects a number of warning situations that are missed
12786 by the GNAT front end, and this switch can be used to activate them.
12787 The use of this switch also sets the default front-end warning mode to
12788 @code{-gnatwa}, that is, most front-end warnings are activated as well.
12798 Conversely, this switch suppresses warnings from the GCC back end.
12799 The use of this switch also sets the default front-end warning mode to
12800 @code{-gnatws}, that is, front-end warnings are suppressed as well.
12803 @geindex -Werror (gcc)
12808 @item @code{-Werror}
12810 This switch causes warnings from the GCC back end to be treated as
12811 errors. The warning string still appears, but the warning messages are
12812 counted as errors, and prevent the generation of an object file.
12813 The use of this switch also sets the default front-end warning mode to
12814 @code{-gnatwe}, that is, front-end warning messages and style check
12815 messages are treated as errors as well.
12818 A string of warning parameters can be used in the same parameter. For example:
12824 will turn on all optional warnings except for unrecognized pragma warnings,
12825 and also specify that warnings should be treated as errors.
12827 When no switch @code{-gnatw} is used, this is equivalent to:
12974 @node Debugging and Assertion Control,Validity Checking,Warning Message Control,Compiler Switches
12975 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-and-assertion-control}@anchor{f3}@anchor{gnat_ugn/building_executable_programs_with_gnat id16}@anchor{f4}
12976 @subsection Debugging and Assertion Control
12979 @geindex -gnata (gcc)
12984 @item @code{-gnata}
12990 @geindex Assertions
12992 @geindex Precondition
12994 @geindex Postcondition
12996 @geindex Type invariants
12998 @geindex Subtype predicates
13000 The @code{-gnata} option is equivalent to the following @code{Assertion_Policy} pragma:
13003 pragma Assertion_Policy (Check);
13006 Which is a shorthand for:
13009 pragma Assertion_Policy
13010 -- Ada RM assertion pragmas
13012 Static_Predicate => Check,
13013 Dynamic_Predicate => Check,
13015 Pre'Class => Check,
13017 Post'Class => Check,
13018 Type_Invariant => Check,
13019 Type_Invariant'Class => Check,
13020 Default_Initial_Condition => Check,
13021 -- GNAT specific assertion pragmas
13022 Assert_And_Cut => Check,
13024 Contract_Cases => Check,
13027 Initial_Condition => Check,
13028 Loop_Invariant => Check,
13029 Loop_Variant => Check,
13030 Postcondition => Check,
13031 Precondition => Check,
13032 Predicate => Check,
13033 Refined_Post => Check,
13034 Subprogram_Variant => Check);
13037 The pragmas @code{Assert} and @code{Debug} normally have no effect and
13038 are ignored. This switch, where @code{a} stands for ‘assert’, causes
13039 pragmas @code{Assert} and @code{Debug} to be activated. This switch also
13040 causes preconditions, postconditions, subtype predicates, and
13041 type invariants to be activated.
13043 The pragmas have the form:
13046 pragma Assert (<Boolean-expression> [, <static-string-expression>])
13047 pragma Debug (<procedure call>)
13048 pragma Type_Invariant (<type-local-name>, <Boolean-expression>)
13049 pragma Predicate (<type-local-name>, <Boolean-expression>)
13050 pragma Precondition (<Boolean-expression>, <string-expression>)
13051 pragma Postcondition (<Boolean-expression>, <string-expression>)
13054 The aspects have the form:
13057 with [Pre|Post|Type_Invariant|Dynamic_Predicate|Static_Predicate]
13058 => <Boolean-expression>;
13061 The @code{Assert} pragma causes @code{Boolean-expression} to be tested.
13062 If the result is @code{True}, the pragma has no effect (other than
13063 possible side effects from evaluating the expression). If the result is
13064 @code{False}, the exception @code{Assert_Failure} declared in the package
13065 @code{System.Assertions} is raised (passing @code{static-string-expression}, if
13066 present, as the message associated with the exception). If no string
13067 expression is given, the default is a string containing the file name and
13068 line number of the pragma.
13070 The @code{Debug} pragma causes @code{procedure} to be called. Note that
13071 @code{pragma Debug} may appear within a declaration sequence, allowing
13072 debugging procedures to be called between declarations.
13074 For the aspect specification, the @code{Boolean-expression} is evaluated.
13075 If the result is @code{True}, the aspect has no effect. If the result
13076 is @code{False}, the exception @code{Assert_Failure} is raised.
13079 @node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
13080 @anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{f5}@anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{e9}
13081 @subsection Validity Checking
13084 @geindex Validity Checking
13086 The Ada Reference Manual defines the concept of invalid values (see
13087 RM 13.9.1). The primary source of invalid values is uninitialized
13088 variables. A scalar variable that is left uninitialized may contain
13089 an invalid value; the concept of invalid does not apply to access or
13092 It is an error to read an invalid value, but the RM does not require
13093 run-time checks to detect such errors, except for some minimal
13094 checking to prevent erroneous execution (i.e. unpredictable
13095 behavior). This corresponds to the @code{-gnatVd} switch below,
13096 which is the default. For example, by default, if the expression of a
13097 case statement is invalid, it will raise Constraint_Error rather than
13098 causing a wild jump, and if an array index on the left-hand side of an
13099 assignment is invalid, it will raise Constraint_Error rather than
13100 overwriting an arbitrary memory location.
13102 The @code{-gnatVa} may be used to enable additional validity checks,
13103 which are not required by the RM. These checks are often very
13104 expensive (which is why the RM does not require them). These checks
13105 are useful in tracking down uninitialized variables, but they are
13106 not usually recommended for production builds, and in particular
13107 we do not recommend using these extra validity checking options in
13108 combination with optimization, since this can confuse the optimizer.
13109 If performance is a consideration, leading to the need to optimize,
13110 then the validity checking options should not be used.
13112 The other @code{-gnatV`x'} switches below allow finer-grained
13113 control; you can enable whichever validity checks you desire. However,
13114 for most debugging purposes, @code{-gnatVa} is sufficient, and the
13115 default @code{-gnatVd} (i.e. standard Ada behavior) is usually
13116 sufficient for non-debugging use.
13118 The @code{-gnatB} switch tells the compiler to assume that all
13119 values are valid (that is, within their declared subtype range)
13120 except in the context of a use of the Valid attribute. This means
13121 the compiler can generate more efficient code, since the range
13122 of values is better known at compile time. However, an uninitialized
13123 variable can cause wild jumps and memory corruption in this mode.
13125 The @code{-gnatV`x'} switch allows control over the validity
13126 checking mode as described below.
13127 The @code{x} argument is a string of letters that
13128 indicate validity checks that are performed or not performed in addition
13129 to the default checks required by Ada as described above.
13131 @geindex -gnatVa (gcc)
13136 @item @code{-gnatVa}
13138 `All validity checks.'
13140 All validity checks are turned on.
13141 That is, @code{-gnatVa} is
13142 equivalent to @code{gnatVcdefimoprst}.
13145 @geindex -gnatVc (gcc)
13150 @item @code{-gnatVc}
13152 `Validity checks for copies.'
13154 The right-hand side of assignments, and the (explicit) initializing values
13155 of object declarations are validity checked.
13158 @geindex -gnatVd (gcc)
13163 @item @code{-gnatVd}
13165 `Default (RM) validity checks.'
13167 Some validity checks are required by Ada (see RM 13.9.1 (9-11)); these
13168 (and only these) validity checks are enabled by default.
13169 For case statements (and case expressions) that lack a “when others =>”
13170 choice, a check is made that the value of the selector expression
13171 belongs to its nominal subtype. If it does not, Constraint_Error is raised.
13172 For assignments to array components (and for indexed components in some
13173 other contexts), a check is made that each index expression belongs to the
13174 corresponding index subtype. If it does not, Constraint_Error is raised.
13175 Both these validity checks may be turned off using switch @code{-gnatVD}.
13176 They are turned on by default. If @code{-gnatVD} is specified, a subsequent
13177 switch @code{-gnatVd} will leave the checks turned on.
13178 Switch @code{-gnatVD} should be used only if you are sure that all such
13179 expressions have valid values. If you use this switch and invalid values
13180 are present, then the program is erroneous, and wild jumps or memory
13181 overwriting may occur.
13184 @geindex -gnatVe (gcc)
13189 @item @code{-gnatVe}
13191 `Validity checks for scalar components.'
13193 In the absence of this switch, assignments to scalar components of
13194 enclosing record or array objects are not validity checked, even if
13195 validity checks for assignments generally (@code{-gnatVc}) are turned on.
13196 Specifying this switch enables such checks.
13197 This switch has no effect if the @code{-gnatVc} switch is not specified.
13200 @geindex -gnatVf (gcc)
13205 @item @code{-gnatVf}
13207 `Validity checks for floating-point values.'
13209 Specifying this switch enables validity checking for floating-point
13210 values in the same contexts where validity checking is enabled for
13211 other scalar values.
13212 In the absence of this switch, validity checking is not performed for
13213 floating-point values. This takes precedence over other statements about
13214 performing validity checking for scalar objects in various scenarios.
13215 One way to look at it is that if this switch is not set, then whenever
13216 any of the other rules in this section use the word “scalar” they
13217 really mean “scalar and not floating-point”.
13218 If @code{-gnatVf} is specified, then validity checking also applies
13219 for floating-point values, and NaNs and infinities are considered invalid,
13220 as well as out-of-range values for constrained types. The exact contexts
13221 in which floating-point values are checked depends on the setting of other
13222 options. For example, @code{-gnatVif} or @code{-gnatVfi}
13223 (the order does not matter) specifies that floating-point parameters of mode
13224 @code{in} should be validity checked.
13227 @geindex -gnatVi (gcc)
13232 @item @code{-gnatVi}
13234 `Validity checks for `@w{`}in`@w{`} mode parameters.'
13236 Arguments for parameters of mode @code{in} are validity checked in function
13237 and procedure calls at the point of call.
13240 @geindex -gnatVm (gcc)
13245 @item @code{-gnatVm}
13247 `Validity checks for `@w{`}in out`@w{`} mode parameters.'
13249 Arguments for parameters of mode @code{in out} are validity checked in
13250 procedure calls at the point of call. The @code{'m'} here stands for
13251 modify, since this concerns parameters that can be modified by the call.
13252 Note that there is no specific option to test @code{out} parameters,
13253 but any reference within the subprogram will be tested in the usual
13254 manner, and if an invalid value is copied back, any reference to it
13255 will be subject to validity checking.
13258 @geindex -gnatVn (gcc)
13263 @item @code{-gnatVn}
13265 `No validity checks.'
13267 This switch turns off all validity checking, including the default checking
13268 for case statements and left hand side subscripts. Note that the use of
13269 the switch @code{-gnatp} suppresses all run-time checks, including
13270 validity checks, and thus implies @code{-gnatVn}. When this switch
13271 is used, it cancels any other @code{-gnatV} previously issued.
13274 @geindex -gnatVo (gcc)
13279 @item @code{-gnatVo}
13281 `Validity checks for operator and attribute operands.'
13283 Scalar arguments for predefined operators and for attributes are
13285 This includes all operators in package @code{Standard},
13286 the shift operators defined as intrinsic in package @code{Interfaces}
13287 and operands for attributes such as @code{Pos}. Checks are also made
13288 on individual component values for composite comparisons, and on the
13289 expressions in type conversions and qualified expressions. Checks are
13290 also made on explicit ranges using @code{..} (e.g., slices, loops etc).
13293 @geindex -gnatVp (gcc)
13298 @item @code{-gnatVp}
13300 `Validity checks for parameters.'
13302 This controls the treatment of formal parameters within a subprogram (as
13303 opposed to @code{-gnatVi} and @code{-gnatVm}, which control validity
13304 testing of actual parameters of a call). If either of these call options is
13305 specified, then normally an assumption is made within a subprogram that
13306 the validity of any incoming formal parameters of the corresponding mode(s)
13307 has already been checked at the point of call and does not need rechecking.
13308 If @code{-gnatVp} is set, then this assumption is not made and so their
13309 validity may be checked (or rechecked) within the subprogram. If neither of
13310 the two call-related options is specified, then this switch has no effect.
13313 @geindex -gnatVr (gcc)
13318 @item @code{-gnatVr}
13320 `Validity checks for function returns.'
13322 The expression in simple @code{return} statements in functions is validity
13326 @geindex -gnatVs (gcc)
13331 @item @code{-gnatVs}
13333 `Validity checks for subscripts.'
13335 All subscript expressions are checked for validity, whatever context
13336 they occur in (in default mode some subscripts are not validity checked;
13337 for example, validity checking may be omitted in some cases involving
13338 a read of a component of an array).
13341 @geindex -gnatVt (gcc)
13346 @item @code{-gnatVt}
13348 `Validity checks for tests.'
13350 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
13351 statements are checked, as well as guard expressions in entry calls.
13354 The @code{-gnatV} switch may be followed by a string of letters
13355 to turn on a series of validity checking options.
13356 For example, @code{-gnatVcr}
13357 specifies that in addition to the default validity checking, copies and
13358 function return expressions are to be validity checked.
13359 In order to make it easier to specify the desired combination of effects,
13360 the upper case letters @code{CDFIMORST} may
13361 be used to turn off the corresponding lower case option.
13362 Thus @code{-gnatVaM} turns on all validity checking options except for
13363 checking of @code{in out} parameters.
13365 The specification of additional validity checking generates extra code (and
13366 in the case of @code{-gnatVa} the code expansion can be substantial).
13367 However, these additional checks can be very useful in detecting
13368 uninitialized variables, incorrect use of unchecked conversion, and other
13369 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
13370 is useful in conjunction with the extra validity checking, since this
13371 ensures that wherever possible uninitialized variables have invalid values.
13373 See also the pragma @code{Validity_Checks} which allows modification of
13374 the validity checking mode at the program source level, and also allows for
13375 temporary disabling of validity checks.
13377 @node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
13378 @anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{ee}
13379 @subsection Style Checking
13382 @geindex Style checking
13384 @geindex -gnaty (gcc)
13386 The @code{-gnaty} switch causes the compiler to
13387 enforce specified style rules. A limited set of style rules has been used
13388 in writing the GNAT sources themselves. This switch allows user programs
13389 to activate all or some of these checks. If the source program fails a
13390 specified style check, an appropriate message is given, preceded by
13391 the character sequence ‘(style)’. This message does not prevent
13392 successful compilation (unless the @code{-gnatwe} switch is used).
13394 Note that this is by no means intended to be a general facility for
13395 checking arbitrary coding standards. It is simply an embedding of the
13396 style rules we have chosen for the GNAT sources. If you are starting
13397 a project which does not have established style standards, you may
13398 find it useful to adopt the entire set of GNAT coding standards, or
13399 some subset of them.
13402 The string @code{x} is a sequence of letters or digits
13403 indicating the particular style
13404 checks to be performed. The following checks are defined:
13406 @geindex -gnaty[0-9] (gcc)
13411 @item @code{-gnaty0}
13413 `Specify indentation level.'
13415 If a digit from 1-9 appears
13416 in the string after @code{-gnaty}
13417 then proper indentation is checked, with the digit indicating the
13418 indentation level required. A value of zero turns off this style check.
13419 The rule checks that the following constructs start on a column that is
13420 a multiple of the alignment level:
13426 beginnings of declarations (except record component declarations)
13430 beginnings of the structural components of compound statements;
13433 @code{end} keyword that completes the declaration of a program unit declaration
13434 or body or that completes a compound statement.
13437 Full line comments must be
13438 aligned with the @code{--} starting on a column that is a multiple of
13439 the alignment level, or they may be aligned the same way as the following
13440 non-blank line (this is useful when full line comments appear in the middle
13441 of a statement, or they may be aligned with the source line on the previous
13445 @geindex -gnatya (gcc)
13450 @item @code{-gnatya}
13452 `Check attribute casing.'
13454 Attribute names, including the case of keywords such as @code{digits}
13455 used as attributes names, must be written in mixed case, that is, the
13456 initial letter and any letter following an underscore must be uppercase.
13457 All other letters must be lowercase.
13460 @geindex -gnatyA (gcc)
13465 @item @code{-gnatyA}
13467 `Use of array index numbers in array attributes.'
13469 When using the array attributes First, Last, Range,
13470 or Length, the index number must be omitted for one-dimensional arrays
13471 and is required for multi-dimensional arrays.
13474 @geindex -gnatyb (gcc)
13479 @item @code{-gnatyb}
13481 `Blanks not allowed at statement end.'
13483 Trailing blanks are not allowed at the end of statements. The purpose of this
13484 rule, together with h (no horizontal tabs), is to enforce a canonical format
13485 for the use of blanks to separate source tokens.
13488 @geindex -gnatyB (gcc)
13493 @item @code{-gnatyB}
13495 `Check Boolean operators.'
13497 The use of AND/OR operators is not permitted except in the cases of modular
13498 operands, array operands, and simple stand-alone boolean variables or
13499 boolean constants. In all other cases @code{and then}/@cite{or else} are
13503 @geindex -gnatyc (gcc)
13508 @item @code{-gnatyc}
13510 `Check comments, double space.'
13512 Comments must meet the following set of rules:
13518 The @code{--} that starts the column must either start in column one,
13519 or else at least one blank must precede this sequence.
13522 Comments that follow other tokens on a line must have at least one blank
13523 following the @code{--} at the start of the comment.
13526 Full line comments must have at least two blanks following the
13527 @code{--} that starts the comment, with the following exceptions.
13530 A line consisting only of the @code{--} characters, possibly preceded
13531 by blanks is permitted.
13534 A comment starting with @code{--x} where @code{x} is a special character
13536 This allows proper processing of the output from specialized tools
13537 such as @code{gnatprep} (where @code{--!} is used) and in earlier versions of the SPARK
13539 language (where @code{--#} is used). For the purposes of this rule, a
13540 special character is defined as being in one of the ASCII ranges
13541 @code{16#21#...16#2F#} or @code{16#3A#...16#3F#}.
13542 Note that this usage is not permitted
13543 in GNAT implementation units (i.e., when @code{-gnatg} is used).
13546 A line consisting entirely of minus signs, possibly preceded by blanks, is
13547 permitted. This allows the construction of box comments where lines of minus
13548 signs are used to form the top and bottom of the box.
13551 A comment that starts and ends with @code{--} is permitted as long as at
13552 least one blank follows the initial @code{--}. Together with the preceding
13553 rule, this allows the construction of box comments, as shown in the following
13557 ---------------------------
13558 -- This is a box comment --
13559 -- with two text lines. --
13560 ---------------------------
13565 @geindex -gnatyC (gcc)
13570 @item @code{-gnatyC}
13572 `Check comments, single space.'
13574 This is identical to @code{c} except that only one space
13575 is required following the @code{--} of a comment instead of two.
13578 @geindex -gnatyd (gcc)
13583 @item @code{-gnatyd}
13585 `Check no DOS line terminators present.'
13587 All lines must be terminated by a single ASCII.LF
13588 character (in particular the DOS line terminator sequence CR/LF is not
13592 @geindex -gnatyD (gcc)
13597 @item @code{-gnatyD}
13599 `Check declared identifiers in mixed case.'
13601 Declared identifiers must be in mixed case, as in
13602 This_Is_An_Identifier. Use -gnatyr in addition to ensure
13603 that references match declarations.
13606 @geindex -gnatye (gcc)
13611 @item @code{-gnatye}
13613 `Check end/exit labels.'
13615 Optional labels on @code{end} statements ending subprograms and on
13616 @code{exit} statements exiting named loops, are required to be present.
13619 @geindex -gnatyf (gcc)
13624 @item @code{-gnatyf}
13626 `No form feeds or vertical tabs.'
13628 Neither form feeds nor vertical tab characters are permitted
13629 in the source text.
13632 @geindex -gnatyg (gcc)
13637 @item @code{-gnatyg}
13641 The set of style check switches is set to match that used by the GNAT sources.
13642 This may be useful when developing code that is eventually intended to be
13643 incorporated into GNAT. Currently this is equivalent to
13644 @code{-gnatyydISuxz}) but additional style switches may be added to this
13645 set in the future without advance notice.
13648 @geindex -gnatyh (gcc)
13653 @item @code{-gnatyh}
13655 `No horizontal tabs.'
13657 Horizontal tab characters are not permitted in the source text.
13658 Together with the b (no blanks at end of line) check, this
13659 enforces a canonical form for the use of blanks to separate
13663 @geindex -gnatyi (gcc)
13668 @item @code{-gnatyi}
13670 `Check if-then layout.'
13672 The keyword @code{then} must appear either on the same
13673 line as corresponding @code{if}, or on a line on its own, lined
13674 up under the @code{if}.
13677 @geindex -gnatyI (gcc)
13682 @item @code{-gnatyI}
13684 `check mode IN keywords.'
13686 Mode @code{in} (the default mode) is not
13687 allowed to be given explicitly. @code{in out} is fine,
13688 but not @code{in} on its own.
13691 @geindex -gnatyk (gcc)
13696 @item @code{-gnatyk}
13698 `Check keyword casing.'
13700 All keywords must be in lower case (with the exception of keywords
13701 such as @code{digits} used as attribute names to which this check
13702 does not apply). A single error is reported for each line breaking
13703 this rule even if multiple casing issues exist on a same line.
13706 @geindex -gnatyl (gcc)
13711 @item @code{-gnatyl}
13715 Layout of statement and declaration constructs must follow the
13716 recommendations in the Ada Reference Manual, as indicated by the
13717 form of the syntax rules. For example an @code{else} keyword must
13718 be lined up with the corresponding @code{if} keyword.
13720 There are two respects in which the style rule enforced by this check
13721 option are more liberal than those in the Ada Reference Manual. First
13722 in the case of record declarations, it is permissible to put the
13723 @code{record} keyword on the same line as the @code{type} keyword, and
13724 then the @code{end} in @code{end record} must line up under @code{type}.
13725 This is also permitted when the type declaration is split on two lines.
13726 For example, any of the following three layouts is acceptable:
13747 Second, in the case of a block statement, a permitted alternative
13748 is to put the block label on the same line as the @code{declare} or
13749 @code{begin} keyword, and then line the @code{end} keyword up under
13750 the block label. For example both the following are permitted:
13767 The same alternative format is allowed for loops. For example, both of
13768 the following are permitted:
13771 Clear : while J < 10 loop
13782 @geindex -gnatyLnnn (gcc)
13787 @item @code{-gnatyL}
13789 `Set maximum nesting level.'
13791 The maximum level of nesting of constructs (including subprograms, loops,
13792 blocks, packages, and conditionals) may not exceed the given value
13793 `nnn'. A value of zero disconnects this style check.
13796 @geindex -gnatym (gcc)
13801 @item @code{-gnatym}
13803 `Check maximum line length.'
13805 The length of source lines must not exceed 79 characters, including
13806 any trailing blanks. The value of 79 allows convenient display on an
13807 80 character wide device or window, allowing for possible special
13808 treatment of 80 character lines. Note that this count is of
13809 characters in the source text. This means that a tab character counts
13810 as one character in this count and a wide character sequence counts as
13811 a single character (however many bytes are needed in the encoding).
13814 @geindex -gnatyMnnn (gcc)
13819 @item @code{-gnatyM}
13821 `Set maximum line length.'
13823 The length of lines must not exceed the
13824 given value `nnn'. The maximum value that can be specified is 32767.
13825 If neither style option for setting the line length is used, then the
13826 default is 255. This also controls the maximum length of lexical elements,
13827 where the only restriction is that they must fit on a single line.
13830 @geindex -gnatyn (gcc)
13835 @item @code{-gnatyn}
13837 `Check casing of entities in Standard.'
13839 Any identifier from Standard must be cased
13840 to match the presentation in the Ada Reference Manual (for example,
13841 @code{Integer} and @code{ASCII.NUL}).
13844 @geindex -gnatyN (gcc)
13849 @item @code{-gnatyN}
13851 `Turn off all style checks.'
13853 All style check options are turned off.
13856 @geindex -gnatyo (gcc)
13861 @item @code{-gnatyo}
13863 `Check order of subprogram bodies.'
13865 All subprogram bodies in a given scope
13866 (e.g., a package body) must be in alphabetical order. The ordering
13867 rule uses normal Ada rules for comparing strings, ignoring casing
13868 of letters, except that if there is a trailing numeric suffix, then
13869 the value of this suffix is used in the ordering (e.g., Junk2 comes
13873 @geindex -gnatyO (gcc)
13878 @item @code{-gnatyO}
13880 `Check that overriding subprograms are explicitly marked as such.'
13882 This applies to all subprograms of a derived type that override a primitive
13883 operation of the type, for both tagged and untagged types. In particular,
13884 the declaration of a primitive operation of a type extension that overrides
13885 an inherited operation must carry an overriding indicator. Another case is
13886 the declaration of a function that overrides a predefined operator (such
13887 as an equality operator).
13890 @geindex -gnatyp (gcc)
13895 @item @code{-gnatyp}
13897 `Check pragma casing.'
13899 Pragma names must be written in mixed case, that is, the
13900 initial letter and any letter following an underscore must be uppercase.
13901 All other letters must be lowercase. An exception is that SPARK_Mode is
13902 allowed as an alternative for Spark_Mode.
13905 @geindex -gnatyr (gcc)
13910 @item @code{-gnatyr}
13912 `Check references.'
13914 All identifier references must be cased in the same way as the
13915 corresponding declaration. No specific casing style is imposed on
13916 identifiers. The only requirement is for consistency of references
13920 @geindex -gnatys (gcc)
13925 @item @code{-gnatys}
13927 `Check separate specs.'
13929 Separate declarations (‘specs’) are required for subprograms (a
13930 body is not allowed to serve as its own declaration). The only
13931 exception is that parameterless library level procedures are
13932 not required to have a separate declaration. This exception covers
13933 the most frequent form of main program procedures.
13936 @geindex -gnatyS (gcc)
13941 @item @code{-gnatyS}
13943 `Check no statements after then/else.'
13945 No statements are allowed
13946 on the same line as a @code{then} or @code{else} keyword following the
13947 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
13948 affected, and a special exception allows a pragma to appear after @code{else}.
13951 @geindex -gnatyt (gcc)
13956 @item @code{-gnatyt}
13958 `Check token spacing.'
13960 The following token spacing rules are enforced:
13966 The keywords @code{abs} and @code{not} must be followed by a space.
13969 The token @code{=>} must be surrounded by spaces.
13972 The token @code{<>} must be preceded by a space or a left parenthesis.
13975 Binary operators other than @code{**} must be surrounded by spaces.
13976 There is no restriction on the layout of the @code{**} binary operator.
13979 Colon must be surrounded by spaces.
13982 Colon-equal (assignment, initialization) must be surrounded by spaces.
13985 Comma must be the first non-blank character on the line, or be
13986 immediately preceded by a non-blank character, and must be followed
13990 If the token preceding a left parenthesis ends with a letter or digit, then
13991 a space must separate the two tokens.
13994 If the token following a right parenthesis starts with a letter or digit, then
13995 a space must separate the two tokens.
13998 A right parenthesis must either be the first non-blank character on
13999 a line, or it must be preceded by a non-blank character.
14002 A semicolon must not be preceded by a space, and must not be followed by
14003 a non-blank character.
14006 A unary plus or minus may not be followed by a space.
14009 A vertical bar must be surrounded by spaces.
14012 Exactly one blank (and no other white space) must appear between
14013 a @code{not} token and a following @code{in} token.
14016 @geindex -gnatyu (gcc)
14021 @item @code{-gnatyu}
14023 `Check unnecessary blank lines.'
14025 Unnecessary blank lines are not allowed. A blank line is considered
14026 unnecessary if it appears at the end of the file, or if more than
14027 one blank line occurs in sequence.
14030 @geindex -gnatyx (gcc)
14035 @item @code{-gnatyx}
14037 `Check extra parentheses.'
14039 Unnecessary extra levels of parentheses (C-style) are not allowed
14040 around conditions (or selection expressions) in @code{if}, @code{while},
14041 @code{case}, and @code{exit} statements, as well as part of ranges.
14044 @geindex -gnatyy (gcc)
14049 @item @code{-gnatyy}
14051 `Set all standard style check options.'
14053 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
14054 options enabled with the exception of @code{-gnatyB}, @code{-gnatyd},
14055 @code{-gnatyI}, @code{-gnatyLnnn}, @code{-gnatyo}, @code{-gnatyO},
14056 @code{-gnatyS}, @code{-gnatyu}, and @code{-gnatyx}.
14059 @geindex -gnatyz (gcc)
14064 @item @code{-gnatyz}
14066 `Check extra parentheses (operator precedence).'
14068 Extra levels of parentheses that are not required by operator precedence
14069 rules are flagged. See also @code{-gnatyx}.
14072 @geindex -gnaty- (gcc)
14077 @item @code{-gnaty-}
14079 `Remove style check options.'
14081 This causes any subsequent options in the string to act as canceling the
14082 corresponding style check option. To cancel maximum nesting level control,
14083 use the @code{L} parameter without any integer value after that, because any
14084 digit following `-' in the parameter string of the @code{-gnaty}
14085 option will be treated as canceling the indentation check. The same is true
14086 for the @code{M} parameter. @code{y} and @code{N} parameters are not
14090 @geindex -gnaty+ (gcc)
14095 @item @code{-gnaty+}
14097 `Enable style check options.'
14099 This causes any subsequent options in the string to enable the corresponding
14100 style check option. That is, it cancels the effect of a previous -,
14104 @c end of switch description (leave this comment to ease automatic parsing for
14108 In the above rules, appearing in column one is always permitted, that is,
14109 counts as meeting either a requirement for a required preceding space,
14110 or as meeting a requirement for no preceding space.
14112 Appearing at the end of a line is also always permitted, that is, counts
14113 as meeting either a requirement for a following space, or as meeting
14114 a requirement for no following space.
14116 If any of these style rules is violated, a message is generated giving
14117 details on the violation. The initial characters of such messages are
14118 always ‘@cite{(style)}’. Note that these messages are treated as warning
14119 messages, so they normally do not prevent the generation of an object
14120 file. The @code{-gnatwe} switch can be used to treat warning messages,
14121 including style messages, as fatal errors.
14123 The switch @code{-gnaty} on its own (that is not
14124 followed by any letters or digits) is equivalent
14125 to the use of @code{-gnatyy} as described above, that is all
14126 built-in standard style check options are enabled.
14128 The switch @code{-gnatyN} clears any previously set style checks.
14130 @node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
14131 @anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{f7}@anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{ec}
14132 @subsection Run-Time Checks
14135 @geindex Division by zero
14137 @geindex Access before elaboration
14140 @geindex division by zero
14143 @geindex access before elaboration
14146 @geindex stack overflow checking
14148 By default, the following checks are suppressed: stack overflow
14149 checks, and checks for access before elaboration on subprogram
14150 calls. All other checks, including overflow checks, range checks and
14151 array bounds checks, are turned on by default. The following @code{gcc}
14152 switches refine this default behavior.
14154 @geindex -gnatp (gcc)
14159 @item @code{-gnatp}
14161 @geindex Suppressing checks
14164 @geindex suppressing
14166 This switch causes the unit to be compiled
14167 as though @code{pragma Suppress (All_checks)}
14168 had been present in the source. Validity checks are also eliminated (in
14169 other words @code{-gnatp} also implies @code{-gnatVn}.
14170 Use this switch to improve the performance
14171 of the code at the expense of safety in the presence of invalid data or
14174 Note that when checks are suppressed, the compiler is allowed, but not
14175 required, to omit the checking code. If the run-time cost of the
14176 checking code is zero or near-zero, the compiler will generate it even
14177 if checks are suppressed. In particular, if the compiler can prove
14178 that a certain check will necessarily fail, it will generate code to
14179 do an unconditional ‘raise’, even if checks are suppressed. The
14180 compiler warns in this case. Another case in which checks may not be
14181 eliminated is when they are embedded in certain run-time routines such
14182 as math library routines.
14184 Of course, run-time checks are omitted whenever the compiler can prove
14185 that they will not fail, whether or not checks are suppressed.
14187 Note that if you suppress a check that would have failed, program
14188 execution is erroneous, which means the behavior is totally
14189 unpredictable. The program might crash, or print wrong answers, or
14190 do anything else. It might even do exactly what you wanted it to do
14191 (and then it might start failing mysteriously next week or next
14192 year). The compiler will generate code based on the assumption that
14193 the condition being checked is true, which can result in erroneous
14194 execution if that assumption is wrong.
14196 The checks subject to suppression include all the checks defined by the Ada
14197 standard, the additional implementation defined checks @code{Alignment_Check},
14198 @code{Duplicated_Tag_Check}, @code{Predicate_Check}, @code{Container_Checks}, @code{Tampering_Check},
14199 and @code{Validity_Check}, as well as any checks introduced using @code{pragma Check_Name}.
14200 Note that @code{Atomic_Synchronization} is not automatically suppressed by use of this option.
14202 If the code depends on certain checks being active, you can use
14203 pragma @code{Unsuppress} either as a configuration pragma or as
14204 a local pragma to make sure that a specified check is performed
14205 even if @code{gnatp} is specified.
14207 The @code{-gnatp} switch has no effect if a subsequent
14208 @code{-gnat-p} switch appears.
14211 @geindex -gnat-p (gcc)
14213 @geindex Suppressing checks
14216 @geindex suppressing
14223 @item @code{-gnat-p}
14225 This switch cancels the effect of a previous @code{gnatp} switch.
14228 @geindex -gnato?? (gcc)
14230 @geindex Overflow checks
14232 @geindex Overflow mode
14240 @item @code{-gnato??}
14242 This switch controls the mode used for computing intermediate
14243 arithmetic integer operations, and also enables overflow checking.
14244 For a full description of overflow mode and checking control, see
14245 the ‘Overflow Check Handling in GNAT’ appendix in this
14248 Overflow checks are always enabled by this switch. The argument
14249 controls the mode, using the codes
14256 In STRICT mode, intermediate operations are always done using the
14257 base type, and overflow checking ensures that the result is within
14258 the base type range.
14260 @item `2 = MINIMIZED'
14262 In MINIMIZED mode, overflows in intermediate operations are avoided
14263 where possible by using a larger integer type for the computation
14264 (typically @code{Long_Long_Integer}). Overflow checking ensures that
14265 the result fits in this larger integer type.
14267 @item `3 = ELIMINATED'
14269 In ELIMINATED mode, overflows in intermediate operations are avoided
14270 by using multi-precision arithmetic. In this case, overflow checking
14271 has no effect on intermediate operations (since overflow is impossible).
14274 If two digits are present after @code{-gnato} then the first digit
14275 sets the mode for expressions outside assertions, and the second digit
14276 sets the mode for expressions within assertions. Here assertions is used
14277 in the technical sense (which includes for example precondition and
14278 postcondition expressions).
14280 If one digit is present, the corresponding mode is applicable to both
14281 expressions within and outside assertion expressions.
14283 If no digits are present, the default is to enable overflow checks
14284 and set STRICT mode for both kinds of expressions. This is compatible
14285 with the use of @code{-gnato} in previous versions of GNAT.
14287 @geindex Machine_Overflows
14289 Note that the @code{-gnato??} switch does not affect the code generated
14290 for any floating-point operations; it applies only to integer semantics.
14291 For floating-point, GNAT has the @code{Machine_Overflows}
14292 attribute set to @code{False} and the normal mode of operation is to
14293 generate IEEE NaN and infinite values on overflow or invalid operations
14294 (such as dividing 0.0 by 0.0).
14296 The reason that we distinguish overflow checking from other kinds of
14297 range constraint checking is that a failure of an overflow check, unlike
14298 for example the failure of a range check, can result in an incorrect
14299 value, but cannot cause random memory destruction (like an out of range
14300 subscript), or a wild jump (from an out of range case value). Overflow
14301 checking is also quite expensive in time and space, since in general it
14302 requires the use of double length arithmetic.
14304 Note again that the default is @code{-gnato11} (equivalent to @code{-gnato1}),
14305 so overflow checking is performed in STRICT mode by default.
14308 @geindex -gnatE (gcc)
14310 @geindex Elaboration checks
14313 @geindex elaboration
14318 @item @code{-gnatE}
14320 Enables dynamic checks for access-before-elaboration
14321 on subprogram calls and generic instantiations.
14322 Note that @code{-gnatE} is not necessary for safety, because in the
14323 default mode, GNAT ensures statically that the checks would not fail.
14324 For full details of the effect and use of this switch,
14325 @ref{c9,,Compiling with gcc}.
14328 @geindex -fstack-check (gcc)
14330 @geindex Stack Overflow Checking
14333 @geindex stack overflow checking
14338 @item @code{-fstack-check}
14340 Activates stack overflow checking. For full details of the effect and use of
14341 this switch see @ref{e7,,Stack Overflow Checking}.
14344 @geindex Unsuppress
14346 The setting of these switches only controls the default setting of the
14347 checks. You may modify them using either @code{Suppress} (to remove
14348 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
14349 the program source.
14351 @node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
14352 @anchor{gnat_ugn/building_executable_programs_with_gnat id20}@anchor{f8}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-syntax-checking}@anchor{f9}
14353 @subsection Using @code{gcc} for Syntax Checking
14356 @geindex -gnats (gcc)
14361 @item @code{-gnats}
14363 The @code{s} stands for ‘syntax’.
14365 Run GNAT in syntax checking only mode. For
14366 example, the command
14369 $ gcc -c -gnats x.adb
14372 compiles file @code{x.adb} in syntax-check-only mode. You can check a
14373 series of files in a single command
14374 , and can use wildcards to specify such a group of files.
14375 Note that you must specify the @code{-c} (compile
14376 only) flag in addition to the @code{-gnats} flag.
14378 You may use other switches in conjunction with @code{-gnats}. In
14379 particular, @code{-gnatl} and @code{-gnatv} are useful to control the
14380 format of any generated error messages.
14382 When the source file is empty or contains only empty lines and/or comments,
14383 the output is a warning:
14386 $ gcc -c -gnats -x ada toto.txt
14387 toto.txt:1:01: warning: empty file, contains no compilation units
14391 Otherwise, the output is simply the error messages, if any. No object file or
14392 ALI file is generated by a syntax-only compilation. Also, no units other
14393 than the one specified are accessed. For example, if a unit @code{X}
14394 `with's a unit @code{Y}, compiling unit @code{X} in syntax
14395 check only mode does not access the source file containing unit
14398 @geindex Multiple units
14399 @geindex syntax checking
14401 Normally, GNAT allows only a single unit in a source file. However, this
14402 restriction does not apply in syntax-check-only mode, and it is possible
14403 to check a file containing multiple compilation units concatenated
14404 together. This is primarily used by the @code{gnatchop} utility
14405 (@ref{1d,,Renaming Files with gnatchop}).
14408 @node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
14409 @anchor{gnat_ugn/building_executable_programs_with_gnat id21}@anchor{fa}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-semantic-checking}@anchor{fb}
14410 @subsection Using @code{gcc} for Semantic Checking
14413 @geindex -gnatc (gcc)
14418 @item @code{-gnatc}
14420 The @code{c} stands for ‘check’.
14421 Causes the compiler to operate in semantic check mode,
14422 with full checking for all illegalities specified in the
14423 Ada Reference Manual, but without generation of any object code
14424 (no object file is generated).
14426 Because dependent files must be accessed, you must follow the GNAT
14427 semantic restrictions on file structuring to operate in this mode:
14433 The needed source files must be accessible
14434 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
14437 Each file must contain only one compilation unit.
14440 The file name and unit name must match (@ref{3b,,File Naming Rules}).
14443 The output consists of error messages as appropriate. No object file is
14444 generated. An @code{ALI} file is generated for use in the context of
14445 cross-reference tools, but this file is marked as not being suitable
14446 for binding (since no object file is generated).
14447 The checking corresponds exactly to the notion of
14448 legality in the Ada Reference Manual.
14450 Any unit can be compiled in semantics-checking-only mode, including
14451 units that would not normally be compiled (subunits,
14452 and specifications where a separate body is present).
14455 @node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
14456 @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{fc}
14457 @subsection Compiling Different Versions of Ada
14460 The switches described in this section allow you to explicitly specify
14461 the version of the Ada language that your programs are written in.
14462 The default mode is Ada 2012,
14463 but you can also specify Ada 95, Ada 2005 mode, or
14464 indicate Ada 83 compatibility mode.
14466 @geindex Compatibility with Ada 83
14468 @geindex -gnat83 (gcc)
14471 @geindex Ada 83 tests
14473 @geindex Ada 83 mode
14478 @item @code{-gnat83} (Ada 83 Compatibility Mode)
14480 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
14481 specifies that the program is to be compiled in Ada 83 mode. With
14482 @code{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
14483 semantics where this can be done easily.
14484 It is not possible to guarantee this switch does a perfect
14485 job; some subtle tests, such as are
14486 found in earlier ACVC tests (and that have been removed from the ACATS suite
14487 for Ada 95), might not compile correctly.
14488 Nevertheless, this switch may be useful in some circumstances, for example
14489 where, due to contractual reasons, existing code needs to be maintained
14490 using only Ada 83 features.
14492 With few exceptions (most notably the need to use @code{<>} on
14494 @geindex Generic formal parameters
14495 generic formal parameters,
14496 the use of the new Ada 95 / Ada 2005
14497 reserved words, and the use of packages
14498 with optional bodies), it is not necessary to specify the
14499 @code{-gnat83} switch when compiling Ada 83 programs, because, with rare
14500 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
14501 a correct Ada 83 program is usually also a correct program
14502 in these later versions of the language standard. For further information
14503 please refer to the `Compatibility and Porting Guide' chapter in the
14504 @cite{GNAT Reference Manual}.
14507 @geindex -gnat95 (gcc)
14509 @geindex Ada 95 mode
14514 @item @code{-gnat95} (Ada 95 mode)
14516 This switch directs the compiler to implement the Ada 95 version of the
14518 Since Ada 95 is almost completely upwards
14519 compatible with Ada 83, Ada 83 programs may generally be compiled using
14520 this switch (see the description of the @code{-gnat83} switch for further
14521 information about Ada 83 mode).
14522 If an Ada 2005 program is compiled in Ada 95 mode,
14523 uses of the new Ada 2005 features will cause error
14524 messages or warnings.
14526 This switch also can be used to cancel the effect of a previous
14527 @code{-gnat83}, @code{-gnat05/2005}, or @code{-gnat12/2012}
14528 switch earlier in the command line.
14531 @geindex -gnat05 (gcc)
14533 @geindex -gnat2005 (gcc)
14535 @geindex Ada 2005 mode
14540 @item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
14542 This switch directs the compiler to implement the Ada 2005 version of the
14543 language, as documented in the official Ada standards document.
14544 Since Ada 2005 is almost completely upwards
14545 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
14546 may generally be compiled using this switch (see the description of the
14547 @code{-gnat83} and @code{-gnat95} switches for further
14551 @geindex -gnat12 (gcc)
14553 @geindex -gnat2012 (gcc)
14555 @geindex Ada 2012 mode
14560 @item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
14562 This switch directs the compiler to implement the Ada 2012 version of the
14563 language (also the default).
14564 Since Ada 2012 is almost completely upwards
14565 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
14566 Ada 83 and Ada 95 programs
14567 may generally be compiled using this switch (see the description of the
14568 @code{-gnat83}, @code{-gnat95}, and @code{-gnat05/2005} switches
14569 for further information).
14572 @geindex -gnat2022 (gcc)
14574 @geindex Ada 2022 mode
14579 @item @code{-gnat2022} (Ada 2022 mode)
14581 This switch directs the compiler to implement the Ada 2022 version of the
14585 @geindex -gnatX0 (gcc)
14587 @geindex Ada language extensions
14589 @geindex GNAT extensions
14594 @item @code{-gnatX0} (Enable GNAT Extensions)
14596 This switch directs the compiler to implement the latest version of the
14597 language (currently Ada 2022) and also to enable certain GNAT implementation
14598 extensions that are not part of any Ada standard. For a full list of these
14599 extensions, see the GNAT reference manual, @code{Pragma Extensions_Allowed}.
14602 @geindex -gnatX (gcc)
14604 @geindex Ada language extensions
14606 @geindex GNAT extensions
14611 @item @code{-gnatX} (Enable core GNAT Extensions)
14613 This switch is similar to -gnatX0 except that only some, not all, of the
14614 GNAT-defined language extensions are enabled. For a list of the
14615 extensions enabled by this switch, see the GNAT reference manual
14616 @code{Pragma Extensions_Allowed} and the description of that pragma’s
14617 “On” (as opposed to “All”) argument.
14620 @node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14621 @anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{31}@anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{fd}
14622 @subsection Character Set Control
14625 @geindex -gnati (gcc)
14630 @item @code{-gnati`c'}
14632 Normally GNAT recognizes the Latin-1 character set in source program
14633 identifiers, as described in the Ada Reference Manual.
14635 GNAT to recognize alternate character sets in identifiers. @code{c} is a
14636 single character indicating the character set, as follows:
14639 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14646 ISO 8859-1 (Latin-1) identifiers
14654 ISO 8859-2 (Latin-2) letters allowed in identifiers
14662 ISO 8859-3 (Latin-3) letters allowed in identifiers
14670 ISO 8859-4 (Latin-4) letters allowed in identifiers
14678 ISO 8859-5 (Cyrillic) letters allowed in identifiers
14686 ISO 8859-15 (Latin-9) letters allowed in identifiers
14694 IBM PC letters (code page 437) allowed in identifiers
14702 IBM PC letters (code page 850) allowed in identifiers
14710 Full upper-half codes allowed in identifiers
14718 No upper-half codes allowed in identifiers
14726 Wide-character codes (that is, codes greater than 255)
14727 allowed in identifiers
14732 See @ref{23,,Foreign Language Representation} for full details on the
14733 implementation of these character sets.
14736 @geindex -gnatW (gcc)
14741 @item @code{-gnatW`e'}
14743 Specify the method of encoding for wide characters.
14744 @code{e} is one of the following:
14747 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14754 Hex encoding (brackets coding also recognized)
14762 Upper half encoding (brackets encoding also recognized)
14770 Shift/JIS encoding (brackets encoding also recognized)
14778 EUC encoding (brackets encoding also recognized)
14786 UTF-8 encoding (brackets encoding also recognized)
14794 Brackets encoding only (default value)
14799 For full details on these encoding
14800 methods see @ref{37,,Wide_Character Encodings}.
14801 Note that brackets coding is always accepted, even if one of the other
14802 options is specified, so for example @code{-gnatW8} specifies that both
14803 brackets and UTF-8 encodings will be recognized. The units that are
14804 with’ed directly or indirectly will be scanned using the specified
14805 representation scheme, and so if one of the non-brackets scheme is
14806 used, it must be used consistently throughout the program. However,
14807 since brackets encoding is always recognized, it may be conveniently
14808 used in standard libraries, allowing these libraries to be used with
14809 any of the available coding schemes.
14811 Note that brackets encoding only applies to program text. Within comments,
14812 brackets are considered to be normal graphic characters, and bracket sequences
14813 are never recognized as wide characters.
14815 If no @code{-gnatW?} parameter is present, then the default
14816 representation is normally Brackets encoding only. However, if the
14817 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14818 byte order mark or BOM for UTF-8), then these three characters are
14819 skipped and the default representation for the file is set to UTF-8.
14821 Note that the wide character representation that is specified (explicitly
14822 or by default) for the main program also acts as the default encoding used
14823 for Wide_Text_IO files if not specifically overridden by a WCEM form
14827 When no @code{-gnatW?} is specified, then characters (other than wide
14828 characters represented using brackets notation) are treated as 8-bit
14829 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14830 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14831 characters in the range 16#00#..16#1F# are not accepted in program text
14832 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14833 in program text, but allowed and ignored in comments. Note in particular
14834 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14835 as an end of line in this default mode. If your source program contains
14836 instances of the NEL character used as a line terminator,
14837 you must use UTF-8 encoding for the whole
14838 source program. In default mode, all lines must be ended by a standard
14839 end of line sequence (CR, CR/LF, or LF).
14841 Note that the convention of simply accepting all upper half characters in
14842 comments means that programs that use standard ASCII for program text, but
14843 UTF-8 encoding for comments are accepted in default mode, providing that the
14844 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14845 This is a common mode for many programs with foreign language comments.
14847 @node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14848 @anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{fe}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{ff}
14849 @subsection File Naming Control
14852 @geindex -gnatk (gcc)
14857 @item @code{-gnatk`n'}
14859 Activates file name ‘krunching’. @code{n}, a decimal integer in the range
14860 1-999, indicates the maximum allowable length of a file name (not
14861 including the @code{.ads} or @code{.adb} extension). The default is not
14862 to enable file name krunching.
14864 For the source file naming rules, @ref{3b,,File Naming Rules}.
14867 @node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14868 @anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{100}@anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{101}
14869 @subsection Subprogram Inlining Control
14872 @geindex -gnatn (gcc)
14877 @item @code{-gnatn[12]}
14879 The @code{n} here is intended to suggest the first syllable of the word ‘inline’.
14880 GNAT recognizes and processes @code{Inline} pragmas. However, for inlining to
14881 actually occur, optimization must be enabled and, by default, inlining of
14882 subprograms across units is not performed. If you want to additionally
14883 enable inlining of subprograms specified by pragma @code{Inline} across units,
14884 you must also specify this switch.
14886 In the absence of this switch, GNAT does not attempt inlining across units
14887 and does not access the bodies of subprograms for which @code{pragma Inline} is
14888 specified if they are not in the current unit.
14890 You can optionally specify the inlining level: 1 for moderate inlining across
14891 units, which is a good compromise between compilation times and performances
14892 at run time, or 2 for full inlining across units, which may bring about
14893 longer compilation times. If no inlining level is specified, the compiler will
14894 pick it based on the optimization level: 1 for @code{-O1}, @code{-O2} or
14895 @code{-Os} and 2 for @code{-O3}.
14897 If you specify this switch the compiler will access these bodies,
14898 creating an extra source dependency for the resulting object file, and
14899 where possible, the call will be inlined.
14900 For further details on when inlining is possible
14901 see @ref{102,,Inlining of Subprograms}.
14904 @geindex -gnatN (gcc)
14909 @item @code{-gnatN}
14911 This switch activates front-end inlining which also
14912 generates additional dependencies.
14914 When using a gcc-based back end, then the use of
14915 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
14916 Historically front end inlining was more extensive than the gcc back end
14917 inlining, but that is no longer the case.
14920 @node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14921 @anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{103}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{104}
14922 @subsection Auxiliary Output Control
14925 @geindex -gnatu (gcc)
14930 @item @code{-gnatu}
14932 Print a list of units required by this compilation on @code{stdout}.
14933 The listing includes all units on which the unit being compiled depends
14934 either directly or indirectly.
14937 @geindex -pass-exit-codes (gcc)
14942 @item @code{-pass-exit-codes}
14944 If this switch is not used, the exit code returned by @code{gcc} when
14945 compiling multiple files indicates whether all source files have
14946 been successfully used to generate object files or not.
14948 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
14949 exit status and allows an integrated development environment to better
14950 react to a compilation failure. Those exit status are:
14953 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14960 There was an error in at least one source file.
14968 At least one source file did not generate an object file.
14976 The compiler died unexpectedly (internal error for example).
14984 An object file has been generated for every source file.
14990 @node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
14991 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{105}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{106}
14992 @subsection Debugging Control
14997 @geindex Debugging options
15000 @geindex -gnatd (gcc)
15005 @item @code{-gnatd`x'}
15007 Activate internal debugging switches. @code{x} is a letter or digit, or
15008 string of letters or digits, which specifies the type of debugging
15009 outputs desired. Normally these are used only for internal development
15010 or system debugging purposes. You can find full documentation for these
15011 switches in the body of the @code{Debug} unit in the compiler source
15012 file @code{debug.adb}.
15015 @geindex -gnatG (gcc)
15020 @item @code{-gnatG[=`nn']}
15022 This switch causes the compiler to generate auxiliary output containing
15023 a pseudo-source listing of the generated expanded code. Like most Ada
15024 compilers, GNAT works by first transforming the high level Ada code into
15025 lower level constructs. For example, tasking operations are transformed
15026 into calls to the tasking run-time routines. A unique capability of GNAT
15027 is to list this expanded code in a form very close to normal Ada source.
15028 This is very useful in understanding the implications of various Ada
15029 usage on the efficiency of the generated code. There are many cases in
15030 Ada (e.g., the use of controlled types), where simple Ada statements can
15031 generate a lot of run-time code. By using @code{-gnatG} you can identify
15032 these cases, and consider whether it may be desirable to modify the coding
15033 approach to improve efficiency.
15035 The optional parameter @code{nn} if present after -gnatG specifies an
15036 alternative maximum line length that overrides the normal default of 72.
15037 This value is in the range 40-999999, values less than 40 being silently
15038 reset to 40. The equal sign is optional.
15040 The format of the output is very similar to standard Ada source, and is
15041 easily understood by an Ada programmer. The following special syntactic
15042 additions correspond to low level features used in the generated code that
15043 do not have any exact analogies in pure Ada source form. The following
15044 is a partial list of these special constructions. See the spec
15045 of package @code{Sprint} in file @code{sprint.ads} for a full list.
15047 @geindex -gnatL (gcc)
15049 If the switch @code{-gnatL} is used in conjunction with
15050 @code{-gnatG}, then the original source lines are interspersed
15051 in the expanded source (as comment lines with the original line number).
15056 @item @code{new @var{xxx} [storage_pool = @var{yyy}]}
15058 Shows the storage pool being used for an allocator.
15060 @item @code{at end @var{procedure-name};}
15062 Shows the finalization (cleanup) procedure for a scope.
15064 @item @code{(if @var{expr} then @var{expr} else @var{expr})}
15066 Conditional expression equivalent to the @code{x?y:z} construction in C.
15068 @item @code{@var{target}^(@var{source})}
15070 A conversion with floating-point truncation instead of rounding.
15072 @item @code{@var{target}?(@var{source})}
15074 A conversion that bypasses normal Ada semantic checking. In particular
15075 enumeration types and fixed-point types are treated simply as integers.
15077 @item @code{@var{target}?^(@var{source})}
15079 Combines the above two cases.
15082 @code{@var{x} #/ @var{y}}
15084 @code{@var{x} #mod @var{y}}
15086 @code{@var{x} # @var{y}}
15091 @item @code{@var{x} #rem @var{y}}
15093 A division or multiplication of fixed-point values which are treated as
15094 integers without any kind of scaling.
15096 @item @code{free @var{expr} [storage_pool = @var{xxx}]}
15098 Shows the storage pool associated with a @code{free} statement.
15100 @item @code{[subtype or type declaration]}
15102 Used to list an equivalent declaration for an internally generated
15103 type that is referenced elsewhere in the listing.
15105 @item @code{freeze @var{type-name} [@var{actions}]}
15107 Shows the point at which @code{type-name} is frozen, with possible
15108 associated actions to be performed at the freeze point.
15110 @item @code{reference @var{itype}}
15112 Reference (and hence definition) to internal type @code{itype}.
15114 @item @code{@var{function-name}! (@var{arg}, @var{arg}, @var{arg})}
15116 Intrinsic function call.
15118 @item @code{@var{label-name} : label}
15120 Declaration of label @code{labelname}.
15122 @item @code{#$ @var{subprogram-name}}
15124 An implicit call to a run-time support routine
15125 (to meet the requirement of H.3.1(9) in a
15126 convenient manner).
15128 @item @code{@var{expr} && @var{expr} && @var{expr} ... && @var{expr}}
15130 A multiple concatenation (same effect as @code{expr} & @code{expr} &
15131 @code{expr}, but handled more efficiently).
15133 @item @code{[constraint_error]}
15135 Raise the @code{Constraint_Error} exception.
15137 @item @code{@var{expression}'reference}
15139 A pointer to the result of evaluating @{expression@}.
15141 @item @code{@var{target-type}!(@var{source-expression})}
15143 An unchecked conversion of @code{source-expression} to @code{target-type}.
15145 @item @code{[@var{numerator}/@var{denominator}]}
15147 Used to represent internal real literals (that) have no exact
15148 representation in base 2-16 (for example, the result of compile time
15149 evaluation of the expression 1.0/27.0).
15153 @geindex -gnatD (gcc)
15158 @item @code{-gnatD[=nn]}
15160 When used in conjunction with @code{-gnatG}, this switch causes
15161 the expanded source, as described above for
15162 @code{-gnatG} to be written to files with names
15163 @code{xxx.dg}, where @code{xxx} is the normal file name,
15164 instead of to the standard output file. For
15165 example, if the source file name is @code{hello.adb}, then a file
15166 @code{hello.adb.dg} will be written. The debugging
15167 information generated by the @code{gcc} @code{-g} switch
15168 will refer to the generated @code{xxx.dg} file. This allows
15169 you to do source level debugging using the generated code which is
15170 sometimes useful for complex code, for example to find out exactly
15171 which part of a complex construction raised an exception. This switch
15172 also suppresses generation of cross-reference information (see
15173 @code{-gnatx}) since otherwise the cross-reference information
15174 would refer to the @code{.dg} file, which would cause
15175 confusion since this is not the original source file.
15177 Note that @code{-gnatD} actually implies @code{-gnatG}
15178 automatically, so it is not necessary to give both options.
15179 In other words @code{-gnatD} is equivalent to @code{-gnatDG}).
15181 @geindex -gnatL (gcc)
15183 If the switch @code{-gnatL} is used in conjunction with
15184 @code{-gnatDG}, then the original source lines are interspersed
15185 in the expanded source (as comment lines with the original line number).
15187 The optional parameter @code{nn} if present after -gnatD specifies an
15188 alternative maximum line length that overrides the normal default of 72.
15189 This value is in the range 40-999999, values less than 40 being silently
15190 reset to 40. The equal sign is optional.
15193 @geindex -gnatr (gcc)
15195 @geindex pragma Restrictions
15200 @item @code{-gnatr}
15202 This switch causes pragma Restrictions to be treated as Restriction_Warnings
15203 so that violation of restrictions causes warnings rather than illegalities.
15204 This is useful during the development process when new restrictions are added
15205 or investigated. The switch also causes pragma Profile to be treated as
15206 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
15207 restriction warnings rather than restrictions.
15210 @geindex -gnatR (gcc)
15215 @item @code{-gnatR[0|1|2|3|4][e][j][m][s]}
15217 This switch controls output from the compiler of a listing showing
15218 representation information for declared types, objects and subprograms.
15219 For @code{-gnatR0}, no information is output (equivalent to omitting
15220 the @code{-gnatR} switch). For @code{-gnatR1} (which is the default,
15221 so @code{-gnatR} with no parameter has the same effect), size and
15222 alignment information is listed for declared array and record types.
15224 For @code{-gnatR2}, size and alignment information is listed for all
15225 declared types and objects. The @code{Linker_Section} is also listed for any
15226 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
15227 latter case occurs for objects of a type for which a @code{Linker_Section}
15230 For @code{-gnatR3}, symbolic expressions for values that are computed
15231 at run time for records are included. These symbolic expressions have
15232 a mostly obvious format with #n being used to represent the value of the
15233 n’th discriminant. See source files @code{repinfo.ads/adb} in the
15234 GNAT sources for full details on the format of @code{-gnatR3} output.
15236 For @code{-gnatR4}, information for relevant compiler-generated types
15237 is also listed, i.e. when they are structurally part of other declared
15240 If the switch is followed by an @code{e} (e.g. @code{-gnatR2e}), then
15241 extended representation information for record sub-components of records
15244 If the switch is followed by an @code{m} (e.g. @code{-gnatRm}), then
15245 subprogram conventions and parameter passing mechanisms for all the
15246 subprograms are included.
15248 If the switch is followed by a @code{j} (e.g., @code{-gnatRj}), then
15249 the output is in the JSON data interchange format specified by the
15250 ECMA-404 standard. The semantic description of this JSON output is
15251 available in the specification of the Repinfo unit present in the
15254 If the switch is followed by an @code{s} (e.g., @code{-gnatR3s}), then
15255 the output is to a file with the name @code{file.rep} where @code{file} is
15256 the name of the corresponding source file, except if @code{j} is also
15257 specified, in which case the file name is @code{file.json}.
15259 Note that it is possible for record components to have zero size. In
15260 this case, the component clause uses an obvious extension of permitted
15261 Ada syntax, for example @code{at 0 range 0 .. -1}.
15264 @geindex -gnatS (gcc)
15269 @item @code{-gnatS}
15271 The use of the switch @code{-gnatS} for an
15272 Ada compilation will cause the compiler to output a
15273 representation of package Standard in a form very
15274 close to standard Ada. It is not quite possible to
15275 do this entirely in standard Ada (since new
15276 numeric base types cannot be created in standard
15277 Ada), but the output is easily
15278 readable to any Ada programmer, and is useful to
15279 determine the characteristics of target dependent
15280 types in package Standard.
15283 @geindex -gnatx (gcc)
15288 @item @code{-gnatx}
15290 Normally the compiler generates full cross-referencing information in
15291 the @code{ALI} file. This information is used by a number of tools.
15292 The @code{-gnatx} switch suppresses this information. This saves some space
15293 and may slightly speed up compilation, but means that tools depending
15294 on this information cannot be used.
15297 @geindex -fgnat-encodings (gcc)
15302 @item @code{-fgnat-encodings=[all|gdb|minimal]}
15304 This switch controls the balance between GNAT encodings and standard DWARF
15305 emitted in the debug information.
15307 Historically, old debug formats like stabs were not powerful enough to
15308 express some Ada types (for instance, variant records or fixed-point types).
15309 To work around this, GNAT introduced proprietary encodings that embed the
15310 missing information (“GNAT encodings”).
15312 Recent versions of the DWARF debug information format are now able to
15313 correctly describe most of these Ada constructs (“standard DWARF”). As
15314 third-party tools started to use this format, GNAT has been enhanced to
15315 generate it. However, most tools (including GDB) are still relying on GNAT
15318 To support all tools, GNAT needs to be versatile about the balance between
15319 generation of GNAT encodings and standard DWARF. This is what
15320 @code{-fgnat-encodings} is about.
15326 @code{=all}: Emit all GNAT encodings, and then emit as much standard DWARF as
15327 possible so it does not conflict with GNAT encodings.
15330 @code{=gdb}: Emit as much standard DWARF as possible as long as the current
15331 GDB handles it. Emit GNAT encodings for the rest.
15334 @code{=minimal}: Emit as much standard DWARF as possible and emit GNAT
15335 encodings for the rest.
15339 @node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
15340 @anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{107}@anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{108}
15341 @subsection Exception Handling Control
15344 GNAT uses two methods for handling exceptions at run time. The
15345 @code{setjmp/longjmp} method saves the context when entering
15346 a frame with an exception handler. Then when an exception is
15347 raised, the context can be restored immediately, without the
15348 need for tracing stack frames. This method provides very fast
15349 exception propagation, but introduces significant overhead for
15350 the use of exception handlers, even if no exception is raised.
15352 The other approach is called ‘zero cost’ exception handling.
15353 With this method, the compiler builds static tables to describe
15354 the exception ranges. No dynamic code is required when entering
15355 a frame containing an exception handler. When an exception is
15356 raised, the tables are used to control a back trace of the
15357 subprogram invocation stack to locate the required exception
15358 handler. This method has considerably poorer performance for
15359 the propagation of exceptions, but there is no overhead for
15360 exception handlers if no exception is raised. Note that in this
15361 mode and in the context of mixed Ada and C/C++ programming,
15362 to propagate an exception through a C/C++ code, the C/C++ code
15363 must be compiled with the @code{-funwind-tables} GCC’s
15366 The following switches may be used to control which of the
15367 two exception handling methods is used.
15369 @geindex --RTS=sjlj (gnatmake)
15374 @item @code{--RTS=sjlj}
15376 This switch causes the setjmp/longjmp run-time (when available) to be used
15377 for exception handling. If the default
15378 mechanism for the target is zero cost exceptions, then
15379 this switch can be used to modify this default, and must be
15380 used for all units in the partition.
15381 This option is rarely used. One case in which it may be
15382 advantageous is if you have an application where exception
15383 raising is common and the overall performance of the
15384 application is improved by favoring exception propagation.
15387 @geindex --RTS=zcx (gnatmake)
15389 @geindex Zero Cost Exceptions
15394 @item @code{--RTS=zcx}
15396 This switch causes the zero cost approach to be used
15397 for exception handling. If this is the default mechanism for the
15398 target (see below), then this switch is unneeded. If the default
15399 mechanism for the target is setjmp/longjmp exceptions, then
15400 this switch can be used to modify this default, and must be
15401 used for all units in the partition.
15402 This option can only be used if the zero cost approach
15403 is available for the target in use, otherwise it will generate an error.
15406 The same option @code{--RTS} must be used both for @code{gcc}
15407 and @code{gnatbind}. Passing this option to @code{gnatmake}
15408 (@ref{d0,,Switches for gnatmake}) will ensure the required consistency
15409 through the compilation and binding steps.
15411 @node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
15412 @anchor{gnat_ugn/building_executable_programs_with_gnat id29}@anchor{109}@anchor{gnat_ugn/building_executable_programs_with_gnat units-to-sources-mapping-files}@anchor{ea}
15413 @subsection Units to Sources Mapping Files
15416 @geindex -gnatem (gcc)
15421 @item @code{-gnatem=`path'}
15423 A mapping file is a way to communicate to the compiler two mappings:
15424 from unit names to file names (without any directory information) and from
15425 file names to path names (with full directory information). These mappings
15426 are used by the compiler to short-circuit the path search.
15428 The use of mapping files is not required for correct operation of the
15429 compiler, but mapping files can improve efficiency, particularly when
15430 sources are read over a slow network connection. In normal operation,
15431 you need not be concerned with the format or use of mapping files,
15432 and the @code{-gnatem} switch is not a switch that you would use
15433 explicitly. It is intended primarily for use by automatic tools such as
15434 @code{gnatmake} running under the project file facility. The
15435 description here of the format of mapping files is provided
15436 for completeness and for possible use by other tools.
15438 A mapping file is a sequence of sets of three lines. In each set, the
15439 first line is the unit name, in lower case, with @code{%s} appended
15440 for specs and @code{%b} appended for bodies; the second line is the
15441 file name; and the third line is the path name.
15448 /gnat/project1/sources/main.2.ada
15451 When the switch @code{-gnatem} is specified, the compiler will
15452 create in memory the two mappings from the specified file. If there is
15453 any problem (nonexistent file, truncated file or duplicate entries),
15454 no mapping will be created.
15456 Several @code{-gnatem} switches may be specified; however, only the
15457 last one on the command line will be taken into account.
15459 When using a project file, @code{gnatmake} creates a temporary
15460 mapping file and communicates it to the compiler using this switch.
15463 @node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
15464 @anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{10a}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{10b}
15465 @subsection Code Generation Control
15468 The GCC technology provides a wide range of target dependent
15469 @code{-m} switches for controlling
15470 details of code generation with respect to different versions of
15471 architectures. This includes variations in instruction sets (e.g.,
15472 different members of the power pc family), and different requirements
15473 for optimal arrangement of instructions (e.g., different members of
15474 the x86 family). The list of available @code{-m} switches may be
15475 found in the GCC documentation.
15477 Use of these @code{-m} switches may in some cases result in improved
15480 The GNAT technology is tested and qualified without any
15481 @code{-m} switches,
15482 so generally the most reliable approach is to avoid the use of these
15483 switches. However, we generally expect most of these switches to work
15484 successfully with GNAT, and many customers have reported successful
15485 use of these options.
15487 Our general advice is to avoid the use of @code{-m} switches unless
15488 special needs lead to requirements in this area. In particular,
15489 there is no point in using @code{-m} switches to improve performance
15490 unless you actually see a performance improvement.
15492 @node Linker Switches,Binding with gnatbind,Compiler Switches,Building Executable Programs with GNAT
15493 @anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{10c}@anchor{gnat_ugn/building_executable_programs_with_gnat linker-switches}@anchor{10d}
15494 @section Linker Switches
15497 Linker switches can be specified after @code{-largs} builder switch.
15499 @geindex -fuse-ld=name
15504 @item @code{-fuse-ld=`name'}
15506 Linker to be used. The default is @code{bfd} for @code{ld.bfd}; @code{gold}
15507 (for @code{ld.gold}) and @code{mold} (for @code{ld.mold}) are more
15508 recent and faster alternatives, but only available on GNU/Linux
15513 @node Binding with gnatbind,Linking with gnatlink,Linker Switches,Building Executable Programs with GNAT
15514 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{ca}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{10e}
15515 @section Binding with @code{gnatbind}
15520 This chapter describes the GNAT binder, @code{gnatbind}, which is used
15521 to bind compiled GNAT objects.
15523 The @code{gnatbind} program performs four separate functions:
15529 Checks that a program is consistent, in accordance with the rules in
15530 Chapter 10 of the Ada Reference Manual. In particular, error
15531 messages are generated if a program uses inconsistent versions of a
15535 Checks that an acceptable order of elaboration exists for the program
15536 and issues an error message if it cannot find an order of elaboration
15537 that satisfies the rules in Chapter 10 of the Ada Language Manual.
15540 Generates a main program incorporating the given elaboration order.
15541 This program is a small Ada package (body and spec) that
15542 must be subsequently compiled
15543 using the GNAT compiler. The necessary compilation step is usually
15544 performed automatically by @code{gnatlink}. The two most important
15545 functions of this program
15546 are to call the elaboration routines of units in an appropriate order
15547 and to call the main program.
15550 Determines the set of object files required by the given main program.
15551 This information is output in the forms of comments in the generated program,
15552 to be read by the @code{gnatlink} utility used to link the Ada application.
15556 * Running gnatbind::
15557 * Switches for gnatbind::
15558 * Command-Line Access::
15559 * Search Paths for gnatbind::
15560 * Examples of gnatbind Usage::
15564 @node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
15565 @anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{10f}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{110}
15566 @subsection Running @code{gnatbind}
15569 The form of the @code{gnatbind} command is
15572 $ gnatbind [ switches ] mainprog[.ali] [ switches ]
15575 where @code{mainprog.adb} is the Ada file containing the main program
15576 unit body. @code{gnatbind} constructs an Ada
15577 package in two files whose names are
15578 @code{b~mainprog.ads}, and @code{b~mainprog.adb}.
15579 For example, if given the
15580 parameter @code{hello.ali}, for a main program contained in file
15581 @code{hello.adb}, the binder output files would be @code{b~hello.ads}
15582 and @code{b~hello.adb}.
15584 When doing consistency checking, the binder takes into consideration
15585 any source files it can locate. For example, if the binder determines
15586 that the given main program requires the package @code{Pack}, whose
15588 file is @code{pack.ali} and whose corresponding source spec file is
15589 @code{pack.ads}, it attempts to locate the source file @code{pack.ads}
15590 (using the same search path conventions as previously described for the
15591 @code{gcc} command). If it can locate this source file, it checks that
15593 or source checksums of the source and its references to in @code{ALI} files
15594 match. In other words, any @code{ALI} files that mentions this spec must have
15595 resulted from compiling this version of the source file (or in the case
15596 where the source checksums match, a version close enough that the
15597 difference does not matter).
15599 @geindex Source files
15600 @geindex use by binder
15602 The effect of this consistency checking, which includes source files, is
15603 that the binder ensures that the program is consistent with the latest
15604 version of the source files that can be located at bind time. Editing a
15605 source file without compiling files that depend on the source file cause
15606 error messages to be generated by the binder.
15608 For example, suppose you have a main program @code{hello.adb} and a
15609 package @code{P}, from file @code{p.ads} and you perform the following
15616 Enter @code{gcc -c hello.adb} to compile the main program.
15619 Enter @code{gcc -c p.ads} to compile package @code{P}.
15622 Edit file @code{p.ads}.
15625 Enter @code{gnatbind hello}.
15628 At this point, the file @code{p.ali} contains an out-of-date time stamp
15629 because the file @code{p.ads} has been edited. The attempt at binding
15630 fails, and the binder generates the following error messages:
15633 error: "hello.adb" must be recompiled ("p.ads" has been modified)
15634 error: "p.ads" has been modified and must be recompiled
15637 Now both files must be recompiled as indicated, and then the bind can
15638 succeed, generating a main program. You need not normally be concerned
15639 with the contents of this file, but for reference purposes a sample
15640 binder output file is given in @ref{e,,Example of Binder Output File}.
15642 In most normal usage, the default mode of @code{gnatbind} which is to
15643 generate the main package in Ada, as described in the previous section.
15644 In particular, this means that any Ada programmer can read and understand
15645 the generated main program. It can also be debugged just like any other
15646 Ada code provided the @code{-g} switch is used for
15647 @code{gnatbind} and @code{gnatlink}.
15649 @node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
15650 @anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{111}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{112}
15651 @subsection Switches for @code{gnatbind}
15654 The following switches are available with @code{gnatbind}; details will
15655 be presented in subsequent sections.
15657 @geindex --version (gnatbind)
15662 @item @code{--version}
15664 Display Copyright and version, then exit disregarding all other options.
15667 @geindex --help (gnatbind)
15672 @item @code{--help}
15674 If @code{--version} was not used, display usage, then exit disregarding
15678 @geindex -a (gnatbind)
15685 Indicates that, if supported by the platform, the adainit procedure should
15686 be treated as an initialisation routine by the linker (a constructor). This
15687 is intended to be used by the Project Manager to automatically initialize
15688 shared Stand-Alone Libraries.
15691 @geindex -aO (gnatbind)
15698 Specify directory to be searched for ALI files.
15701 @geindex -aI (gnatbind)
15708 Specify directory to be searched for source file.
15711 @geindex -A (gnatbind)
15716 @item @code{-A[=`filename']}
15718 Output ALI list (to standard output or to the named file).
15721 @geindex -b (gnatbind)
15728 Generate brief messages to @code{stderr} even if verbose mode set.
15731 @geindex -c (gnatbind)
15738 Check only, no generation of binder output file.
15741 @geindex -dnn[k|m] (gnatbind)
15746 @item @code{-d`nn'[k|m]}
15748 This switch can be used to change the default task stack size value
15749 to a specified size @code{nn}, which is expressed in bytes by default, or
15750 in kilobytes when suffixed with @code{k} or in megabytes when suffixed
15752 In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15753 in effect, to completing all task specs with
15756 pragma Storage_Size (nn);
15759 When they do not already have such a pragma.
15762 @geindex -D (gnatbind)
15767 @item @code{-D`nn'[k|m]}
15769 Set the default secondary stack size to @code{nn}. The suffix indicates whether
15770 the size is in bytes (no suffix), kilobytes (@code{k} suffix) or megabytes
15773 The secondary stack holds objects of unconstrained types that are returned by
15774 functions, for example unconstrained Strings. The size of the secondary stack
15775 can be dynamic or fixed depending on the target.
15777 For most targets, the secondary stack grows on demand and is implemented as
15778 a chain of blocks in the heap. In this case, the default secondary stack size
15779 determines the initial size of the secondary stack for each task and the
15780 smallest amount the secondary stack can grow by.
15782 For Ravenscar, ZFP, and Cert run-times the size of the secondary stack is
15783 fixed. This switch can be used to change the default size of these stacks.
15784 The default secondary stack size can be overridden on a per-task basis if
15785 individual tasks have different secondary stack requirements. This is
15786 achieved through the Secondary_Stack_Size aspect that takes the size of the
15787 secondary stack in bytes.
15790 @geindex -e (gnatbind)
15797 Output complete list of elaboration-order dependencies.
15800 @geindex -Ea (gnatbind)
15807 Store tracebacks in exception occurrences when the target supports it.
15808 The “a” is for “address”; tracebacks will contain hexadecimal addresses,
15809 unless symbolic tracebacks are enabled.
15811 See also the packages @code{GNAT.Traceback} and
15812 @code{GNAT.Traceback.Symbolic} for more information.
15813 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
15817 @geindex -Es (gnatbind)
15824 Store tracebacks in exception occurrences when the target supports it.
15825 The “s” is for “symbolic”; symbolic tracebacks are enabled.
15828 @geindex -E (gnatbind)
15835 Currently the same as @code{-Ea}.
15838 @geindex -f (gnatbind)
15843 @item @code{-f`elab-order'}
15845 Force elaboration order. For further details see @ref{113,,Elaboration Control}
15846 and @ref{f,,Elaboration Order Handling in GNAT}.
15849 @geindex -F (gnatbind)
15856 Force the checks of elaboration flags. @code{gnatbind} does not normally
15857 generate checks of elaboration flags for the main executable, except when
15858 a Stand-Alone Library is used. However, there are cases when this cannot be
15859 detected by gnatbind. An example is importing an interface of a Stand-Alone
15860 Library through a pragma Import and only specifying through a linker switch
15861 this Stand-Alone Library. This switch is used to guarantee that elaboration
15862 flag checks are generated.
15865 @geindex -h (gnatbind)
15872 Output usage (help) information.
15875 @geindex -H (gnatbind)
15882 Legacy elaboration order model enabled. For further details see
15883 @ref{f,,Elaboration Order Handling in GNAT}.
15886 @geindex -H32 (gnatbind)
15893 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
15894 For further details see @ref{114,,Dynamic Allocation Control}.
15897 @geindex -H64 (gnatbind)
15899 @geindex __gnat_malloc
15906 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
15907 For further details see @ref{114,,Dynamic Allocation Control}.
15909 @geindex -I (gnatbind)
15913 Specify directory to be searched for source and ALI files.
15915 @geindex -I- (gnatbind)
15919 Do not look for sources in the current directory where @code{gnatbind} was
15920 invoked, and do not look for ALI files in the directory containing the
15921 ALI file named in the @code{gnatbind} command line.
15923 @geindex -k (gnatbind)
15927 Disable checking of elaboration flags. When using @code{-n}
15928 either explicitly or implicitly, @code{-F} is also implied,
15929 unless @code{-k} is used. This switch should be used with care
15930 and you should ensure manually that elaboration routines are not called
15931 twice unintentionally.
15933 @geindex -K (gnatbind)
15937 Give list of linker options specified for link.
15939 @geindex -l (gnatbind)
15943 Output chosen elaboration order.
15945 @geindex -L (gnatbind)
15947 @item @code{-L`xxx'}
15949 Bind the units for library building. In this case the @code{adainit} and
15950 @code{adafinal} procedures (@ref{a0,,Binding with Non-Ada Main Programs})
15951 are renamed to @code{@var{xxx}init} and
15952 @code{@var{xxx}final}.
15954 (@ref{2a,,GNAT and Libraries}, for more details.)
15956 @geindex -M (gnatbind)
15958 @item @code{-M`xyz'}
15960 Rename generated main program from main to xyz. This option is
15961 supported on cross environments only.
15963 @geindex -m (gnatbind)
15967 Limit number of detected errors or warnings to @code{n}, where @code{n} is
15968 in the range 1..999999. The default value if no switch is
15969 given is 9999. If the number of warnings reaches this limit, then a
15970 message is output and further warnings are suppressed, the bind
15971 continues in this case. If the number of errors reaches this
15972 limit, then a message is output and the bind is abandoned.
15973 A value of zero means that no limit is enforced. The equal
15976 @geindex -minimal (gnatbind)
15978 @item @code{-minimal}
15980 Generate a binder file suitable for space-constrained applications. When
15981 active, binder-generated objects not required for program operation are no
15982 longer generated. `Warning:' this option comes with the following
15989 Starting the program’s execution in the debugger will cause it to
15990 stop at the start of the @code{main} function instead of the main subprogram.
15991 This can be worked around by manually inserting a breakpoint on that
15992 subprogram and resuming the program’s execution until reaching that breakpoint.
15995 Programs using GNAT.Compiler_Version will not link.
15998 @geindex -n (gnatbind)
16004 @geindex -nostdinc (gnatbind)
16006 @item @code{-nostdinc}
16008 Do not look for sources in the system default directory.
16010 @geindex -nostdlib (gnatbind)
16012 @item @code{-nostdlib}
16014 Do not look for library files in the system default directory.
16016 @geindex --RTS (gnatbind)
16018 @item @code{--RTS=`rts-path'}
16020 Specifies the default location of the run-time library. Same meaning as the
16021 equivalent @code{gnatmake} flag (@ref{d0,,Switches for gnatmake}).
16023 @geindex -o (gnatbind)
16025 @item @code{-o `file'}
16027 Name the output file @code{file} (default is @code{b~`xxx}.adb`).
16028 Note that if this option is used, then linking must be done manually,
16029 gnatlink cannot be used.
16031 @geindex -O (gnatbind)
16033 @item @code{-O[=`filename']}
16035 Output object list (to standard output or to the named file).
16037 @geindex -p (gnatbind)
16041 Pessimistic (worst-case) elaboration order.
16043 @geindex -P (gnatbind)
16047 Generate binder file suitable for CodePeer.
16049 @geindex -R (gnatbind)
16053 Output closure source list, which includes all non-run-time units that are
16054 included in the bind.
16056 @geindex -Ra (gnatbind)
16060 Like @code{-R} but the list includes run-time units.
16062 @geindex -s (gnatbind)
16066 Require all source files to be present.
16068 @geindex -S (gnatbind)
16070 @item @code{-S`xxx'}
16072 Specifies the value to be used when detecting uninitialized scalar
16073 objects with pragma Initialize_Scalars.
16074 The @code{xxx} string specified with the switch is one of:
16080 @code{in} for an invalid value.
16082 If zero is invalid for the discrete type in question,
16083 then the scalar value is set to all zero bits.
16084 For signed discrete types, the largest possible negative value of
16085 the underlying scalar is set (i.e. a one bit followed by all zero bits).
16086 For unsigned discrete types, the underlying scalar value is set to all
16087 one bits. For floating-point types, a NaN value is set
16088 (see body of package System.Scalar_Values for exact values).
16091 @code{lo} for low value.
16093 If zero is invalid for the discrete type in question,
16094 then the scalar value is set to all zero bits.
16095 For signed discrete types, the largest possible negative value of
16096 the underlying scalar is set (i.e. a one bit followed by all zero bits).
16097 For unsigned discrete types, the underlying scalar value is set to all
16098 zero bits. For floating-point, a small value is set
16099 (see body of package System.Scalar_Values for exact values).
16102 @code{hi} for high value.
16104 If zero is invalid for the discrete type in question,
16105 then the scalar value is set to all one bits.
16106 For signed discrete types, the largest possible positive value of
16107 the underlying scalar is set (i.e. a zero bit followed by all one bits).
16108 For unsigned discrete types, the underlying scalar value is set to all
16109 one bits. For floating-point, a large value is set
16110 (see body of package System.Scalar_Values for exact values).
16113 @code{xx} for hex value (two hex digits).
16115 The underlying scalar is set to a value consisting of repeated bytes, whose
16116 value corresponds to the given value. For example if @code{BF} is given,
16117 then a 32-bit scalar value will be set to the bit pattern @code{16#BFBFBFBF#}.
16120 @geindex GNAT_INIT_SCALARS
16122 In addition, you can specify @code{-Sev} to indicate that the value is
16123 to be set at run time. In this case, the program will look for an environment
16124 variable of the form @code{GNAT_INIT_SCALARS=@var{yy}}, where @code{yy} is one
16125 of @code{in/lo/hi/@var{xx}} with the same meanings as above.
16126 If no environment variable is found, or if it does not have a valid value,
16127 then the default is @code{in} (invalid values).
16130 @geindex -static (gnatbind)
16135 @item @code{-static}
16137 Link against a static GNAT run-time.
16139 @geindex -shared (gnatbind)
16141 @item @code{-shared}
16143 Link against a shared GNAT run-time when available.
16145 @geindex -t (gnatbind)
16149 Tolerate time stamp and other consistency errors.
16151 @geindex -T (gnatbind)
16155 Set the time slice value to @code{n} milliseconds. If the system supports
16156 the specification of a specific time slice value, then the indicated value
16157 is used. If the system does not support specific time slice values, but
16158 does support some general notion of round-robin scheduling, then any
16159 nonzero value will activate round-robin scheduling.
16161 A value of zero is treated specially. It turns off time
16162 slicing, and in addition, indicates to the tasking run-time that the
16163 semantics should match as closely as possible the Annex D
16164 requirements of the Ada RM, and in particular sets the default
16165 scheduling policy to @code{FIFO_Within_Priorities}.
16167 @geindex -u (gnatbind)
16171 Enable dynamic stack usage, with @code{n} results stored and displayed
16172 at program termination. A result is generated when a task
16173 terminates. Results that can’t be stored are displayed on the fly, at
16174 task termination. This option is currently not supported on Itanium
16175 platforms. (See @ref{115,,Dynamic Stack Usage Analysis} for details.)
16177 @geindex -v (gnatbind)
16181 Verbose mode. Write error messages, header, summary output to
16184 @geindex -V (gnatbind)
16186 @item @code{-V`key'=`value'}
16188 Store the given association of @code{key} to @code{value} in the bind environment.
16189 Values stored this way can be retrieved at run time using
16190 @code{GNAT.Bind_Environment}.
16192 @geindex -w (gnatbind)
16196 Warning mode; @code{x} = s/e for suppress/treat as error.
16198 @geindex -Wx (gnatbind)
16200 @item @code{-Wx`e'}
16202 Override default wide character encoding for standard Text_IO files.
16204 @geindex -x (gnatbind)
16208 Exclude source files (check object consistency only).
16210 @geindex -xdr (gnatbind)
16214 Use the target-independent XDR protocol for stream oriented attributes
16215 instead of the default implementation which is based on direct binary
16216 representations and is therefore target-and endianness-dependent.
16217 However it does not support 128-bit integer types and the exception
16218 @code{Ada.IO_Exceptions.Device_Error} is raised if any attempt is made
16219 at streaming 128-bit integer types with it.
16221 @geindex -Xnnn (gnatbind)
16223 @item @code{-X`nnn'}
16225 Set default exit status value, normally 0 for POSIX compliance.
16227 @geindex -y (gnatbind)
16231 Enable leap seconds support in @code{Ada.Calendar} and its children.
16233 @geindex -z (gnatbind)
16237 No main subprogram.
16240 You may obtain this listing of switches by running @code{gnatbind} with
16244 * Consistency-Checking Modes::
16245 * Binder Error Message Control::
16246 * Elaboration Control::
16248 * Dynamic Allocation Control::
16249 * Binding with Non-Ada Main Programs::
16250 * Binding Programs with No Main Subprogram::
16254 @node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
16255 @anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{116}@anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{117}
16256 @subsubsection Consistency-Checking Modes
16259 As described earlier, by default @code{gnatbind} checks
16260 that object files are consistent with one another and are consistent
16261 with any source files it can locate. The following switches control binder
16266 @geindex -s (gnatbind)
16274 Require source files to be present. In this mode, the binder must be
16275 able to locate all source files that are referenced, in order to check
16276 their consistency. In normal mode, if a source file cannot be located it
16277 is simply ignored. If you specify this switch, a missing source
16280 @geindex -Wx (gnatbind)
16282 @item @code{-Wx`e'}
16284 Override default wide character encoding for standard Text_IO files.
16285 Normally the default wide character encoding method used for standard
16286 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
16287 the main source input (see description of switch
16288 @code{-gnatWx} for the compiler). The
16289 use of this switch for the binder (which has the same set of
16290 possible arguments) overrides this default as specified.
16292 @geindex -x (gnatbind)
16296 Exclude source files. In this mode, the binder only checks that ALI
16297 files are consistent with one another. Source files are not accessed.
16298 The binder runs faster in this mode, and there is still a guarantee that
16299 the resulting program is self-consistent.
16300 If a source file has been edited since it was last compiled, and you
16301 specify this switch, the binder will not detect that the object
16302 file is out of date with respect to the source file. Note that this is the
16303 mode that is automatically used by @code{gnatmake} because in this
16304 case the checking against sources has already been performed by
16305 @code{gnatmake} in the course of compilation (i.e., before binding).
16308 @node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
16309 @anchor{gnat_ugn/building_executable_programs_with_gnat binder-error-message-control}@anchor{118}@anchor{gnat_ugn/building_executable_programs_with_gnat id36}@anchor{119}
16310 @subsubsection Binder Error Message Control
16313 The following switches provide control over the generation of error
16314 messages from the binder:
16318 @geindex -v (gnatbind)
16326 Verbose mode. In the normal mode, brief error messages are generated to
16327 @code{stderr}. If this switch is present, a header is written
16328 to @code{stdout} and any error messages are directed to @code{stdout}.
16329 All that is written to @code{stderr} is a brief summary message.
16331 @geindex -b (gnatbind)
16335 Generate brief error messages to @code{stderr} even if verbose mode is
16336 specified. This is relevant only when used with the
16339 @geindex -m (gnatbind)
16343 Limits the number of error messages to @code{n}, a decimal integer in the
16344 range 1-999. The binder terminates immediately if this limit is reached.
16346 @geindex -M (gnatbind)
16348 @item @code{-M`xxx'}
16350 Renames the generated main program from @code{main} to @code{xxx}.
16351 This is useful in the case of some cross-building environments, where
16352 the actual main program is separate from the one generated
16353 by @code{gnatbind}.
16355 @geindex -ws (gnatbind)
16361 Suppress all warning messages.
16363 @geindex -we (gnatbind)
16367 Treat any warning messages as fatal errors.
16369 @geindex -t (gnatbind)
16371 @geindex Time stamp checks
16374 @geindex Binder consistency checks
16376 @geindex Consistency checks
16381 The binder performs a number of consistency checks including:
16387 Check that time stamps of a given source unit are consistent
16390 Check that checksums of a given source unit are consistent
16393 Check that consistent versions of @code{GNAT} were used for compilation
16396 Check consistency of configuration pragmas as required
16399 Normally failure of such checks, in accordance with the consistency
16400 requirements of the Ada Reference Manual, causes error messages to be
16401 generated which abort the binder and prevent the output of a binder
16402 file and subsequent link to obtain an executable.
16404 The @code{-t} switch converts these error messages
16405 into warnings, so that
16406 binding and linking can continue to completion even in the presence of such
16407 errors. The result may be a failed link (due to missing symbols), or a
16408 non-functional executable which has undefined semantics.
16412 This means that @code{-t} should be used only in unusual situations,
16418 @node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
16419 @anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{113}@anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{11a}
16420 @subsubsection Elaboration Control
16423 The following switches provide additional control over the elaboration
16424 order. For further details see @ref{f,,Elaboration Order Handling in GNAT}.
16426 @geindex -f (gnatbind)
16431 @item @code{-f`elab-order'}
16433 Force elaboration order.
16435 @code{elab-order} should be the name of a “forced elaboration order file”, that
16436 is, a text file containing library item names, one per line. A name of the
16437 form “some.unit%s” or “some.unit (spec)” denotes the spec of Some.Unit. A
16438 name of the form “some.unit%b” or “some.unit (body)” denotes the body of
16439 Some.Unit. Each pair of lines is taken to mean that there is an elaboration
16440 dependence of the second line on the first. For example, if the file
16450 then the spec of This will be elaborated before the body of This, and the
16451 body of This will be elaborated before the spec of That, and the spec of That
16452 will be elaborated before the body of That. The first and last of these three
16453 dependences are already required by Ada rules, so this file is really just
16454 forcing the body of This to be elaborated before the spec of That.
16456 The given order must be consistent with Ada rules, or else @code{gnatbind} will
16457 give elaboration cycle errors. For example, if you say x (body) should be
16458 elaborated before x (spec), there will be a cycle, because Ada rules require
16459 x (spec) to be elaborated before x (body); you can’t have the spec and body
16460 both elaborated before each other.
16462 If you later add “with That;” to the body of This, there will be a cycle, in
16463 which case you should erase either “this (body)” or “that (spec)” from the
16464 above forced elaboration order file.
16466 Blank lines and Ada-style comments are ignored. Unit names that do not exist
16467 in the program are ignored. Units in the GNAT predefined library are also
16471 @geindex -p (gnatbind)
16478 Pessimistic elaboration order
16480 This switch is only applicable to the pre-20.x legacy elaboration models.
16481 The post-20.x elaboration model uses a more informed approach of ordering
16484 Normally the binder attempts to choose an elaboration order that is likely to
16485 minimize the likelihood of an elaboration order error resulting in raising a
16486 @code{Program_Error} exception. This switch reverses the action of the binder,
16487 and requests that it deliberately choose an order that is likely to maximize
16488 the likelihood of an elaboration error. This is useful in ensuring
16489 portability and avoiding dependence on accidental fortuitous elaboration
16492 Normally it only makes sense to use the @code{-p} switch if dynamic
16493 elaboration checking is used (@code{-gnatE} switch used for compilation).
16494 This is because in the default static elaboration mode, all necessary
16495 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
16496 These implicit pragmas are still respected by the binder in @code{-p}
16497 mode, so a safe elaboration order is assured.
16499 Note that @code{-p} is not intended for production use; it is more for
16500 debugging/experimental use.
16503 @node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
16504 @anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{11b}@anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{11c}
16505 @subsubsection Output Control
16508 The following switches allow additional control over the output
16509 generated by the binder.
16513 @geindex -c (gnatbind)
16521 Check only. Do not generate the binder output file. In this mode the
16522 binder performs all error checks but does not generate an output file.
16524 @geindex -e (gnatbind)
16528 Output complete list of elaboration-order dependencies, showing the
16529 reason for each dependency. This output can be rather extensive but may
16530 be useful in diagnosing problems with elaboration order. The output is
16531 written to @code{stdout}.
16533 @geindex -h (gnatbind)
16537 Output usage information. The output is written to @code{stdout}.
16539 @geindex -K (gnatbind)
16543 Output linker options to @code{stdout}. Includes library search paths,
16544 contents of pragmas Ident and Linker_Options, and libraries added
16545 by @code{gnatbind}.
16547 @geindex -l (gnatbind)
16551 Output chosen elaboration order. The output is written to @code{stdout}.
16553 @geindex -O (gnatbind)
16557 Output full names of all the object files that must be linked to provide
16558 the Ada component of the program. The output is written to @code{stdout}.
16559 This list includes the files explicitly supplied and referenced by the user
16560 as well as implicitly referenced run-time unit files. The latter are
16561 omitted if the corresponding units reside in shared libraries. The
16562 directory names for the run-time units depend on the system configuration.
16564 @geindex -o (gnatbind)
16566 @item @code{-o `file'}
16568 Set name of output file to @code{file} instead of the normal
16569 @code{b~`mainprog}.adb` default. Note that @code{file} denote the Ada
16570 binder generated body filename.
16571 Note that if this option is used, then linking must be done manually.
16572 It is not possible to use gnatlink in this case, since it cannot locate
16575 @geindex -r (gnatbind)
16579 Generate list of @code{pragma Restrictions} that could be applied to
16580 the current unit. This is useful for code audit purposes, and also may
16581 be used to improve code generation in some cases.
16584 @node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
16585 @anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{114}@anchor{gnat_ugn/building_executable_programs_with_gnat id39}@anchor{11d}
16586 @subsubsection Dynamic Allocation Control
16589 The heap control switches – @code{-H32} and @code{-H64} –
16590 determine whether dynamic allocation uses 32-bit or 64-bit memory.
16591 They only affect compiler-generated allocations via @code{__gnat_malloc};
16592 explicit calls to @code{malloc} and related functions from the C
16593 run-time library are unaffected.
16600 Allocate memory on 32-bit heap
16604 Allocate memory on 64-bit heap. This is the default
16605 unless explicitly overridden by a @code{'Size} clause on the access type.
16608 These switches are only effective on VMS platforms.
16610 @node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
16611 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-non-ada-main-programs}@anchor{a0}@anchor{gnat_ugn/building_executable_programs_with_gnat id40}@anchor{11e}
16612 @subsubsection Binding with Non-Ada Main Programs
16615 The description so far has assumed that the main
16616 program is in Ada, and that the task of the binder is to generate a
16617 corresponding function @code{main} that invokes this Ada main
16618 program. GNAT also supports the building of executable programs where
16619 the main program is not in Ada, but some of the called routines are
16620 written in Ada and compiled using GNAT (@ref{2c,,Mixed Language Programming}).
16621 The following switch is used in this situation:
16625 @geindex -n (gnatbind)
16633 No main program. The main program is not in Ada.
16636 In this case, most of the functions of the binder are still required,
16637 but instead of generating a main program, the binder generates a file
16638 containing the following callable routines:
16647 @item @code{adainit}
16649 You must call this routine to initialize the Ada part of the program by
16650 calling the necessary elaboration routines. A call to @code{adainit} is
16651 required before the first call to an Ada subprogram.
16653 Note that it is assumed that the basic execution environment must be setup
16654 to be appropriate for Ada execution at the point where the first Ada
16655 subprogram is called. In particular, if the Ada code will do any
16656 floating-point operations, then the FPU must be setup in an appropriate
16657 manner. For the case of the x86, for example, full precision mode is
16658 required. The procedure GNAT.Float_Control.Reset may be used to ensure
16659 that the FPU is in the right state.
16667 @item @code{adafinal}
16669 You must call this routine to perform any library-level finalization
16670 required by the Ada subprograms. A call to @code{adafinal} is required
16671 after the last call to an Ada subprogram, and before the program
16676 @geindex -n (gnatbind)
16679 @geindex multiple input files
16681 If the @code{-n} switch
16682 is given, more than one ALI file may appear on
16683 the command line for @code{gnatbind}. The normal @code{closure}
16684 calculation is performed for each of the specified units. Calculating
16685 the closure means finding out the set of units involved by tracing
16686 `with' references. The reason it is necessary to be able to
16687 specify more than one ALI file is that a given program may invoke two or
16688 more quite separate groups of Ada units.
16690 The binder takes the name of its output file from the last specified ALI
16691 file, unless overridden by the use of the @code{-o file}.
16693 @geindex -o (gnatbind)
16695 The output is an Ada unit in source form that can be compiled with GNAT.
16696 This compilation occurs automatically as part of the @code{gnatlink}
16699 Currently the GNAT run-time requires a FPU using 80 bits mode
16700 precision. Under targets where this is not the default it is required to
16701 call GNAT.Float_Control.Reset before using floating point numbers (this
16702 include float computation, float input and output) in the Ada code. A
16703 side effect is that this could be the wrong mode for the foreign code
16704 where floating point computation could be broken after this call.
16706 @node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
16707 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-programs-with-no-main-subprogram}@anchor{11f}@anchor{gnat_ugn/building_executable_programs_with_gnat id41}@anchor{120}
16708 @subsubsection Binding Programs with No Main Subprogram
16711 It is possible to have an Ada program which does not have a main
16712 subprogram. This program will call the elaboration routines of all the
16713 packages, then the finalization routines.
16715 The following switch is used to bind programs organized in this manner:
16719 @geindex -z (gnatbind)
16727 Normally the binder checks that the unit name given on the command line
16728 corresponds to a suitable main subprogram. When this switch is used,
16729 a list of ALI files can be given, and the execution of the program
16730 consists of elaboration of these units in an appropriate order. Note
16731 that the default wide character encoding method for standard Text_IO
16732 files is always set to Brackets if this switch is set (you can use
16734 @code{-Wx} to override this default).
16737 @node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
16738 @anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{121}@anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{122}
16739 @subsection Command-Line Access
16742 The package @code{Ada.Command_Line} provides access to the command-line
16743 arguments and program name. In order for this interface to operate
16744 correctly, the two variables
16755 are declared in one of the GNAT library routines. These variables must
16756 be set from the actual @code{argc} and @code{argv} values passed to the
16757 main program. With no `n' present, @code{gnatbind}
16758 generates the C main program to automatically set these variables.
16759 If the `n' switch is used, there is no automatic way to
16760 set these variables. If they are not set, the procedures in
16761 @code{Ada.Command_Line} will not be available, and any attempt to use
16762 them will raise @code{Constraint_Error}. If command line access is
16763 required, your main program must set @code{gnat_argc} and
16764 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
16767 @node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
16768 @anchor{gnat_ugn/building_executable_programs_with_gnat id43}@anchor{123}@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-for-gnatbind}@anchor{76}
16769 @subsection Search Paths for @code{gnatbind}
16772 The binder takes the name of an ALI file as its argument and needs to
16773 locate source files as well as other ALI files to verify object consistency.
16775 For source files, it follows exactly the same search rules as @code{gcc}
16776 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
16777 directories searched are:
16783 The directory containing the ALI file named in the command line, unless
16784 the switch @code{-I-} is specified.
16787 All directories specified by @code{-I}
16788 switches on the @code{gnatbind}
16789 command line, in the order given.
16791 @geindex ADA_PRJ_OBJECTS_FILE
16794 Each of the directories listed in the text file whose name is given
16796 @geindex ADA_PRJ_OBJECTS_FILE
16797 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16798 @code{ADA_PRJ_OBJECTS_FILE} environment variable.
16800 @geindex ADA_PRJ_OBJECTS_FILE
16801 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16802 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
16803 driver when project files are used. It should not normally be set
16806 @geindex ADA_OBJECTS_PATH
16809 Each of the directories listed in the value of the
16810 @geindex ADA_OBJECTS_PATH
16811 @geindex environment variable; ADA_OBJECTS_PATH
16812 @code{ADA_OBJECTS_PATH} environment variable.
16813 Construct this value
16816 @geindex environment variable; PATH
16817 @code{PATH} environment variable: a list of directory
16818 names separated by colons (semicolons when working with the NT version
16822 The content of the @code{ada_object_path} file which is part of the GNAT
16823 installation tree and is used to store standard libraries such as the
16824 GNAT Run-Time Library (RTL) unless the switch @code{-nostdlib} is
16825 specified. See @ref{72,,Installing a library}
16828 @geindex -I (gnatbind)
16830 @geindex -aI (gnatbind)
16832 @geindex -aO (gnatbind)
16834 In the binder the switch @code{-I}
16835 is used to specify both source and
16836 library file paths. Use @code{-aI}
16837 instead if you want to specify
16838 source paths only, and @code{-aO}
16839 if you want to specify library paths
16840 only. This means that for the binder
16841 @code{-I`dir'} is equivalent to
16844 The binder generates the bind file (a C language source file) in the
16845 current working directory.
16851 @geindex Interfaces
16855 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
16856 children make up the GNAT Run-Time Library, together with the package
16857 GNAT and its children, which contain a set of useful additional
16858 library functions provided by GNAT. The sources for these units are
16859 needed by the compiler and are kept together in one directory. The ALI
16860 files and object files generated by compiling the RTL are needed by the
16861 binder and the linker and are kept together in one directory, typically
16862 different from the directory containing the sources. In a normal
16863 installation, you need not specify these directory names when compiling
16864 or binding. Either the environment variables or the built-in defaults
16865 cause these files to be found.
16867 Besides simplifying access to the RTL, a major use of search paths is
16868 in compiling sources from multiple directories. This can make
16869 development environments much more flexible.
16871 @node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16872 @anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatbind-usage}@anchor{124}@anchor{gnat_ugn/building_executable_programs_with_gnat id44}@anchor{125}
16873 @subsection Examples of @code{gnatbind} Usage
16876 Here are some examples of @code{gnatbind} invocations:
16884 The main program @code{Hello} (source program in @code{hello.adb}) is
16885 bound using the standard switch settings. The generated main program is
16886 @code{b~hello.adb}. This is the normal, default use of the binder.
16889 gnatbind hello -o mainprog.adb
16892 The main program @code{Hello} (source program in @code{hello.adb}) is
16893 bound using the standard switch settings. The generated main program is
16894 @code{mainprog.adb} with the associated spec in
16895 @code{mainprog.ads}. Note that you must specify the body here not the
16896 spec. Note that if this option is used, then linking must be done manually,
16897 since gnatlink will not be able to find the generated file.
16900 @node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16901 @anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{126}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{cb}
16902 @section Linking with @code{gnatlink}
16907 This chapter discusses @code{gnatlink}, a tool that links
16908 an Ada program and builds an executable file. This utility
16909 invokes the system linker (via the @code{gcc} command)
16910 with a correct list of object files and library references.
16911 @code{gnatlink} automatically determines the list of files and
16912 references for the Ada part of a program. It uses the binder file
16913 generated by the @code{gnatbind} to determine this list.
16916 * Running gnatlink::
16917 * Switches for gnatlink::
16921 @node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16922 @anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{127}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{128}
16923 @subsection Running @code{gnatlink}
16926 The form of the @code{gnatlink} command is
16929 $ gnatlink [ switches ] mainprog [.ali]
16930 [ non-Ada objects ] [ linker options ]
16933 The arguments of @code{gnatlink} (switches, main @code{ALI} file,
16935 or linker options) may be in any order, provided that no non-Ada object may
16936 be mistaken for a main @code{ALI} file.
16937 Any file name @code{F} without the @code{.ali}
16938 extension will be taken as the main @code{ALI} file if a file exists
16939 whose name is the concatenation of @code{F} and @code{.ali}.
16941 @code{mainprog.ali} references the ALI file of the main program.
16942 The @code{.ali} extension of this file can be omitted. From this
16943 reference, @code{gnatlink} locates the corresponding binder file
16944 @code{b~mainprog.adb} and, using the information in this file along
16945 with the list of non-Ada objects and linker options, constructs a
16946 linker command file to create the executable.
16948 The arguments other than the @code{gnatlink} switches and the main
16949 @code{ALI} file are passed to the linker uninterpreted.
16950 They typically include the names of
16951 object files for units written in other languages than Ada and any library
16952 references required to resolve references in any of these foreign language
16953 units, or in @code{Import} pragmas in any Ada units.
16955 @code{linker options} is an optional list of linker specific
16957 The default linker called by gnatlink is @code{gcc} which in
16958 turn calls the appropriate system linker.
16960 One useful option for the linker is @code{-s}: it reduces the size of the
16961 executable by removing all symbol table and relocation information from the
16964 Standard options for the linker such as @code{-lmy_lib} or
16965 @code{-Ldir} can be added as is.
16966 For options that are not recognized by
16967 @code{gcc} as linker options, use the @code{gcc} switches
16968 @code{-Xlinker} or @code{-Wl,}.
16970 Refer to the GCC documentation for
16973 Here is an example showing how to generate a linker map:
16976 $ gnatlink my_prog -Wl,-Map,MAPFILE
16979 Using @code{linker options} it is possible to set the program stack and
16981 See @ref{129,,Setting Stack Size from gnatlink} and
16982 @ref{12a,,Setting Heap Size from gnatlink}.
16984 @code{gnatlink} determines the list of objects required by the Ada
16985 program and prepends them to the list of objects passed to the linker.
16986 @code{gnatlink} also gathers any arguments set by the use of
16987 @code{pragma Linker_Options} and adds them to the list of arguments
16988 presented to the linker.
16990 @node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
16991 @anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{12b}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{12c}
16992 @subsection Switches for @code{gnatlink}
16995 The following switches are available with the @code{gnatlink} utility:
16997 @geindex --version (gnatlink)
17002 @item @code{--version}
17004 Display Copyright and version, then exit disregarding all other options.
17007 @geindex --help (gnatlink)
17012 @item @code{--help}
17014 If @code{--version} was not used, display usage, then exit disregarding
17018 @geindex Command line length
17020 @geindex -f (gnatlink)
17027 On some targets, the command line length is limited, and @code{gnatlink}
17028 will generate a separate file for the linker if the list of object files
17030 The @code{-f} switch forces this file
17031 to be generated even if
17032 the limit is not exceeded. This is useful in some cases to deal with
17033 special situations where the command line length is exceeded.
17036 @geindex Debugging information
17039 @geindex -g (gnatlink)
17046 The option to include debugging information causes the Ada bind file (in
17047 other words, @code{b~mainprog.adb}) to be compiled with @code{-g}.
17048 In addition, the binder does not delete the @code{b~mainprog.adb},
17049 @code{b~mainprog.o} and @code{b~mainprog.ali} files.
17050 Without @code{-g}, the binder removes these files by default.
17053 @geindex -n (gnatlink)
17060 Do not compile the file generated by the binder. This may be used when
17061 a link is rerun with different options, but there is no need to recompile
17065 @geindex -v (gnatlink)
17072 Verbose mode. Causes additional information to be output, including a full
17073 list of the included object files.
17074 This switch option is most useful when you want
17075 to see what set of object files are being used in the link step.
17078 @geindex -v -v (gnatlink)
17085 Very verbose mode. Requests that the compiler operate in verbose mode when
17086 it compiles the binder file, and that the system linker run in verbose mode.
17089 @geindex -o (gnatlink)
17094 @item @code{-o `exec-name'}
17096 @code{exec-name} specifies an alternate name for the generated
17097 executable program. If this switch is omitted, the executable has the same
17098 name as the main unit. For example, @code{gnatlink try.ali} creates
17099 an executable called @code{try}.
17102 @geindex -B (gnatlink)
17107 @item @code{-B`dir'}
17109 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
17110 from @code{dir} instead of the default location. Only use this switch
17111 when multiple versions of the GNAT compiler are available.
17112 See the @code{Directory Options} section in @cite{The_GNU_Compiler_Collection}
17113 for further details. You would normally use the @code{-b} or
17114 @code{-V} switch instead.
17117 @geindex -M (gnatlink)
17124 When linking an executable, create a map file. The name of the map file
17125 has the same name as the executable with extension “.map”.
17128 @geindex -M= (gnatlink)
17133 @item @code{-M=`mapfile'}
17135 When linking an executable, create a map file. The name of the map file is
17139 @geindex --GCC=compiler_name (gnatlink)
17144 @item @code{--GCC=`compiler_name'}
17146 Program used for compiling the binder file. The default is
17147 @code{gcc}. You need to use quotes around @code{compiler_name} if
17148 @code{compiler_name} contains spaces or other separator characters.
17149 As an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to
17150 use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
17151 inserted after your command name. Thus in the above example the compiler
17152 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
17153 A limitation of this syntax is that the name and path name of the executable
17154 itself must not include any embedded spaces. If the compiler executable is
17155 different from the default one (gcc or <prefix>-gcc), then the back-end
17156 switches in the ALI file are not used to compile the binder generated source.
17157 For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
17158 switches will be used for @code{--GCC="gcc -gnatv"}. If several
17159 @code{--GCC=compiler_name} are used, only the last @code{compiler_name}
17160 is taken into account. However, all the additional switches are also taken
17161 into account. Thus,
17162 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
17163 @code{--GCC="bar -x -y -z -t"}.
17166 @geindex --LINK= (gnatlink)
17171 @item @code{--LINK=`name'}
17173 @code{name} is the name of the linker to be invoked. This is especially
17174 useful in mixed language programs since languages such as C++ require
17175 their own linker to be used. When this switch is omitted, the default
17176 name for the linker is @code{gcc}. When this switch is used, the
17177 specified linker is called instead of @code{gcc} with exactly the same
17178 parameters that would have been passed to @code{gcc} so if the desired
17179 linker requires different parameters it is necessary to use a wrapper
17180 script that massages the parameters before invoking the real linker. It
17181 may be useful to control the exact invocation by using the verbose
17185 @node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
17186 @anchor{gnat_ugn/building_executable_programs_with_gnat id48}@anchor{12d}@anchor{gnat_ugn/building_executable_programs_with_gnat using-the-gnu-make-utility}@anchor{70}
17187 @section Using the GNU @code{make} Utility
17190 @geindex make (GNU)
17193 This chapter offers some examples of makefiles that solve specific
17194 problems. It does not explain how to write a makefile, nor does it try to replace the
17195 @code{gnatmake} utility (@ref{c8,,Building with gnatmake}).
17197 All the examples in this section are specific to the GNU version of
17198 make. Although @code{make} is a standard utility, and the basic language
17199 is the same, these examples use some advanced features found only in
17203 * Using gnatmake in a Makefile::
17204 * Automatically Creating a List of Directories::
17205 * Generating the Command Line Switches::
17206 * Overcoming Command Line Length Limits::
17210 @node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
17211 @anchor{gnat_ugn/building_executable_programs_with_gnat id49}@anchor{12e}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gnatmake-in-a-makefile}@anchor{12f}
17212 @subsection Using gnatmake in a Makefile
17215 @c index makefile (GNU make)
17217 Complex project organizations can be handled in a very powerful way by
17218 using GNU make combined with gnatmake. For instance, here is a Makefile
17219 which allows you to build each subsystem of a big project into a separate
17220 shared library. Such a makefile allows you to significantly reduce the link
17221 time of very big applications while maintaining full coherence at
17222 each step of the build process.
17224 The list of dependencies are handled automatically by
17225 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
17226 the appropriate directories.
17228 Note that you should also read the example on how to automatically
17229 create the list of directories
17230 (@ref{130,,Automatically Creating a List of Directories})
17231 which might help you in case your project has a lot of subdirectories.
17234 ## This Makefile is intended to be used with the following directory
17236 ## - The sources are split into a series of csc (computer software components)
17237 ## Each of these csc is put in its own directory.
17238 ## Their name are referenced by the directory names.
17239 ## They will be compiled into shared library (although this would also work
17240 ## with static libraries)
17241 ## - The main program (and possibly other packages that do not belong to any
17242 ## csc) is put in the top level directory (where the Makefile is).
17243 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
17244 ## \\_ second_csc (sources) __ lib (will contain the library)
17246 ## Although this Makefile is build for shared library, it is easy to modify
17247 ## to build partial link objects instead (modify the lines with -shared and
17250 ## With this makefile, you can change any file in the system or add any new
17251 ## file, and everything will be recompiled correctly (only the relevant shared
17252 ## objects will be recompiled, and the main program will be re-linked).
17254 # The list of computer software component for your project. This might be
17255 # generated automatically.
17258 # Name of the main program (no extension)
17261 # If we need to build objects with -fPIC, uncomment the following line
17264 # The following variable should give the directory containing libgnat.so
17265 # You can get this directory through 'gnatls -v'. This is usually the last
17266 # directory in the Object_Path.
17269 # The directories for the libraries
17270 # (This macro expands the list of CSC to the list of shared libraries, you
17271 # could simply use the expanded form:
17272 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17273 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17275 $@{MAIN@}: objects $@{LIB_DIR@}
17276 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17277 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17280 # recompile the sources
17281 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17283 # Note: In a future version of GNAT, the following commands will be simplified
17284 # by a new tool, gnatmlib
17286 mkdir -p $@{dir $@@ @}
17287 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17288 cd $@{dir $@@ @} && cp -f ../*.ali .
17290 # The dependencies for the modules
17291 # Note that we have to force the expansion of *.o, since in some cases
17292 # make won't be able to do it itself.
17293 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17294 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17295 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17297 # Make sure all of the shared libraries are in the path before starting the
17300 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17303 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17304 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17305 $@{RM@} $@{CSC_LIST:%=%/*.o@}
17306 $@{RM@} *.o *.ali $@{MAIN@}
17309 @node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
17310 @anchor{gnat_ugn/building_executable_programs_with_gnat automatically-creating-a-list-of-directories}@anchor{130}@anchor{gnat_ugn/building_executable_programs_with_gnat id50}@anchor{131}
17311 @subsection Automatically Creating a List of Directories
17314 In most makefiles, you will have to specify a list of directories, and
17315 store it in a variable. For small projects, it is often easier to
17316 specify each of them by hand, since you then have full control over what
17317 is the proper order for these directories, which ones should be
17320 However, in larger projects, which might involve hundreds of
17321 subdirectories, it might be more convenient to generate this list
17324 The example below presents two methods. The first one, although less
17325 general, gives you more control over the list. It involves wildcard
17326 characters, that are automatically expanded by @code{make}. Its
17327 shortcoming is that you need to explicitly specify some of the
17328 organization of your project, such as for instance the directory tree
17329 depth, whether some directories are found in a separate tree, etc.
17331 The second method is the most general one. It requires an external
17332 program, called @code{find}, which is standard on all Unix systems. All
17333 the directories found under a given root directory will be added to the
17337 # The examples below are based on the following directory hierarchy:
17338 # All the directories can contain any number of files
17339 # ROOT_DIRECTORY -> a -> aa -> aaa
17342 # -> b -> ba -> baa
17345 # This Makefile creates a variable called DIRS, that can be reused any time
17346 # you need this list (see the other examples in this section)
17348 # The root of your project's directory hierarchy
17352 # First method: specify explicitly the list of directories
17353 # This allows you to specify any subset of all the directories you need.
17356 DIRS := a/aa/ a/ab/ b/ba/
17359 # Second method: use wildcards
17360 # Note that the argument(s) to wildcard below should end with a '/'.
17361 # Since wildcards also return file names, we have to filter them out
17362 # to avoid duplicate directory names.
17363 # We thus use make's `@w{`}dir`@w{`} and `@w{`}sort`@w{`} functions.
17364 # It sets DIRs to the following value (note that the directories aaa and baa
17365 # are not given, unless you change the arguments to wildcard).
17366 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17369 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17370 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17373 # Third method: use an external program
17374 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17375 # This is the most complete command: it sets DIRs to the following value:
17376 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17379 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17382 @node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
17383 @anchor{gnat_ugn/building_executable_programs_with_gnat generating-the-command-line-switches}@anchor{132}@anchor{gnat_ugn/building_executable_programs_with_gnat id51}@anchor{133}
17384 @subsection Generating the Command Line Switches
17387 Once you have created the list of directories as explained in the
17388 previous section (@ref{130,,Automatically Creating a List of Directories}),
17389 you can easily generate the command line arguments to pass to gnatmake.
17391 For the sake of completeness, this example assumes that the source path
17392 is not the same as the object path, and that you have two separate lists
17396 # see "Automatically creating a list of directories" to create
17401 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17402 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17405 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17408 @node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
17409 @anchor{gnat_ugn/building_executable_programs_with_gnat id52}@anchor{134}@anchor{gnat_ugn/building_executable_programs_with_gnat overcoming-command-line-length-limits}@anchor{135}
17410 @subsection Overcoming Command Line Length Limits
17413 One problem that might be encountered on big projects is that many
17414 operating systems limit the length of the command line. It is thus hard to give
17415 gnatmake the list of source and object directories.
17417 This example shows how you can set up environment variables, which will
17418 make @code{gnatmake} behave exactly as if the directories had been
17419 specified on the command line, but have a much higher length limit (or
17420 even none on most systems).
17422 It assumes that you have created a list of directories in your Makefile,
17423 using one of the methods presented in
17424 @ref{130,,Automatically Creating a List of Directories}.
17425 For the sake of completeness, we assume that the object
17426 path (where the ALI files are found) is different from the sources patch.
17428 Note a small trick in the Makefile below: for efficiency reasons, we
17429 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17430 expanded immediately by @code{make}. This way we overcome the standard
17431 make behavior which is to expand the variables only when they are
17434 On Windows, if you are using the standard Windows command shell, you must
17435 replace colons with semicolons in the assignments to these variables.
17438 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17439 # This is the same thing as putting the -I arguments on the command line.
17440 # (the equivalent of using -aI on the command line would be to define
17441 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17442 # You can of course have different values for these variables.
17444 # Note also that we need to keep the previous values of these variables, since
17445 # they might have been set before running 'make' to specify where the GNAT
17446 # library is installed.
17448 # see "Automatically creating a list of directories" to create these
17454 space:=$@{empty@} $@{empty@}
17455 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17456 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17457 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17458 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17459 export ADA_INCLUDE_PATH
17460 export ADA_OBJECTS_PATH
17466 @node GNAT Utility Programs,GNAT and Program Execution,Building Executable Programs with GNAT,Top
17467 @anchor{gnat_ugn/gnat_utility_programs doc}@anchor{136}@anchor{gnat_ugn/gnat_utility_programs gnat-utility-programs}@anchor{b}@anchor{gnat_ugn/gnat_utility_programs id1}@anchor{137}
17468 @chapter GNAT Utility Programs
17471 This chapter describes a number of utility programs:
17478 @ref{138,,The File Cleanup Utility gnatclean}
17481 @ref{139,,The GNAT Library Browser gnatls}
17484 Other GNAT utilities are described elsewhere in this manual:
17490 @ref{42,,Handling Arbitrary File Naming Conventions with gnatname}
17493 @ref{4c,,File Name Krunching with gnatkr}
17496 @ref{1d,,Renaming Files with gnatchop}
17499 @ref{8f,,Preprocessing with gnatprep}
17503 * The File Cleanup Utility gnatclean::
17504 * The GNAT Library Browser gnatls::
17508 @node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
17509 @anchor{gnat_ugn/gnat_utility_programs id2}@anchor{13a}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{138}
17510 @section The File Cleanup Utility @code{gnatclean}
17513 @geindex File cleanup tool
17517 @code{gnatclean} is a tool that allows the deletion of files produced by the
17518 compiler, binder and linker, including ALI files, object files, tree files,
17519 expanded source files, library files, interface copy source files, binder
17520 generated files and executable files.
17523 * Running gnatclean::
17524 * Switches for gnatclean::
17528 @node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
17529 @anchor{gnat_ugn/gnat_utility_programs id3}@anchor{13b}@anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{13c}
17530 @subsection Running @code{gnatclean}
17533 The @code{gnatclean} command has the form:
17538 $ gnatclean switches names
17542 where @code{names} is a list of source file names. Suffixes @code{.ads} and
17543 @code{adb} may be omitted. If a project file is specified using switch
17544 @code{-P}, then @code{names} may be completely omitted.
17546 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17547 if switch @code{-c} is not specified, by the binder and
17548 the linker. In informative-only mode, specified by switch
17549 @code{-n}, the list of files that would have been deleted in
17550 normal mode is listed, but no file is actually deleted.
17552 @node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
17553 @anchor{gnat_ugn/gnat_utility_programs id4}@anchor{13d}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{13e}
17554 @subsection Switches for @code{gnatclean}
17557 @code{gnatclean} recognizes the following switches:
17559 @geindex --version (gnatclean)
17564 @item @code{--version}
17566 Display copyright and version, then exit disregarding all other options.
17569 @geindex --help (gnatclean)
17574 @item @code{--help}
17576 If @code{--version} was not used, display usage, then exit disregarding
17579 @item @code{--subdirs=`subdir'}
17581 Actual object directory of each project file is the subdirectory subdir of the
17582 object directory specified or defaulted in the project file.
17584 @item @code{--unchecked-shared-lib-imports}
17586 By default, shared library projects are not allowed to import static library
17587 projects. When this switch is used on the command line, this restriction is
17591 @geindex -c (gnatclean)
17598 Only attempt to delete the files produced by the compiler, not those produced
17599 by the binder or the linker. The files that are not to be deleted are library
17600 files, interface copy files, binder generated files and executable files.
17603 @geindex -D (gnatclean)
17608 @item @code{-D `dir'}
17610 Indicate that ALI and object files should normally be found in directory @code{dir}.
17613 @geindex -F (gnatclean)
17620 When using project files, if some errors or warnings are detected during
17621 parsing and verbose mode is not in effect (no use of switch
17622 -v), then error lines start with the full path name of the project
17623 file, rather than its simple file name.
17626 @geindex -h (gnatclean)
17633 Output a message explaining the usage of @code{gnatclean}.
17636 @geindex -n (gnatclean)
17643 Informative-only mode. Do not delete any files. Output the list of the files
17644 that would have been deleted if this switch was not specified.
17647 @geindex -P (gnatclean)
17652 @item @code{-P`project'}
17654 Use project file @code{project}. Only one such switch can be used.
17655 When cleaning a project file, the files produced by the compilation of the
17656 immediate sources or inherited sources of the project files are to be
17657 deleted. This is not depending on the presence or not of executable names
17658 on the command line.
17661 @geindex -q (gnatclean)
17668 Quiet output. If there are no errors, do not output anything, except in
17669 verbose mode (switch -v) or in informative-only mode
17673 @geindex -r (gnatclean)
17680 When a project file is specified (using switch -P),
17681 clean all imported and extended project files, recursively. If this switch
17682 is not specified, only the files related to the main project file are to be
17683 deleted. This switch has no effect if no project file is specified.
17686 @geindex -v (gnatclean)
17696 @geindex -vP (gnatclean)
17701 @item @code{-vP`x'}
17703 Indicates the verbosity of the parsing of GNAT project files.
17704 @ref{d1,,Switches Related to Project Files}.
17707 @geindex -X (gnatclean)
17712 @item @code{-X`name'=`value'}
17714 Indicates that external variable @code{name} has the value @code{value}.
17715 The Project Manager will use this value for occurrences of
17716 @code{external(name)} when parsing the project file.
17717 See @ref{d1,,Switches Related to Project Files}.
17720 @geindex -aO (gnatclean)
17725 @item @code{-aO`dir'}
17727 When searching for ALI and object files, look in directory @code{dir}.
17730 @geindex -I (gnatclean)
17735 @item @code{-I`dir'}
17737 Equivalent to @code{-aO`dir'}.
17740 @geindex -I- (gnatclean)
17742 @geindex Source files
17743 @geindex suppressing search
17750 Do not look for ALI or object files in the directory
17751 where @code{gnatclean} was invoked.
17754 @node The GNAT Library Browser gnatls,,The File Cleanup Utility gnatclean,GNAT Utility Programs
17755 @anchor{gnat_ugn/gnat_utility_programs id5}@anchor{13f}@anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{139}
17756 @section The GNAT Library Browser @code{gnatls}
17759 @geindex Library browser
17763 @code{gnatls} is a tool that outputs information about compiled
17764 units. It gives the relationship between objects, unit names and source
17765 files. It can also be used to check the source dependencies of a unit
17766 as well as various characteristics.
17770 * Switches for gnatls::
17771 * Example of gnatls Usage::
17775 @node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
17776 @anchor{gnat_ugn/gnat_utility_programs id6}@anchor{140}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{141}
17777 @subsection Running @code{gnatls}
17780 The @code{gnatls} command has the form
17785 $ gnatls switches object_or_ali_file
17789 The main argument is the list of object or @code{ali} files
17790 (see @ref{28,,The Ada Library Information Files})
17791 for which information is requested.
17793 In normal mode, without additional option, @code{gnatls} produces a
17794 four-column listing. Each line represents information for a specific
17795 object. The first column gives the full path of the object, the second
17796 column gives the name of the principal unit in this object, the third
17797 column gives the status of the source and the fourth column gives the
17798 full path of the source representing this unit.
17799 Here is a simple example of use:
17805 ./demo1.o demo1 DIF demo1.adb
17806 ./demo2.o demo2 OK demo2.adb
17807 ./hello.o h1 OK hello.adb
17808 ./instr-child.o instr.child MOK instr-child.adb
17809 ./instr.o instr OK instr.adb
17810 ./tef.o tef DIF tef.adb
17811 ./text_io_example.o text_io_example OK text_io_example.adb
17812 ./tgef.o tgef DIF tgef.adb
17816 The first line can be interpreted as follows: the main unit which is
17818 object file @code{demo1.o} is demo1, whose main source is in
17819 @code{demo1.adb}. Furthermore, the version of the source used for the
17820 compilation of demo1 has been modified (DIF). Each source file has a status
17821 qualifier which can be:
17826 @item `OK (unchanged)'
17828 The version of the source file used for the compilation of the
17829 specified unit corresponds exactly to the actual source file.
17831 @item `MOK (slightly modified)'
17833 The version of the source file used for the compilation of the
17834 specified unit differs from the actual source file but not enough to
17835 require recompilation. If you use gnatmake with the option
17836 @code{-m} (minimal recompilation), a file marked
17837 MOK will not be recompiled.
17839 @item `DIF (modified)'
17841 No version of the source found on the path corresponds to the source
17842 used to build this object.
17844 @item `??? (file not found)'
17846 No source file was found for this unit.
17848 @item `HID (hidden, unchanged version not first on PATH)'
17850 The version of the source that corresponds exactly to the source used
17851 for compilation has been found on the path but it is hidden by another
17852 version of the same source that has been modified.
17855 @node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
17856 @anchor{gnat_ugn/gnat_utility_programs id7}@anchor{142}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{143}
17857 @subsection Switches for @code{gnatls}
17860 @code{gnatls} recognizes the following switches:
17862 @geindex --version (gnatls)
17867 @item @code{--version}
17869 Display copyright and version, then exit disregarding all other options.
17872 @geindex --help (gnatls)
17877 @item @code{--help}
17879 If @code{--version} was not used, display usage, then exit disregarding
17883 @geindex -a (gnatls)
17890 Consider all units, including those of the predefined Ada library.
17891 Especially useful with @code{-d}.
17894 @geindex -d (gnatls)
17901 List sources from which specified units depend on.
17904 @geindex -h (gnatls)
17911 Output the list of options.
17914 @geindex -o (gnatls)
17921 Only output information about object files.
17924 @geindex -s (gnatls)
17931 Only output information about source files.
17934 @geindex -u (gnatls)
17941 Only output information about compilation units.
17944 @geindex -files (gnatls)
17949 @item @code{-files=`file'}
17951 Take as arguments the files listed in text file @code{file}.
17952 Text file @code{file} may contain empty lines that are ignored.
17953 Each nonempty line should contain the name of an existing file.
17954 Several such switches may be specified simultaneously.
17957 @geindex -aO (gnatls)
17959 @geindex -aI (gnatls)
17961 @geindex -I (gnatls)
17963 @geindex -I- (gnatls)
17968 @item @code{-aO`dir'}, @code{-aI`dir'}, @code{-I`dir'}, @code{-I-}, @code{-nostdinc}
17970 Source path manipulation. Same meaning as the equivalent @code{gnatmake}
17971 flags (@ref{d0,,Switches for gnatmake}).
17974 @geindex -aP (gnatls)
17979 @item @code{-aP`dir'}
17981 Add @code{dir} at the beginning of the project search dir.
17984 @geindex --RTS (gnatls)
17989 @item @code{--RTS=`rts-path'}
17991 Specifies the default location of the runtime library. Same meaning as the
17992 equivalent @code{gnatmake} flag (@ref{d0,,Switches for gnatmake}).
17995 @geindex -v (gnatls)
18002 Verbose mode. Output the complete source, object and project paths. Do not use
18003 the default column layout but instead use long format giving as much as
18004 information possible on each requested units, including special
18005 characteristics such as:
18011 `Preelaborable': The unit is preelaborable in the Ada sense.
18014 `No_Elab_Code': No elaboration code has been produced by the compiler for this unit.
18017 `Pure': The unit is pure in the Ada sense.
18020 `Elaborate_Body': The unit contains a pragma Elaborate_Body.
18023 `Remote_Types': The unit contains a pragma Remote_Types.
18026 `Shared_Passive': The unit contains a pragma Shared_Passive.
18029 `Predefined': This unit is part of the predefined environment and cannot be modified
18033 `Remote_Call_Interface': The unit contains a pragma Remote_Call_Interface.
18037 @node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
18038 @anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{144}@anchor{gnat_ugn/gnat_utility_programs id8}@anchor{145}
18039 @subsection Example of @code{gnatls} Usage
18042 Example of using the verbose switch. Note how the source and
18043 object paths are affected by the -I switch.
18048 $ gnatls -v -I.. demo1.o
18050 GNATLS 5.03w (20041123-34)
18051 Copyright 1997-2004 Free Software Foundation, Inc.
18053 Source Search Path:
18054 <Current_Directory>
18056 /home/comar/local/adainclude/
18058 Object Search Path:
18059 <Current_Directory>
18061 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18063 Project Search Path:
18064 <Current_Directory>
18065 /home/comar/local/lib/gnat/
18070 Kind => subprogram body
18071 Flags => No_Elab_Code
18072 Source => demo1.adb modified
18076 The following is an example of use of the dependency list.
18077 Note the use of the -s switch
18078 which gives a straight list of source files. This can be useful for
18079 building specialized scripts.
18084 $ gnatls -d demo2.o
18085 ./demo2.o demo2 OK demo2.adb
18091 $ gnatls -d -s -a demo1.o
18093 /home/comar/local/adainclude/ada.ads
18094 /home/comar/local/adainclude/a-finali.ads
18095 /home/comar/local/adainclude/a-filico.ads
18096 /home/comar/local/adainclude/a-stream.ads
18097 /home/comar/local/adainclude/a-tags.ads
18100 /home/comar/local/adainclude/gnat.ads
18101 /home/comar/local/adainclude/g-io.ads
18103 /home/comar/local/adainclude/system.ads
18104 /home/comar/local/adainclude/s-exctab.ads
18105 /home/comar/local/adainclude/s-finimp.ads
18106 /home/comar/local/adainclude/s-finroo.ads
18107 /home/comar/local/adainclude/s-secsta.ads
18108 /home/comar/local/adainclude/s-stalib.ads
18109 /home/comar/local/adainclude/s-stoele.ads
18110 /home/comar/local/adainclude/s-stratt.ads
18111 /home/comar/local/adainclude/s-tasoli.ads
18112 /home/comar/local/adainclude/s-unstyp.ads
18113 /home/comar/local/adainclude/unchconv.ads
18121 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
18123 @node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
18124 @anchor{gnat_ugn/gnat_and_program_execution doc}@anchor{146}@anchor{gnat_ugn/gnat_and_program_execution gnat-and-program-execution}@anchor{c}@anchor{gnat_ugn/gnat_and_program_execution id1}@anchor{147}
18125 @chapter GNAT and Program Execution
18128 This chapter covers several topics:
18134 @ref{148,,Running and Debugging Ada Programs}
18137 @ref{149,,Profiling}
18140 @ref{14a,,Improving Performance}
18143 @ref{14b,,Overflow Check Handling in GNAT}
18146 @ref{14c,,Performing Dimensionality Analysis in GNAT}
18149 @ref{14d,,Stack Related Facilities}
18152 @ref{14e,,Memory Management Issues}
18156 * Running and Debugging Ada Programs::
18158 * Improving Performance::
18159 * Overflow Check Handling in GNAT::
18160 * Performing Dimensionality Analysis in GNAT::
18161 * Stack Related Facilities::
18162 * Memory Management Issues::
18166 @node Running and Debugging Ada Programs,Profiling,,GNAT and Program Execution
18167 @anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{148}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{14f}
18168 @section Running and Debugging Ada Programs
18173 This section discusses how to debug Ada programs.
18175 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18181 The illegality may be a violation of the static semantics of Ada. In
18182 that case GNAT diagnoses the constructs in the program that are illegal.
18183 It is then a straightforward matter for the user to modify those parts of
18187 The illegality may be a violation of the dynamic semantics of Ada. In
18188 that case the program compiles and executes, but may generate incorrect
18189 results, or may terminate abnormally with some exception.
18192 When presented with a program that contains convoluted errors, GNAT
18193 itself may terminate abnormally without providing full diagnostics on
18194 the incorrect user program.
18202 * The GNAT Debugger GDB::
18204 * Introduction to GDB Commands::
18205 * Using Ada Expressions::
18206 * Calling User-Defined Subprograms::
18207 * Using the next Command in a Function::
18208 * Stopping When Ada Exceptions Are Raised::
18210 * Debugging Generic Units::
18211 * Remote Debugging with gdbserver::
18212 * GNAT Abnormal Termination or Failure to Terminate::
18213 * Naming Conventions for GNAT Source Files::
18214 * Getting Internal Debugging Information::
18215 * Stack Traceback::
18216 * Pretty-Printers for the GNAT runtime::
18220 @node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
18221 @anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{150}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{151}
18222 @subsection The GNAT Debugger GDB
18225 @code{GDB} is a general purpose, platform-independent debugger that
18226 can be used to debug mixed-language programs compiled with @code{gcc},
18227 and in particular is capable of debugging Ada programs compiled with
18228 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18229 complex Ada data structures.
18231 See @cite{Debugging with GDB},
18232 for full details on the usage of @code{GDB}, including a section on
18233 its usage on programs. This manual should be consulted for full
18234 details. The section that follows is a brief introduction to the
18235 philosophy and use of @code{GDB}.
18237 When GNAT programs are compiled, the compiler optionally writes debugging
18238 information into the generated object file, including information on
18239 line numbers, and on declared types and variables. This information is
18240 separate from the generated code. It makes the object files considerably
18241 larger, but it does not add to the size of the actual executable that
18242 will be loaded into memory, and has no impact on run-time performance. The
18243 generation of debug information is triggered by the use of the
18244 @code{-g} switch in the @code{gcc} or @code{gnatmake} command
18245 used to carry out the compilations. It is important to emphasize that
18246 the use of these options does not change the generated code.
18248 The debugging information is written in standard system formats that
18249 are used by many tools, including debuggers and profilers. The format
18250 of the information is typically designed to describe C types and
18251 semantics, but GNAT implements a translation scheme which allows full
18252 details about Ada types and variables to be encoded into these
18253 standard C formats. Details of this encoding scheme may be found in
18254 the file exp_dbug.ads in the GNAT source distribution. However, the
18255 details of this encoding are, in general, of no interest to a user,
18256 since @code{GDB} automatically performs the necessary decoding.
18258 When a program is bound and linked, the debugging information is
18259 collected from the object files, and stored in the executable image of
18260 the program. Again, this process significantly increases the size of
18261 the generated executable file, but it does not increase the size of
18262 the executable program itself. Furthermore, if this program is run in
18263 the normal manner, it runs exactly as if the debug information were
18264 not present, and takes no more actual memory.
18266 However, if the program is run under control of @code{GDB}, the
18267 debugger is activated. The image of the program is loaded, at which
18268 point it is ready to run. If a run command is given, then the program
18269 will run exactly as it would have if @code{GDB} were not present. This
18270 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
18271 entirely non-intrusive until a breakpoint is encountered. If no
18272 breakpoint is ever hit, the program will run exactly as it would if no
18273 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18274 the debugging information and can respond to user commands to inspect
18275 variables, and more generally to report on the state of execution.
18277 @node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
18278 @anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{152}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{153}
18279 @subsection Running GDB
18282 This section describes how to initiate the debugger.
18284 The debugger can be launched from a @code{GNAT Studio} menu or
18285 directly from the command line. The description below covers the latter use.
18286 All the commands shown can be used in the @code{GNAT Studio} debug console window,
18287 but there are usually more GUI-based ways to achieve the same effect.
18289 The command to run @code{GDB} is
18298 where @code{program} is the name of the executable file. This
18299 activates the debugger and results in a prompt for debugger commands.
18300 The simplest command is simply @code{run}, which causes the program to run
18301 exactly as if the debugger were not present. The following section
18302 describes some of the additional commands that can be given to @code{GDB}.
18304 @node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
18305 @anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{154}@anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{155}
18306 @subsection Introduction to GDB Commands
18309 @code{GDB} contains a large repertoire of commands.
18310 See @cite{Debugging with GDB} for extensive documentation on the use
18311 of these commands, together with examples of their use. Furthermore,
18312 the command `help' invoked from within GDB activates a simple help
18313 facility which summarizes the available commands and their options.
18314 In this section we summarize a few of the most commonly
18315 used commands to give an idea of what @code{GDB} is about. You should create
18316 a simple program with debugging information and experiment with the use of
18317 these @code{GDB} commands on the program as you read through the
18327 @item @code{set args @var{arguments}}
18329 The `arguments' list above is a list of arguments to be passed to
18330 the program on a subsequent run command, just as though the arguments
18331 had been entered on a normal invocation of the program. The @code{set args}
18332 command is not needed if the program does not require arguments.
18341 The @code{run} command causes execution of the program to start from
18342 the beginning. If the program is already running, that is to say if
18343 you are currently positioned at a breakpoint, then a prompt will ask
18344 for confirmation that you want to abandon the current execution and
18352 @item @code{breakpoint @var{location}}
18354 The breakpoint command sets a breakpoint, that is to say a point at which
18355 execution will halt and @code{GDB} will await further
18356 commands. `location' is
18357 either a line number within a file, given in the format @code{file:linenumber},
18358 or it is the name of a subprogram. If you request that a breakpoint be set on
18359 a subprogram that is overloaded, a prompt will ask you to specify on which of
18360 those subprograms you want to breakpoint. You can also
18361 specify that all of them should be breakpointed. If the program is run
18362 and execution encounters the breakpoint, then the program
18363 stops and @code{GDB} signals that the breakpoint was encountered by
18364 printing the line of code before which the program is halted.
18371 @item @code{catch exception @var{name}}
18373 This command causes the program execution to stop whenever exception
18374 @code{name} is raised. If @code{name} is omitted, then the execution is
18375 suspended when any exception is raised.
18382 @item @code{print @var{expression}}
18384 This will print the value of the given expression. Most simple
18385 Ada expression formats are properly handled by @code{GDB}, so the expression
18386 can contain function calls, variables, operators, and attribute references.
18393 @item @code{continue}
18395 Continues execution following a breakpoint, until the next breakpoint or the
18396 termination of the program.
18405 Executes a single line after a breakpoint. If the next statement
18406 is a subprogram call, execution continues into (the first statement of)
18407 the called subprogram.
18416 Executes a single line. If this line is a subprogram call, executes and
18417 returns from the call.
18426 Lists a few lines around the current source location. In practice, it
18427 is usually more convenient to have a separate edit window open with the
18428 relevant source file displayed. Successive applications of this command
18429 print subsequent lines. The command can be given an argument which is a
18430 line number, in which case it displays a few lines around the specified one.
18437 @item @code{backtrace}
18439 Displays a backtrace of the call chain. This command is typically
18440 used after a breakpoint has occurred, to examine the sequence of calls that
18441 leads to the current breakpoint. The display includes one line for each
18442 activation record (frame) corresponding to an active subprogram.
18451 At a breakpoint, @code{GDB} can display the values of variables local
18452 to the current frame. The command @code{up} can be used to
18453 examine the contents of other active frames, by moving the focus up
18454 the stack, that is to say from callee to caller, one frame at a time.
18463 Moves the focus of @code{GDB} down from the frame currently being
18464 examined to the frame of its callee (the reverse of the previous command),
18471 @item @code{frame @var{n}}
18473 Inspect the frame with the given number. The value 0 denotes the frame
18474 of the current breakpoint, that is to say the top of the call stack.
18483 Kills the child process in which the program is running under GDB.
18484 This may be useful for several purposes:
18490 It allows you to recompile and relink your program, since on many systems
18491 you cannot regenerate an executable file while it is running in a process.
18494 You can run your program outside the debugger, on systems that do not
18495 permit executing a program outside GDB while breakpoints are set
18499 It allows you to debug a core dump rather than a running process.
18504 The above list is a very short introduction to the commands that
18505 @code{GDB} provides. Important additional capabilities, including conditional
18506 breakpoints, the ability to execute command sequences on a breakpoint,
18507 the ability to debug at the machine instruction level and many other
18508 features are described in detail in @cite{Debugging with GDB}.
18509 Note that most commands can be abbreviated
18510 (for example, c for continue, bt for backtrace).
18512 @node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
18513 @anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{156}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{157}
18514 @subsection Using Ada Expressions
18517 @geindex Ada expressions (in gdb)
18519 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18520 extensions. The philosophy behind the design of this subset is
18528 That @code{GDB} should provide basic literals and access to operations for
18529 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18530 leaving more sophisticated computations to subprograms written into the
18531 program (which therefore may be called from @code{GDB}).
18534 That type safety and strict adherence to Ada language restrictions
18535 are not particularly relevant in a debugging context.
18538 That brevity is important to the @code{GDB} user.
18542 Thus, for brevity, the debugger acts as if there were
18543 implicit @code{with} and @code{use} clauses in effect for all user-written
18544 packages, thus making it unnecessary to fully qualify most names with
18545 their packages, regardless of context. Where this causes ambiguity,
18546 @code{GDB} asks the user’s intent.
18548 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
18550 @node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
18551 @anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{158}@anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{159}
18552 @subsection Calling User-Defined Subprograms
18555 An important capability of @code{GDB} is the ability to call user-defined
18556 subprograms while debugging. This is achieved simply by entering
18557 a subprogram call statement in the form:
18562 call subprogram-name (parameters)
18566 The keyword @code{call} can be omitted in the normal case where the
18567 @code{subprogram-name} does not coincide with any of the predefined
18568 @code{GDB} commands.
18570 The effect is to invoke the given subprogram, passing it the
18571 list of parameters that is supplied. The parameters can be expressions and
18572 can include variables from the program being debugged. The
18573 subprogram must be defined
18574 at the library level within your program, and @code{GDB} will call the
18575 subprogram within the environment of your program execution (which
18576 means that the subprogram is free to access or even modify variables
18577 within your program).
18579 The most important use of this facility is in allowing the inclusion of
18580 debugging routines that are tailored to particular data structures
18581 in your program. Such debugging routines can be written to provide a suitably
18582 high-level description of an abstract type, rather than a low-level dump
18583 of its physical layout. After all, the standard
18584 @code{GDB print} command only knows the physical layout of your
18585 types, not their abstract meaning. Debugging routines can provide information
18586 at the desired semantic level and are thus enormously useful.
18588 For example, when debugging GNAT itself, it is crucial to have access to
18589 the contents of the tree nodes used to represent the program internally.
18590 But tree nodes are represented simply by an integer value (which in turn
18591 is an index into a table of nodes).
18592 Using the @code{print} command on a tree node would simply print this integer
18593 value, which is not very useful. But the PN routine (defined in file
18594 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18595 a useful high level representation of the tree node, which includes the
18596 syntactic category of the node, its position in the source, the integers
18597 that denote descendant nodes and parent node, as well as varied
18598 semantic information. To study this example in more detail, you might want to
18599 look at the body of the PN procedure in the stated file.
18601 Another useful application of this capability is to deal with situations of
18602 complex data which are not handled suitably by GDB. For example, if you specify
18603 Convention Fortran for a multi-dimensional array, GDB does not know that
18604 the ordering of array elements has been switched and will not properly
18605 address the array elements. In such a case, instead of trying to print the
18606 elements directly from GDB, you can write a callable procedure that prints
18607 the elements in the desired format.
18609 @node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
18610 @anchor{gnat_ugn/gnat_and_program_execution id8}@anchor{15a}@anchor{gnat_ugn/gnat_and_program_execution using-the-next-command-in-a-function}@anchor{15b}
18611 @subsection Using the `next' Command in a Function
18614 When you use the @code{next} command in a function, the current source
18615 location will advance to the next statement as usual. A special case
18616 arises in the case of a @code{return} statement.
18618 Part of the code for a return statement is the ‘epilogue’ of the function.
18619 This is the code that returns to the caller. There is only one copy of
18620 this epilogue code, and it is typically associated with the last return
18621 statement in the function if there is more than one return. In some
18622 implementations, this epilogue is associated with the first statement
18625 The result is that if you use the @code{next} command from a return
18626 statement that is not the last return statement of the function you
18627 may see a strange apparent jump to the last return statement or to
18628 the start of the function. You should simply ignore this odd jump.
18629 The value returned is always that from the first return statement
18630 that was stepped through.
18632 @node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
18633 @anchor{gnat_ugn/gnat_and_program_execution id9}@anchor{15c}@anchor{gnat_ugn/gnat_and_program_execution stopping-when-ada-exceptions-are-raised}@anchor{15d}
18634 @subsection Stopping When Ada Exceptions Are Raised
18637 @geindex Exceptions (in gdb)
18639 You can set catchpoints that stop the program execution when your program
18640 raises selected exceptions.
18649 @item @code{catch exception}
18651 Set a catchpoint that stops execution whenever (any task in the) program
18652 raises any exception.
18659 @item @code{catch exception @var{name}}
18661 Set a catchpoint that stops execution whenever (any task in the) program
18662 raises the exception `name'.
18669 @item @code{catch exception unhandled}
18671 Set a catchpoint that stops executing whenever (any task in the) program
18672 raises an exception for which there is no handler.
18679 @item @code{info exceptions}, @code{info exceptions @var{regexp}}
18681 The @code{info exceptions} command permits the user to examine all defined
18682 exceptions within Ada programs. With a regular expression, `regexp', as
18683 argument, prints out only those exceptions whose name matches `regexp'.
18687 @geindex Tasks (in gdb)
18689 @node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
18690 @anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{15e}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{15f}
18691 @subsection Ada Tasks
18694 @code{GDB} allows the following task-related commands:
18703 @item @code{info tasks}
18705 This command shows a list of current Ada tasks, as in the following example:
18709 ID TID P-ID Thread Pri State Name
18710 1 8088000 0 807e000 15 Child Activation Wait main_task
18711 2 80a4000 1 80ae000 15 Accept/Select Wait b
18712 3 809a800 1 80a4800 15 Child Activation Wait a
18713 * 4 80ae800 3 80b8000 15 Running c
18716 In this listing, the asterisk before the first task indicates it to be the
18717 currently running task. The first column lists the task ID that is used
18718 to refer to tasks in the following commands.
18722 @geindex Breakpoints and tasks
18728 @code{break} `linespec' @code{task} `taskid', @code{break} `linespec' @code{task} `taskid' @code{if} …
18732 These commands are like the @code{break ... thread ...}.
18733 `linespec' specifies source lines.
18735 Use the qualifier @code{task @var{taskid}} with a breakpoint command
18736 to specify that you only want @code{GDB} to stop the program when a
18737 particular Ada task reaches this breakpoint. `taskid' is one of the
18738 numeric task identifiers assigned by @code{GDB}, shown in the first
18739 column of the @code{info tasks} display.
18741 If you do not specify @code{task @var{taskid}} when you set a
18742 breakpoint, the breakpoint applies to `all' tasks of your
18745 You can use the @code{task} qualifier on conditional breakpoints as
18746 well; in this case, place @code{task @var{taskid}} before the
18747 breakpoint condition (before the @code{if}).
18751 @geindex Task switching (in gdb)
18757 @code{task @var{taskno}}
18761 This command allows switching to the task referred by `taskno'. In
18762 particular, this allows browsing of the backtrace of the specified
18763 task. It is advisable to switch back to the original task before
18764 continuing execution otherwise the scheduling of the program may be
18769 For more detailed information on the tasking support,
18770 see @cite{Debugging with GDB}.
18772 @geindex Debugging Generic Units
18776 @node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
18777 @anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{160}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{161}
18778 @subsection Debugging Generic Units
18781 GNAT always uses code expansion for generic instantiation. This means that
18782 each time an instantiation occurs, a complete copy of the original code is
18783 made, with appropriate substitutions of formals by actuals.
18785 It is not possible to refer to the original generic entities in
18786 @code{GDB}, but it is always possible to debug a particular instance of
18787 a generic, by using the appropriate expanded names. For example, if we have
18794 generic package k is
18795 procedure kp (v1 : in out integer);
18799 procedure kp (v1 : in out integer) is
18805 package k1 is new k;
18806 package k2 is new k;
18808 var : integer := 1;
18819 Then to break on a call to procedure kp in the k2 instance, simply
18825 (gdb) break g.k2.kp
18829 When the breakpoint occurs, you can step through the code of the
18830 instance in the normal manner and examine the values of local variables, as for
18833 @geindex Remote Debugging with gdbserver
18835 @node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
18836 @anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{162}@anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{163}
18837 @subsection Remote Debugging with gdbserver
18840 On platforms where gdbserver is supported, it is possible to use this tool
18841 to debug your application remotely. This can be useful in situations
18842 where the program needs to be run on a target host that is different
18843 from the host used for development, particularly when the target has
18844 a limited amount of resources (either CPU and/or memory).
18846 To do so, start your program using gdbserver on the target machine.
18847 gdbserver then automatically suspends the execution of your program
18848 at its entry point, waiting for a debugger to connect to it. The
18849 following commands starts an application and tells gdbserver to
18850 wait for a connection with the debugger on localhost port 4444.
18855 $ gdbserver localhost:4444 program
18856 Process program created; pid = 5685
18857 Listening on port 4444
18861 Once gdbserver has started listening, we can tell the debugger to establish
18862 a connection with this gdbserver, and then start the same debugging session
18863 as if the program was being debugged on the same host, directly under
18864 the control of GDB.
18870 (gdb) target remote targethost:4444
18871 Remote debugging using targethost:4444
18872 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
18874 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
18878 Breakpoint 1, foo () at foo.adb:4
18883 It is also possible to use gdbserver to attach to an already running
18884 program, in which case the execution of that program is simply suspended
18885 until the connection between the debugger and gdbserver is established.
18887 For more information on how to use gdbserver, see the `Using the gdbserver Program'
18888 section in @cite{Debugging with GDB}.
18889 GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
18891 @geindex Abnormal Termination or Failure to Terminate
18893 @node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
18894 @anchor{gnat_ugn/gnat_and_program_execution gnat-abnormal-termination-or-failure-to-terminate}@anchor{164}@anchor{gnat_ugn/gnat_and_program_execution id13}@anchor{165}
18895 @subsection GNAT Abnormal Termination or Failure to Terminate
18898 When presented with programs that contain serious errors in syntax
18900 GNAT may on rare occasions experience problems in operation, such
18902 segmentation fault or illegal memory access, raising an internal
18903 exception, terminating abnormally, or failing to terminate at all.
18904 In such cases, you can activate
18905 various features of GNAT that can help you pinpoint the construct in your
18906 program that is the likely source of the problem.
18908 The following strategies are presented in increasing order of
18909 difficulty, corresponding to your experience in using GNAT and your
18910 familiarity with compiler internals.
18916 Run @code{gcc} with the @code{-gnatf}. This first
18917 switch causes all errors on a given line to be reported. In its absence,
18918 only the first error on a line is displayed.
18920 The @code{-gnatdO} switch causes errors to be displayed as soon as they
18921 are encountered, rather than after compilation is terminated. If GNAT
18922 terminates prematurely or goes into an infinite loop, the last error
18923 message displayed may help to pinpoint the culprit.
18926 Run @code{gcc} with the @code{-v} (verbose) switch. In this
18927 mode, @code{gcc} produces ongoing information about the progress of the
18928 compilation and provides the name of each procedure as code is
18929 generated. This switch allows you to find which Ada procedure was being
18930 compiled when it encountered a code generation problem.
18933 @geindex -gnatdc switch
18939 Run @code{gcc} with the @code{-gnatdc} switch. This is a GNAT specific
18940 switch that does for the front-end what @code{-v} does
18941 for the back end. The system prints the name of each unit,
18942 either a compilation unit or nested unit, as it is being analyzed.
18945 Finally, you can start
18946 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
18947 front-end of GNAT, and can be run independently (normally it is just
18948 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
18949 would on a C program (but @ref{151,,The GNAT Debugger GDB} for caveats). The
18950 @code{where} command is the first line of attack; the variable
18951 @code{lineno} (seen by @code{print lineno}), used by the second phase of
18952 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
18953 which the execution stopped, and @code{input_file name} indicates the name of
18957 @node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
18958 @anchor{gnat_ugn/gnat_and_program_execution id14}@anchor{166}@anchor{gnat_ugn/gnat_and_program_execution naming-conventions-for-gnat-source-files}@anchor{167}
18959 @subsection Naming Conventions for GNAT Source Files
18962 In order to examine the workings of the GNAT system, the following
18963 brief description of its organization may be helpful:
18969 Files with prefix @code{sc} contain the lexical scanner.
18972 All files prefixed with @code{par} are components of the parser. The
18973 numbers correspond to chapters of the Ada Reference Manual. For example,
18974 parsing of select statements can be found in @code{par-ch9.adb}.
18977 All files prefixed with @code{sem} perform semantic analysis. The
18978 numbers correspond to chapters of the Ada standard. For example, all
18979 issues involving context clauses can be found in @code{sem_ch10.adb}. In
18980 addition, some features of the language require sufficient special processing
18981 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
18982 dynamic dispatching, etc.
18985 All files prefixed with @code{exp} perform normalization and
18986 expansion of the intermediate representation (abstract syntax tree, or AST).
18987 these files use the same numbering scheme as the parser and semantics files.
18988 For example, the construction of record initialization procedures is done in
18989 @code{exp_ch3.adb}.
18992 The files prefixed with @code{bind} implement the binder, which
18993 verifies the consistency of the compilation, determines an order of
18994 elaboration, and generates the bind file.
18997 The files @code{atree.ads} and @code{atree.adb} detail the low-level
18998 data structures used by the front-end.
19001 The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
19002 the abstract syntax tree as produced by the parser.
19005 The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
19006 all entities, computed during semantic analysis.
19009 Library management issues are dealt with in files with prefix
19012 @geindex Annex A (in Ada Reference Manual)
19015 Ada files with the prefix @code{a-} are children of @code{Ada}, as
19016 defined in Annex A.
19018 @geindex Annex B (in Ada reference Manual)
19021 Files with prefix @code{i-} are children of @code{Interfaces}, as
19022 defined in Annex B.
19024 @geindex System (package in Ada Reference Manual)
19027 Files with prefix @code{s-} are children of @code{System}. This includes
19028 both language-defined children and GNAT run-time routines.
19030 @geindex GNAT (package)
19033 Files with prefix @code{g-} are children of @code{GNAT}. These are useful
19034 general-purpose packages, fully documented in their specs. All
19035 the other @code{.c} files are modifications of common @code{gcc} files.
19038 @node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
19039 @anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{168}@anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{169}
19040 @subsection Getting Internal Debugging Information
19043 Most compilers have internal debugging switches and modes. GNAT
19044 does also, except GNAT internal debugging switches and modes are not
19045 secret. A summary and full description of all the compiler and binder
19046 debug flags are in the file @code{debug.adb}. You must obtain the
19047 sources of the compiler to see the full detailed effects of these flags.
19049 The switches that print the source of the program (reconstructed from
19050 the internal tree) are of general interest for user programs, as are the
19052 the full internal tree, and the entity table (the symbol table
19053 information). The reconstructed source provides a readable version of the
19054 program after the front-end has completed analysis and expansion,
19055 and is useful when studying the performance of specific constructs.
19056 For example, constraint checks are indicated, complex aggregates
19057 are replaced with loops and assignments, and tasking primitives
19058 are replaced with run-time calls.
19062 @geindex stack traceback
19064 @geindex stack unwinding
19066 @node Stack Traceback,Pretty-Printers for the GNAT runtime,Getting Internal Debugging Information,Running and Debugging Ada Programs
19067 @anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{16a}@anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{16b}
19068 @subsection Stack Traceback
19071 Traceback is a mechanism to display the sequence of subprogram calls that
19072 leads to a specified execution point in a program. Often (but not always)
19073 the execution point is an instruction at which an exception has been raised.
19074 This mechanism is also known as `stack unwinding' because it obtains
19075 its information by scanning the run-time stack and recovering the activation
19076 records of all active subprograms. Stack unwinding is one of the most
19077 important tools for program debugging.
19079 The first entry stored in traceback corresponds to the deepest calling level,
19080 that is to say the subprogram currently executing the instruction
19081 from which we want to obtain the traceback.
19083 Note that there is no runtime performance penalty when stack traceback
19084 is enabled, and no exception is raised during program execution.
19087 @geindex non-symbolic
19090 * Non-Symbolic Traceback::
19091 * Symbolic Traceback::
19095 @node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
19096 @anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{16c}@anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{16d}
19097 @subsubsection Non-Symbolic Traceback
19100 Note: this feature is not supported on all platforms. See
19101 @code{GNAT.Traceback} spec in @code{g-traceb.ads}
19102 for a complete list of supported platforms.
19104 @subsubheading Tracebacks From an Unhandled Exception
19107 A runtime non-symbolic traceback is a list of addresses of call instructions.
19108 To enable this feature you must use the @code{-E} @code{gnatbind} option. With
19109 this option a stack traceback is stored as part of exception information.
19111 You can translate this information using the @code{addr2line} tool, provided that
19112 the program is compiled with debugging options (see @ref{dd,,Compiler Switches})
19113 and linked at a fixed position with @code{-no-pie}.
19115 Here is a simple example with @code{gnatmake}:
19124 raise Constraint_Error;
19138 $ gnatmake stb -g -bargs -E -largs -no-pie
19141 Execution of stb terminated by unhandled exception
19142 raised CONSTRAINT_ERROR : stb.adb:5 explicit raise
19143 Load address: 0x400000
19144 Call stack traceback locations:
19145 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19149 As we see the traceback lists a sequence of addresses for the unhandled
19150 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19151 guess that this exception come from procedure P1. To translate these
19152 addresses into the source lines where the calls appear, the @code{addr2line}
19153 tool needs to be invoked like this:
19158 $ addr2line -e stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19159 0x4011f1 0x77e892a4
19164 d:/stb/b~stb.adb:197
19171 The @code{addr2line} tool has several other useful options:
19176 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
19179 @code{-a --addresses}
19183 to show the addresses alongside the line numbers
19187 @code{-f --functions}
19191 to get the function name corresponding to a location
19195 @code{-p --pretty-print}
19199 to print all the information on a single line
19203 @code{--demangle=gnat}
19207 to use the GNAT decoding mode for the function names
19213 $ addr2line -e stb -a -f -p --demangle=gnat 0x401373 0x40138b
19214 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19216 0x00401373: stb.p1 at d:/stb/stb.adb:5
19217 0x0040138B: stb.p2 at d:/stb/stb.adb:10
19218 0x0040139C: stb at d:/stb/stb.adb:14
19219 0x00401335: main at d:/stb/b~stb.adb:197
19220 0x004011c4: ?? at crtexe.c:?
19221 0x004011f1: ?? at crtexe.c:?
19222 0x77e892a4: ?? ??:0
19226 From this traceback we can see that the exception was raised in @code{stb.adb}
19227 at line 5, which was reached from a procedure call in @code{stb.adb} at line
19228 10, and so on. The @code{b~std.adb} is the binder file, which contains the
19229 call to the main program. @ref{110,,Running gnatbind}. The remaining entries are
19230 assorted runtime routines and the output will vary from platform to platform.
19232 It is also possible to use @code{GDB} with these traceback addresses to debug
19233 the program. For example, we can break at a given code location, as reported
19234 in the stack traceback:
19239 (gdb) break *0x401373
19240 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19243 It is important to note that the stack traceback addresses do not change when
19244 debug information is included. This is particularly useful because it makes it
19245 possible to release software without debug information (to minimize object
19246 size), get a field report that includes a stack traceback whenever an internal
19247 bug occurs, and then be able to retrieve the sequence of calls with the same
19248 program compiled with debug information.
19250 However the @code{addr2line} tool does not work with Position-Independent Code
19251 (PIC), the historical example being Linux dynamic libraries and Windows DLLs,
19252 which nowadays encompasse Position-Independent Executables (PIE) on recent
19253 Linux and Windows versions.
19255 In order to translate addresses the source lines with Position-Independent
19256 Executables on recent Linux and Windows versions, in other words without
19257 using the switch @code{-no-pie} during linking, you need to use the
19258 @code{gnatsymbolize} tool with @code{--load} instead of the @code{addr2line}
19259 tool. The main difference is that you need to copy the Load Address output
19260 in the traceback ahead of the sequence of addresses. And the default mode
19261 of @code{gnatsymbolize} is equivalent to that of @code{addr2line} with the above
19262 switches, so none of them is needed:
19265 $ gnatmake stb -g -bargs -E
19268 Execution of stb terminated by unhandled exception
19269 raised CONSTRAINT_ERROR : stb.adb:5 explicit raise
19270 Load address: 0x400000
19271 Call stack traceback locations:
19272 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19274 $ gnatsymbolize --load stb 0x400000 0x401373 0x40138b 0x40139c 0x401335 \
19275 0x4011c4 0x4011f1 0x77e892a4
19277 0x00401373 Stb.P1 at stb.adb:5
19278 0x0040138B Stb.P2 at stb.adb:10
19279 0x0040139C Stb at stb.adb:14
19280 0x00401335 Main at b~stb.adb:197
19281 0x004011c4 __tmainCRTStartup at ???
19282 0x004011f1 mainCRTStartup at ???
19283 0x77e892a4 ??? at ???
19286 @subsubheading Tracebacks From Exception Occurrences
19289 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
19290 The stack traceback is attached to the exception information string, and can
19291 be retrieved in an exception handler within the Ada program, by means of the
19292 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19298 with Ada.Exceptions;
19303 use Ada.Exceptions;
19311 Text_IO.Put_Line (Exception_Information (E));
19325 $ gnatmake stb -g -bargs -E -largs -no-pie
19328 raised CONSTRAINT_ERROR : stb.adb:12 range check failed
19329 Load address: 0x400000
19330 Call stack traceback locations:
19331 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19335 @subsubheading Tracebacks From Anywhere in a Program
19338 It is also possible to retrieve a stack traceback from anywhere in a program.
19339 For this you need to use the @code{GNAT.Traceback} API. This package includes a
19340 procedure called @code{Call_Chain} that computes a complete stack traceback, as
19341 well as useful display procedures described below. It is not necessary to use
19342 the @code{-E} @code{gnatbind} option in this case, because the stack traceback
19343 mechanism is invoked explicitly.
19345 In the following example we compute a traceback at a specific location in the
19346 program, and we display it using @code{GNAT.Debug_Utilities.Image} to convert
19347 addresses to strings:
19353 with GNAT.Traceback;
19354 with GNAT.Debug_Utilities;
19362 use GNAT.Traceback;
19365 LA : constant Address := Executable_Load_Address;
19368 TB : Tracebacks_Array (1 .. 10);
19369 -- We are asking for a maximum of 10 stack frames.
19371 -- Len will receive the actual number of stack frames returned.
19373 Call_Chain (TB, Len);
19375 Put ("In STB.P1 : ");
19377 for K in 1 .. Len loop
19378 Put (Debug_Utilities.Image_C (TB (K)));
19391 if LA /= Null_Address then
19392 Put_Line ("Load address: " & Debug_Utilities.Image_C (LA));
19403 Load address: 0x400000
19404 In STB.P1 : 0x40F1E4 0x4014F2 0x40170B 0x40171C 0x401461 0x4011C4 \
19405 0x4011F1 0x77E892A4
19409 You can then get further information by invoking the @code{addr2line} tool or
19410 the @code{gnatsymbolize} tool as described earlier (note that the hexadecimal
19411 addresses need to be specified in C format, with a leading ‘0x’).
19416 @node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
19417 @anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{16e}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{16f}
19418 @subsubsection Symbolic Traceback
19421 A symbolic traceback is a stack traceback in which procedure names are
19422 associated with each code location.
19424 Note that this feature is not supported on all platforms. See
19425 @code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
19426 list of currently supported platforms.
19428 Note that the symbolic traceback requires that the program be compiled
19429 with debug information. If it is not compiled with debug information
19430 only the non-symbolic information will be valid.
19432 @subsubheading Tracebacks From Exception Occurrences
19435 Here is an example:
19441 with GNAT.Traceback.Symbolic;
19447 raise Constraint_Error;
19464 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19469 $ gnatmake -g stb -bargs -E
19472 0040149F in stb.p1 at stb.adb:8
19473 004014B7 in stb.p2 at stb.adb:13
19474 004014CF in stb.p3 at stb.adb:18
19475 004015DD in ada.stb at stb.adb:22
19476 00401461 in main at b~stb.adb:168
19477 004011C4 in __mingw_CRTStartup at crt1.c:200
19478 004011F1 in mainCRTStartup at crt1.c:222
19479 77E892A4 in ?? at ??:0
19483 @subsubheading Tracebacks From Anywhere in a Program
19486 It is possible to get a symbolic stack traceback
19487 from anywhere in a program, just as for non-symbolic tracebacks.
19488 The first step is to obtain a non-symbolic
19489 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19490 information. Here is an example:
19496 with GNAT.Traceback;
19497 with GNAT.Traceback.Symbolic;
19502 use GNAT.Traceback;
19503 use GNAT.Traceback.Symbolic;
19506 TB : Tracebacks_Array (1 .. 10);
19507 -- We are asking for a maximum of 10 stack frames.
19509 -- Len will receive the actual number of stack frames returned.
19511 Call_Chain (TB, Len);
19512 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19526 @subsubheading Automatic Symbolic Tracebacks
19529 Symbolic tracebacks may also be enabled by using the -Es switch to gnatbind (as
19530 in @code{gprbuild -g ... -bargs -Es}).
19531 This will cause the Exception_Information to contain a symbolic traceback,
19532 which will also be printed if an unhandled exception terminates the
19535 @node Pretty-Printers for the GNAT runtime,,Stack Traceback,Running and Debugging Ada Programs
19536 @anchor{gnat_ugn/gnat_and_program_execution id19}@anchor{170}@anchor{gnat_ugn/gnat_and_program_execution pretty-printers-for-the-gnat-runtime}@anchor{171}
19537 @subsection Pretty-Printers for the GNAT runtime
19540 As discussed in @cite{Calling User-Defined Subprograms}, GDB’s
19541 @code{print} command only knows about the physical layout of program data
19542 structures and therefore normally displays only low-level dumps, which
19543 are often hard to understand.
19545 An example of this is when trying to display the contents of an Ada
19546 standard container, such as @code{Ada.Containers.Ordered_Maps.Map}:
19551 with Ada.Containers.Ordered_Maps;
19554 package Int_To_Nat is
19555 new Ada.Containers.Ordered_Maps (Integer, Natural);
19557 Map : Int_To_Nat.Map;
19559 Map.Insert (1, 10);
19560 Map.Insert (2, 20);
19561 Map.Insert (3, 30);
19563 Map.Clear; -- BREAK HERE
19568 When this program is built with debugging information and run under
19569 GDB up to the @code{Map.Clear} statement, trying to print @code{Map} will
19570 yield information that is only relevant to the developers of our standard
19592 Fortunately, GDB has a feature called pretty-printers@footnote{http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Introduction},
19593 which allows customizing how GDB displays data structures. The GDB
19594 shipped with GNAT embeds such pretty-printers for the most common
19595 containers in the standard library. To enable them, either run the
19596 following command manually under GDB or add it to your @code{.gdbinit} file:
19601 python import gnatdbg; gnatdbg.setup()
19605 Once this is done, GDB’s @code{print} command will automatically use
19606 these pretty-printers when appropriate. Using the previous example:
19612 $1 = pp.int_to_nat.map of length 3 = @{
19620 Pretty-printers are invoked each time GDB tries to display a value,
19621 including when displaying the arguments of a called subprogram (in
19622 GDB’s @code{backtrace} command) or when printing the value returned by a
19623 function (in GDB’s @code{finish} command).
19625 To display a value without involving pretty-printers, @code{print} can be
19626 invoked with its @code{/r} option:
19637 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}
19638 for more information.
19642 @node Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
19643 @anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{172}@anchor{gnat_ugn/gnat_and_program_execution profiling}@anchor{149}
19647 This section describes how to use the @code{gprof} profiler tool on Ada programs.
19654 * Profiling an Ada Program with gprof::
19658 @node Profiling an Ada Program with gprof,,,Profiling
19659 @anchor{gnat_ugn/gnat_and_program_execution id21}@anchor{173}@anchor{gnat_ugn/gnat_and_program_execution profiling-an-ada-program-with-gprof}@anchor{174}
19660 @subsection Profiling an Ada Program with gprof
19663 This section is not meant to be an exhaustive documentation of @code{gprof}.
19664 Full documentation for it can be found in the @cite{GNU Profiler User’s Guide}
19665 documentation that is part of this GNAT distribution.
19667 Profiling a program helps determine the parts of a program that are executed
19668 most often, and are therefore the most time-consuming.
19670 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
19671 better handle Ada programs and multitasking.
19672 It is currently supported on the following platforms
19681 Windows x86/x86_64 (without PIE support)
19684 In order to profile a program using @code{gprof}, several steps are needed:
19690 Instrument the code, which requires a full recompilation of the project with the
19694 Execute the program under the analysis conditions, i.e. with the desired
19698 Analyze the results using the @code{gprof} tool.
19701 The following sections detail the different steps, and indicate how
19702 to interpret the results.
19705 * Compilation for profiling::
19706 * Program execution::
19708 * Interpretation of profiling results::
19712 @node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
19713 @anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{175}@anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{176}
19714 @subsubsection Compilation for profiling
19718 @geindex for profiling
19720 @geindex -pg (gnatlink)
19721 @geindex for profiling
19723 In order to profile a program the first step is to tell the compiler
19724 to generate the necessary profiling information. The compiler switch to be used
19725 is @code{-pg}, which must be added to other compilation switches. This
19726 switch needs to be specified both during compilation and link stages, and can
19727 be specified once when using gnatmake:
19732 $ gnatmake -f -pg -P my_project
19736 Note that only the objects that were compiled with the @code{-pg} switch will
19737 be profiled; if you need to profile your whole project, use the @code{-f}
19738 gnatmake switch to force full recompilation.
19740 Note that on Windows, gprof does not support PIE. The @code{-no-pie} switch
19741 should be added to the linker flags to disable this feature.
19743 @node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
19744 @anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{177}@anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{178}
19745 @subsubsection Program execution
19748 Once the program has been compiled for profiling, you can run it as usual.
19750 The only constraint imposed by profiling is that the program must terminate
19751 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
19754 Once the program completes execution, a data file called @code{gmon.out} is
19755 generated in the directory where the program was launched from. If this file
19756 already exists, it will be overwritten.
19758 @node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
19759 @anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{179}@anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{17a}
19760 @subsubsection Running gprof
19763 The @code{gprof} tool is called as follow:
19768 $ gprof my_prog gmon.out
19781 The complete form of the gprof command line is the following:
19786 $ gprof [switches] [executable [data-file]]
19790 @code{gprof} supports numerous switches. The order of these
19791 switch does not matter. The full list of options can be found in
19792 the GNU Profiler User’s Guide documentation that comes with this documentation.
19794 The following is the subset of those switches that is most relevant:
19796 @geindex --demangle (gprof)
19801 @item @code{--demangle[=@var{style}]}, @code{--no-demangle}
19803 These options control whether symbol names should be demangled when
19804 printing output. The default is to demangle C++ symbols. The
19805 @code{--no-demangle} option may be used to turn off demangling. Different
19806 compilers have different mangling styles. The optional demangling style
19807 argument can be used to choose an appropriate demangling style for your
19808 compiler, in particular Ada symbols generated by GNAT can be demangled using
19809 @code{--demangle=gnat}.
19812 @geindex -e (gprof)
19817 @item @code{-e @var{function_name}}
19819 The @code{-e @var{function}} option tells @code{gprof} not to print
19820 information about the function @code{function_name} (and its
19821 children…) in the call graph. The function will still be listed
19822 as a child of any functions that call it, but its index number will be
19823 shown as @code{[not printed]}. More than one @code{-e} option may be
19824 given; only one @code{function_name} may be indicated with each @code{-e}
19828 @geindex -E (gprof)
19833 @item @code{-E @var{function_name}}
19835 The @code{-E @var{function}} option works like the @code{-e} option, but
19836 execution time spent in the function (and children who were not called from
19837 anywhere else), will not be used to compute the percentages-of-time for
19838 the call graph. More than one @code{-E} option may be given; only one
19839 @code{function_name} may be indicated with each @code{-E`} option.
19842 @geindex -f (gprof)
19847 @item @code{-f @var{function_name}}
19849 The @code{-f @var{function}} option causes @code{gprof} to limit the
19850 call graph to the function @code{function_name} and its children (and
19851 their children…). More than one @code{-f} option may be given;
19852 only one @code{function_name} may be indicated with each @code{-f}
19856 @geindex -F (gprof)
19861 @item @code{-F @var{function_name}}
19863 The @code{-F @var{function}} option works like the @code{-f} option, but
19864 only time spent in the function and its children (and their
19865 children…) will be used to determine total-time and
19866 percentages-of-time for the call graph. More than one @code{-F} option
19867 may be given; only one @code{function_name} may be indicated with each
19868 @code{-F} option. The @code{-F} option overrides the @code{-E} option.
19871 @node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
19872 @anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{17b}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{17c}
19873 @subsubsection Interpretation of profiling results
19876 The results of the profiling analysis are represented by two arrays: the
19877 ‘flat profile’ and the ‘call graph’. Full documentation of those outputs
19878 can be found in the GNU Profiler User’s Guide.
19880 The flat profile shows the time spent in each function of the program, and how
19881 many time it has been called. This allows you to locate easily the most
19882 time-consuming functions.
19884 The call graph shows, for each subprogram, the subprograms that call it,
19885 and the subprograms that it calls. It also provides an estimate of the time
19886 spent in each of those callers/called subprograms.
19888 @node Improving Performance,Overflow Check Handling in GNAT,Profiling,GNAT and Program Execution
19889 @anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{14a}@anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{17d}
19890 @section Improving Performance
19893 @geindex Improving performance
19895 This section presents several topics related to program performance.
19896 It first describes some of the tradeoffs that need to be considered
19897 and some of the techniques for making your program run faster.
19899 It then documents the unused subprogram/data elimination feature,
19900 which can reduce the size of program executables.
19903 * Performance Considerations::
19904 * Text_IO Suggestions::
19905 * Reducing Size of Executables with Unused Subprogram/Data Elimination::
19909 @node Performance Considerations,Text_IO Suggestions,,Improving Performance
19910 @anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{17e}@anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{17f}
19911 @subsection Performance Considerations
19914 The GNAT system provides a number of options that allow a trade-off
19921 performance of the generated code
19924 speed of compilation
19927 minimization of dependences and recompilation
19930 the degree of run-time checking.
19933 The defaults (if no options are selected) aim at improving the speed
19934 of compilation and minimizing dependences, at the expense of performance
19935 of the generated code:
19944 no inlining of subprogram calls
19947 all run-time checks enabled except overflow and elaboration checks
19950 These options are suitable for most program development purposes. This
19951 section describes how you can modify these choices, and also provides
19952 some guidelines on debugging optimized code.
19955 * Controlling Run-Time Checks::
19956 * Use of Restrictions::
19957 * Optimization Levels::
19958 * Debugging Optimized Code::
19959 * Inlining of Subprograms::
19960 * Floating Point Operations::
19961 * Vectorization of loops::
19962 * Other Optimization Switches::
19963 * Optimization and Strict Aliasing::
19964 * Aliased Variables and Optimization::
19965 * Atomic Variables and Optimization::
19966 * Passive Task Optimization::
19970 @node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
19971 @anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{180}@anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{181}
19972 @subsubsection Controlling Run-Time Checks
19975 By default, GNAT generates all run-time checks, except stack overflow
19976 checks, and checks for access before elaboration on subprogram
19977 calls. The latter are not required in default mode, because all
19978 necessary checking is done at compile time.
19980 @geindex -gnatp (gcc)
19982 @geindex -gnato (gcc)
19984 The gnat switch, @code{-gnatp} allows this default to be modified. See
19985 @ref{ec,,Run-Time Checks}.
19987 Our experience is that the default is suitable for most development
19990 Elaboration checks are off by default, and also not needed by default, since
19991 GNAT uses a static elaboration analysis approach that avoids the need for
19992 run-time checking. This manual contains a full chapter discussing the issue
19993 of elaboration checks, and if the default is not satisfactory for your use,
19994 you should read this chapter.
19996 For validity checks, the minimal checks required by the Ada Reference
19997 Manual (for case statements and assignments to array elements) are on
19998 by default. These can be suppressed by use of the @code{-gnatVn} switch.
19999 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
20000 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
20001 it may be reasonable to routinely use @code{-gnatVn}. Validity checks
20002 are also suppressed entirely if @code{-gnatp} is used.
20004 @geindex Overflow checks
20011 @geindex Unsuppress
20013 @geindex pragma Suppress
20015 @geindex pragma Unsuppress
20017 Note that the setting of the switches controls the default setting of
20018 the checks. They may be modified using either @code{pragma Suppress} (to
20019 remove checks) or @code{pragma Unsuppress} (to add back suppressed
20020 checks) in the program source.
20022 @node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
20023 @anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{182}@anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{183}
20024 @subsubsection Use of Restrictions
20027 The use of pragma Restrictions allows you to control which features are
20028 permitted in your program. Apart from the obvious point that if you avoid
20029 relatively expensive features like finalization (enforceable by the use
20030 of pragma Restrictions (No_Finalization)), the use of this pragma does not
20031 affect the generated code in most cases.
20033 One notable exception to this rule is that the possibility of task abort
20034 results in some distributed overhead, particularly if finalization or
20035 exception handlers are used. The reason is that certain sections of code
20036 have to be marked as non-abortable.
20038 If you use neither the @code{abort} statement, nor asynchronous transfer
20039 of control (@code{select ... then abort}), then this distributed overhead
20040 is removed, which may have a general positive effect in improving
20041 overall performance. Especially code involving frequent use of tasking
20042 constructs and controlled types will show much improved performance.
20043 The relevant restrictions pragmas are
20048 pragma Restrictions (No_Abort_Statements);
20049 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
20053 It is recommended that these restriction pragmas be used if possible. Note
20054 that this also means that you can write code without worrying about the
20055 possibility of an immediate abort at any point.
20057 @node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
20058 @anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{184}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{ef}
20059 @subsubsection Optimization Levels
20064 Without any optimization option,
20065 the compiler’s goal is to reduce the cost of
20066 compilation and to make debugging produce the expected results.
20067 Statements are independent: if you stop the program with a breakpoint between
20068 statements, you can then assign a new value to any variable or change
20069 the program counter to any other statement in the subprogram and get exactly
20070 the results you would expect from the source code.
20072 Turning on optimization makes the compiler attempt to improve the
20073 performance and/or code size at the expense of compilation time and
20074 possibly the ability to debug the program.
20076 If you use multiple
20077 -O options, with or without level numbers,
20078 the last such option is the one that is effective.
20080 The default is optimization off. This results in the fastest compile
20081 times, but GNAT makes absolutely no attempt to optimize, and the
20082 generated programs are considerably larger and slower than when
20083 optimization is enabled. You can use the
20084 @code{-O} switch (the permitted forms are @code{-O0}, @code{-O1}
20085 @code{-O2}, @code{-O3}, and @code{-Os})
20086 to @code{gcc} to control the optimization level:
20097 No optimization (the default);
20098 generates unoptimized code but has
20099 the fastest compilation time.
20101 Note that many other compilers do substantial optimization even
20102 if ‘no optimization’ is specified. With gcc, it is very unusual
20103 to use @code{-O0} for production if execution time is of any concern,
20104 since @code{-O0} means (almost) no optimization. This difference
20105 between gcc and other compilers should be kept in mind when
20106 doing performance comparisons.
20115 Moderate optimization;
20116 optimizes reasonably well but does not
20117 degrade compilation time significantly.
20127 generates highly optimized code and has
20128 the slowest compilation time.
20137 Full optimization as in @code{-O2};
20138 also uses more aggressive automatic inlining of subprograms within a unit
20139 (@ref{102,,Inlining of Subprograms}) and attempts to vectorize loops.
20148 Optimize space usage (code and data) of resulting program.
20152 Higher optimization levels perform more global transformations on the
20153 program and apply more expensive analysis algorithms in order to generate
20154 faster and more compact code. The price in compilation time, and the
20155 resulting improvement in execution time,
20156 both depend on the particular application and the hardware environment.
20157 You should experiment to find the best level for your application.
20159 Since the precise set of optimizations done at each level will vary from
20160 release to release (and sometime from target to target), it is best to think
20161 of the optimization settings in general terms.
20162 See the `Options That Control Optimization' section in
20163 @cite{Using the GNU Compiler Collection (GCC)}
20165 the @code{-O} settings and a number of @code{-f} options that
20166 individually enable or disable specific optimizations.
20168 Unlike some other compilation systems, @code{gcc} has
20169 been tested extensively at all optimization levels. There are some bugs
20170 which appear only with optimization turned on, but there have also been
20171 bugs which show up only in `unoptimized' code. Selecting a lower
20172 level of optimization does not improve the reliability of the code
20173 generator, which in practice is highly reliable at all optimization
20176 Note regarding the use of @code{-O3}: The use of this optimization level
20177 ought not to be automatically preferred over that of level @code{-O2},
20178 since it often results in larger executables which may run more slowly.
20179 See further discussion of this point in @ref{102,,Inlining of Subprograms}.
20181 @node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
20182 @anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{185}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{186}
20183 @subsubsection Debugging Optimized Code
20186 @geindex Debugging optimized code
20188 @geindex Optimization and debugging
20190 Although it is possible to do a reasonable amount of debugging at
20191 nonzero optimization levels,
20192 the higher the level the more likely that
20193 source-level constructs will have been eliminated by optimization.
20194 For example, if a loop is strength-reduced, the loop
20195 control variable may be completely eliminated and thus cannot be
20196 displayed in the debugger.
20197 This can only happen at @code{-O2} or @code{-O3}.
20198 Explicit temporary variables that you code might be eliminated at
20199 level @code{-O1} or higher.
20203 The use of the @code{-g} switch,
20204 which is needed for source-level debugging,
20205 affects the size of the program executable on disk,
20206 and indeed the debugging information can be quite large.
20207 However, it has no effect on the generated code (and thus does not
20208 degrade performance)
20210 Since the compiler generates debugging tables for a compilation unit before
20211 it performs optimizations, the optimizing transformations may invalidate some
20212 of the debugging data. You therefore need to anticipate certain
20213 anomalous situations that may arise while debugging optimized code.
20214 These are the most common cases:
20220 `The ‘hopping Program Counter’:' Repeated @code{step} or @code{next}
20222 the PC bouncing back and forth in the code. This may result from any of
20223 the following optimizations:
20229 `Common subexpression elimination:' using a single instance of code for a
20230 quantity that the source computes several times. As a result you
20231 may not be able to stop on what looks like a statement.
20234 `Invariant code motion:' moving an expression that does not change within a
20235 loop, to the beginning of the loop.
20238 `Instruction scheduling:' moving instructions so as to
20239 overlap loads and stores (typically) with other code, or in
20240 general to move computations of values closer to their uses. Often
20241 this causes you to pass an assignment statement without the assignment
20242 happening and then later bounce back to the statement when the
20243 value is actually needed. Placing a breakpoint on a line of code
20244 and then stepping over it may, therefore, not always cause all the
20245 expected side-effects.
20249 `The ‘big leap’:' More commonly known as `cross-jumping', in which
20250 two identical pieces of code are merged and the program counter suddenly
20251 jumps to a statement that is not supposed to be executed, simply because
20252 it (and the code following) translates to the same thing as the code
20253 that `was' supposed to be executed. This effect is typically seen in
20254 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
20255 a @code{break} in a C @code{switch} statement.
20258 `The ‘roving variable’:' The symptom is an unexpected value in a variable.
20259 There are various reasons for this effect:
20265 In a subprogram prologue, a parameter may not yet have been moved to its
20269 A variable may be dead, and its register re-used. This is
20270 probably the most common cause.
20273 As mentioned above, the assignment of a value to a variable may
20277 A variable may be eliminated entirely by value propagation or
20278 other means. In this case, GCC may incorrectly generate debugging
20279 information for the variable
20282 In general, when an unexpected value appears for a local variable or parameter
20283 you should first ascertain if that value was actually computed by
20284 your program, as opposed to being incorrectly reported by the debugger.
20286 array elements in an object designated by an access value
20287 are generally less of a problem, once you have ascertained that the access
20289 Typically, this means checking variables in the preceding code and in the
20290 calling subprogram to verify that the value observed is explainable from other
20291 values (one must apply the procedure recursively to those
20292 other values); or re-running the code and stopping a little earlier
20293 (perhaps before the call) and stepping to better see how the variable obtained
20294 the value in question; or continuing to step `from' the point of the
20295 strange value to see if code motion had simply moved the variable’s
20299 In light of such anomalies, a recommended technique is to use @code{-O0}
20300 early in the software development cycle, when extensive debugging capabilities
20301 are most needed, and then move to @code{-O1} and later @code{-O2} as
20302 the debugger becomes less critical.
20303 Whether to use the @code{-g} switch in the release version is
20304 a release management issue.
20305 Note that if you use @code{-g} you can then use the @code{strip} program
20306 on the resulting executable,
20307 which removes both debugging information and global symbols.
20309 @node Inlining of Subprograms,Floating Point Operations,Debugging Optimized Code,Performance Considerations
20310 @anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{187}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{102}
20311 @subsubsection Inlining of Subprograms
20314 A call to a subprogram in the current unit is inlined if all the
20315 following conditions are met:
20321 The optimization level is at least @code{-O1}.
20324 The called subprogram is suitable for inlining: It must be small enough
20325 and not contain something that @code{gcc} cannot support in inlined
20328 @geindex pragma Inline
20333 Any one of the following applies: @code{pragma Inline} is applied to the
20334 subprogram; the subprogram is local to the unit and called once from
20335 within it; the subprogram is small and optimization level @code{-O2} is
20336 specified; optimization level @code{-O3} is specified.
20339 Calls to subprograms in `with'ed units are normally not inlined.
20340 To achieve actual inlining (that is, replacement of the call by the code
20341 in the body of the subprogram), the following conditions must all be true:
20347 The optimization level is at least @code{-O1}.
20350 The called subprogram is suitable for inlining: It must be small enough
20351 and not contain something that @code{gcc} cannot support in inlined
20355 There is a @code{pragma Inline} for the subprogram.
20358 The @code{-gnatn} switch is used on the command line.
20361 Even if all these conditions are met, it may not be possible for
20362 the compiler to inline the call, due to the length of the body,
20363 or features in the body that make it impossible for the compiler
20364 to do the inlining.
20366 Note that specifying the @code{-gnatn} switch causes additional
20367 compilation dependencies. Consider the following:
20389 With the default behavior (no @code{-gnatn} switch specified), the
20390 compilation of the @code{Main} procedure depends only on its own source,
20391 @code{main.adb}, and the spec of the package in file @code{r.ads}. This
20392 means that editing the body of @code{R} does not require recompiling
20395 On the other hand, the call @code{R.Q} is not inlined under these
20396 circumstances. If the @code{-gnatn} switch is present when @code{Main}
20397 is compiled, the call will be inlined if the body of @code{Q} is small
20398 enough, but now @code{Main} depends on the body of @code{R} in
20399 @code{r.adb} as well as on the spec. This means that if this body is edited,
20400 the main program must be recompiled. Note that this extra dependency
20401 occurs whether or not the call is in fact inlined by @code{gcc}.
20403 The use of front end inlining with @code{-gnatN} generates similar
20404 additional dependencies.
20406 @geindex -fno-inline (gcc)
20408 Note: The @code{-fno-inline} switch overrides all other conditions and ensures that
20409 no inlining occurs, unless requested with pragma Inline_Always for @code{gcc}
20410 back-ends. The extra dependences resulting from @code{-gnatn} will still be active,
20411 even if this switch is used to suppress the resulting inlining actions.
20413 @geindex -fno-inline-functions (gcc)
20415 Note: The @code{-fno-inline-functions} switch can be used to prevent
20416 automatic inlining of subprograms if @code{-O3} is used.
20418 @geindex -fno-inline-small-functions (gcc)
20420 Note: The @code{-fno-inline-small-functions} switch can be used to prevent
20421 automatic inlining of small subprograms if @code{-O2} is used.
20423 @geindex -fno-inline-functions-called-once (gcc)
20425 Note: The @code{-fno-inline-functions-called-once} switch
20426 can be used to prevent inlining of subprograms local to the unit
20427 and called once from within it if @code{-O1} is used.
20429 Note regarding the use of @code{-O3}: @code{-gnatn} is made up of two
20430 sub-switches @code{-gnatn1} and @code{-gnatn2} that can be directly
20431 specified in lieu of it, @code{-gnatn} being translated into one of them
20432 based on the optimization level. With @code{-O2} or below, @code{-gnatn}
20433 is equivalent to @code{-gnatn1} which activates pragma @code{Inline} with
20434 moderate inlining across modules. With @code{-O3}, @code{-gnatn} is
20435 equivalent to @code{-gnatn2} which activates pragma @code{Inline} with
20436 full inlining across modules. If you have used pragma @code{Inline} in
20437 appropriate cases, then it is usually much better to use @code{-O2}
20438 and @code{-gnatn} and avoid the use of @code{-O3} which has the additional
20439 effect of inlining subprograms you did not think should be inlined. We have
20440 found that the use of @code{-O3} may slow down the compilation and increase
20441 the code size by performing excessive inlining, leading to increased
20442 instruction cache pressure from the increased code size and thus minor
20443 performance improvements. So the bottom line here is that you should not
20444 automatically assume that @code{-O3} is better than @code{-O2}, and
20445 indeed you should use @code{-O3} only if tests show that it actually
20446 improves performance for your program.
20448 @node Floating Point Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
20449 @anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{188}@anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{189}
20450 @subsubsection Floating Point Operations
20453 @geindex Floating-Point Operations
20455 On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
20456 64-bit standard IEEE floating-point representations, and operations will
20457 use standard IEEE arithmetic as provided by the processor. On most, but
20458 not all, architectures, the attribute Machine_Overflows is False for these
20459 types, meaning that the semantics of overflow is implementation-defined.
20460 In the case of GNAT, these semantics correspond to the normal IEEE
20461 treatment of infinities and NaN (not a number) values. For example,
20462 1.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
20463 avoiding explicit overflow checks, the performance is greatly improved
20464 on many targets. However, if required, floating-point overflow can be
20465 enabled by the use of the pragma Check_Float_Overflow.
20467 Another consideration that applies specifically to x86 32-bit
20468 architectures is which form of floating-point arithmetic is used.
20469 By default the operations use the old style x86 floating-point,
20470 which implements an 80-bit extended precision form (on these
20471 architectures the type Long_Long_Float corresponds to that form).
20472 In addition, generation of efficient code in this mode means that
20473 the extended precision form will be used for intermediate results.
20474 This may be helpful in improving the final precision of a complex
20475 expression. However it means that the results obtained on the x86
20476 will be different from those on other architectures, and for some
20477 algorithms, the extra intermediate precision can be detrimental.
20479 In addition to this old-style floating-point, all modern x86 chips
20480 implement an alternative floating-point operation model referred
20481 to as SSE2. In this model there is no extended form, and furthermore
20482 execution performance is significantly enhanced. To force GNAT to use
20483 this more modern form, use both of the switches:
20487 -msse2 -mfpmath=sse
20490 A unit compiled with these switches will automatically use the more
20491 efficient SSE2 instruction set for Float and Long_Float operations.
20492 Note that the ABI has the same form for both floating-point models,
20493 so it is permissible to mix units compiled with and without these
20496 @node Vectorization of loops,Other Optimization Switches,Floating Point Operations,Performance Considerations
20497 @anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{18a}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{18b}
20498 @subsubsection Vectorization of loops
20501 @geindex Optimization Switches
20503 You can take advantage of the auto-vectorizer present in the @code{gcc}
20504 back end to vectorize loops with GNAT. The corresponding command line switch
20505 is @code{-ftree-vectorize} but, as it is enabled by default at @code{-O3}
20506 and other aggressive optimizations helpful for vectorization also are enabled
20507 by default at this level, using @code{-O3} directly is recommended.
20509 You also need to make sure that the target architecture features a supported
20510 SIMD instruction set. For example, for the x86 architecture, you should at
20511 least specify @code{-msse2} to get significant vectorization (but you don’t
20512 need to specify it for x86-64 as it is part of the base 64-bit architecture).
20513 Similarly, for the PowerPC architecture, you should specify @code{-maltivec}.
20515 The preferred loop form for vectorization is the @code{for} iteration scheme.
20516 Loops with a @code{while} iteration scheme can also be vectorized if they are
20517 very simple, but the vectorizer will quickly give up otherwise. With either
20518 iteration scheme, the flow of control must be straight, in particular no
20519 @code{exit} statement may appear in the loop body. The loop may however
20520 contain a single nested loop, if it can be vectorized when considered alone:
20525 A : array (1..4, 1..4) of Long_Float;
20526 S : array (1..4) of Long_Float;
20530 for I in A'Range(1) loop
20531 for J in A'Range(2) loop
20532 S (I) := S (I) + A (I, J);
20539 The vectorizable operations depend on the targeted SIMD instruction set, but
20540 the adding and some of the multiplying operators are generally supported, as
20541 well as the logical operators for modular types. Note that compiling
20542 with @code{-gnatp} might well reveal cases where some checks do thwart
20545 Type conversions may also prevent vectorization if they involve semantics that
20546 are not directly supported by the code generator or the SIMD instruction set.
20547 A typical example is direct conversion from floating-point to integer types.
20548 The solution in this case is to use the following idiom:
20553 Integer (S'Truncation (F))
20557 if @code{S} is the subtype of floating-point object @code{F}.
20559 In most cases, the vectorizable loops are loops that iterate over arrays.
20560 All kinds of array types are supported, i.e. constrained array types with
20566 type Array_Type is array (1 .. 4) of Long_Float;
20570 constrained array types with dynamic bounds:
20575 type Array_Type is array (1 .. Q.N) of Long_Float;
20577 type Array_Type is array (Q.K .. 4) of Long_Float;
20579 type Array_Type is array (Q.K .. Q.N) of Long_Float;
20583 or unconstrained array types:
20588 type Array_Type is array (Positive range <>) of Long_Float;
20592 The quality of the generated code decreases when the dynamic aspect of the
20593 array type increases, the worst code being generated for unconstrained array
20594 types. This is so because, the less information the compiler has about the
20595 bounds of the array, the more fallback code it needs to generate in order to
20596 fix things up at run time.
20598 It is possible to specify that a given loop should be subject to vectorization
20599 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
20604 pragma Loop_Optimize (Vector);
20608 placed immediately within the loop will convey the appropriate hint to the
20609 compiler for this loop.
20611 It is also possible to help the compiler generate better vectorized code
20612 for a given loop by asserting that there are no loop-carried dependencies
20613 in the loop. Consider for example the procedure:
20618 type Arr is array (1 .. 4) of Long_Float;
20620 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
20622 for I in Arr'Range loop
20623 R(I) := X(I) + Y(I);
20629 By default, the compiler cannot unconditionally vectorize the loop because
20630 assigning to a component of the array designated by R in one iteration could
20631 change the value read from the components of the array designated by X or Y
20632 in a later iteration. As a result, the compiler will generate two versions
20633 of the loop in the object code, one vectorized and the other not vectorized,
20634 as well as a test to select the appropriate version at run time. This can
20635 be overcome by another hint:
20640 pragma Loop_Optimize (Ivdep);
20644 placed immediately within the loop will tell the compiler that it can safely
20645 omit the non-vectorized version of the loop as well as the run-time test.
20647 @node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
20648 @anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{18c}@anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{18d}
20649 @subsubsection Other Optimization Switches
20652 @geindex Optimization Switches
20654 Since GNAT uses the @code{gcc} back end, all the specialized
20655 @code{gcc} optimization switches are potentially usable. These switches
20656 have not been extensively tested with GNAT but can generally be expected
20657 to work. Examples of switches in this category are @code{-funroll-loops}
20658 and the various target-specific @code{-m} options (in particular, it has
20659 been observed that @code{-march=xxx} can significantly improve performance
20660 on appropriate machines). For full details of these switches, see
20661 the `Submodel Options' section in the `Hardware Models and Configurations'
20662 chapter of @cite{Using the GNU Compiler Collection (GCC)}.
20664 @node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
20665 @anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{18e}@anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{e6}
20666 @subsubsection Optimization and Strict Aliasing
20671 @geindex Strict Aliasing
20673 @geindex No_Strict_Aliasing
20675 The strong typing capabilities of Ada allow an optimizer to generate
20676 efficient code in situations where other languages would be forced to
20677 make worst case assumptions preventing such optimizations. Consider
20678 the following example:
20684 type Int1 is new Integer;
20685 type Int2 is new Integer;
20686 type Int1A is access Int1;
20687 type Int2A is access Int2;
20694 for J in Data'Range loop
20695 if Data (J) = Int1V.all then
20696 Int2V.all := Int2V.all + 1;
20704 In this example, since the variable @code{Int1V} can only access objects
20705 of type @code{Int1}, and @code{Int2V} can only access objects of type
20706 @code{Int2}, there is no possibility that the assignment to
20707 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
20708 the compiler optimizer can “know” that the value @code{Int1V.all} is constant
20709 for all iterations of the loop and avoid the extra memory reference
20710 required to dereference it each time through the loop.
20712 This kind of optimization, called strict aliasing analysis, is
20713 triggered by specifying an optimization level of @code{-O2} or
20714 higher or @code{-Os} and allows GNAT to generate more efficient code
20715 when access values are involved.
20717 However, although this optimization is always correct in terms of
20718 the formal semantics of the Ada Reference Manual, difficulties can
20719 arise if features like @code{Unchecked_Conversion} are used to break
20720 the typing system. Consider the following complete program example:
20726 type int1 is new integer;
20727 type int2 is new integer;
20728 type a1 is access int1;
20729 type a2 is access int2;
20734 function to_a2 (Input : a1) return a2;
20737 with Ada.Unchecked_Conversion;
20739 function to_a2 (Input : a1) return a2 is
20741 new Ada.Unchecked_Conversion (a1, a2);
20743 return to_a2u (Input);
20749 with Text_IO; use Text_IO;
20751 v1 : a1 := new int1;
20752 v2 : a2 := to_a2 (v1);
20756 put_line (int1'image (v1.all));
20761 This program prints out 0 in @code{-O0} or @code{-O1}
20762 mode, but it prints out 1 in @code{-O2} mode. That’s
20763 because in strict aliasing mode, the compiler can and
20764 does assume that the assignment to @code{v2.all} could not
20765 affect the value of @code{v1.all}, since different types
20768 This behavior is not a case of non-conformance with the standard, since
20769 the Ada RM specifies that an unchecked conversion where the resulting
20770 bit pattern is not a correct value of the target type can result in an
20771 abnormal value and attempting to reference an abnormal value makes the
20772 execution of a program erroneous. That’s the case here since the result
20773 does not point to an object of type @code{int2}. This means that the
20774 effect is entirely unpredictable.
20776 However, although that explanation may satisfy a language
20777 lawyer, in practice an applications programmer expects an
20778 unchecked conversion involving pointers to create true
20779 aliases and the behavior of printing 1 seems plain wrong.
20780 In this case, the strict aliasing optimization is unwelcome.
20782 Indeed the compiler recognizes this possibility, and the
20783 unchecked conversion generates a warning:
20788 p2.adb:5:07: warning: possible aliasing problem with type "a2"
20789 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
20790 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
20794 Unfortunately the problem is recognized when compiling the body of
20795 package @code{p2}, but the actual “bad” code is generated while
20796 compiling the body of @code{m} and this latter compilation does not see
20797 the suspicious @code{Unchecked_Conversion}.
20799 As implied by the warning message, there are approaches you can use to
20800 avoid the unwanted strict aliasing optimization in a case like this.
20802 One possibility is to simply avoid the use of @code{-O2}, but
20803 that is a bit drastic, since it throws away a number of useful
20804 optimizations that do not involve strict aliasing assumptions.
20806 A less drastic approach is to compile the program using the
20807 option @code{-fno-strict-aliasing}. Actually it is only the
20808 unit containing the dereferencing of the suspicious pointer
20809 that needs to be compiled. So in this case, if we compile
20810 unit @code{m} with this switch, then we get the expected
20811 value of zero printed. Analyzing which units might need
20812 the switch can be painful, so a more reasonable approach
20813 is to compile the entire program with options @code{-O2}
20814 and @code{-fno-strict-aliasing}. If the performance is
20815 satisfactory with this combination of options, then the
20816 advantage is that the entire issue of possible “wrong”
20817 optimization due to strict aliasing is avoided.
20819 To avoid the use of compiler switches, the configuration
20820 pragma @code{No_Strict_Aliasing} with no parameters may be
20821 used to specify that for all access types, the strict
20822 aliasing optimization should be suppressed.
20824 However, these approaches are still overkill, in that they causes
20825 all manipulations of all access values to be deoptimized. A more
20826 refined approach is to concentrate attention on the specific
20827 access type identified as problematic.
20829 First, if a careful analysis of uses of the pointer shows
20830 that there are no possible problematic references, then
20831 the warning can be suppressed by bracketing the
20832 instantiation of @code{Unchecked_Conversion} to turn
20838 pragma Warnings (Off);
20840 new Ada.Unchecked_Conversion (a1, a2);
20841 pragma Warnings (On);
20845 Of course that approach is not appropriate for this particular
20846 example, since indeed there is a problematic reference. In this
20847 case we can take one of two other approaches.
20849 The first possibility is to move the instantiation of unchecked
20850 conversion to the unit in which the type is declared. In
20851 this example, we would move the instantiation of
20852 @code{Unchecked_Conversion} from the body of package
20853 @code{p2} to the spec of package @code{p1}. Now the
20854 warning disappears. That’s because any use of the
20855 access type knows there is a suspicious unchecked
20856 conversion, and the strict aliasing optimization
20857 is automatically suppressed for the type.
20859 If it is not practical to move the unchecked conversion to the same unit
20860 in which the destination access type is declared (perhaps because the
20861 source type is not visible in that unit), you may use pragma
20862 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
20863 same declarative sequence as the declaration of the access type:
20868 type a2 is access int2;
20869 pragma No_Strict_Aliasing (a2);
20873 Here again, the compiler now knows that the strict aliasing optimization
20874 should be suppressed for any reference to type @code{a2} and the
20875 expected behavior is obtained.
20877 Finally, note that although the compiler can generate warnings for
20878 simple cases of unchecked conversions, there are tricker and more
20879 indirect ways of creating type incorrect aliases which the compiler
20880 cannot detect. Examples are the use of address overlays and unchecked
20881 conversions involving composite types containing access types as
20882 components. In such cases, no warnings are generated, but there can
20883 still be aliasing problems. One safe coding practice is to forbid the
20884 use of address clauses for type overlaying, and to allow unchecked
20885 conversion only for primitive types. This is not really a significant
20886 restriction since any possible desired effect can be achieved by
20887 unchecked conversion of access values.
20889 The aliasing analysis done in strict aliasing mode can certainly
20890 have significant benefits. We have seen cases of large scale
20891 application code where the time is increased by up to 5% by turning
20892 this optimization off. If you have code that includes significant
20893 usage of unchecked conversion, you might want to just stick with
20894 @code{-O1} and avoid the entire issue. If you get adequate
20895 performance at this level of optimization level, that’s probably
20896 the safest approach. If tests show that you really need higher
20897 levels of optimization, then you can experiment with @code{-O2}
20898 and @code{-O2 -fno-strict-aliasing} to see how much effect this
20899 has on size and speed of the code. If you really need to use
20900 @code{-O2} with strict aliasing in effect, then you should
20901 review any uses of unchecked conversion of access types,
20902 particularly if you are getting the warnings described above.
20904 @node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
20905 @anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{18f}@anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{190}
20906 @subsubsection Aliased Variables and Optimization
20911 There are scenarios in which programs may
20912 use low level techniques to modify variables
20913 that otherwise might be considered to be unassigned. For example,
20914 a variable can be passed to a procedure by reference, which takes
20915 the address of the parameter and uses the address to modify the
20916 variable’s value, even though it is passed as an IN parameter.
20917 Consider the following example:
20923 Max_Length : constant Natural := 16;
20924 type Char_Ptr is access all Character;
20926 procedure Get_String(Buffer: Char_Ptr; Size : Integer);
20927 pragma Import (C, Get_String, "get_string");
20929 Name : aliased String (1 .. Max_Length) := (others => ' ');
20932 function Addr (S : String) return Char_Ptr is
20933 function To_Char_Ptr is
20934 new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
20936 return To_Char_Ptr (S (S'First)'Address);
20940 Temp := Addr (Name);
20941 Get_String (Temp, Max_Length);
20946 where Get_String is a C function that uses the address in Temp to
20947 modify the variable @code{Name}. This code is dubious, and arguably
20948 erroneous, and the compiler would be entitled to assume that
20949 @code{Name} is never modified, and generate code accordingly.
20951 However, in practice, this would cause some existing code that
20952 seems to work with no optimization to start failing at high
20953 levels of optimization.
20955 What the compiler does for such cases is to assume that marking
20956 a variable as aliased indicates that some “funny business” may
20957 be going on. The optimizer recognizes the aliased keyword and
20958 inhibits optimizations that assume the value cannot be assigned.
20959 This means that the above example will in fact “work” reliably,
20960 that is, it will produce the expected results.
20962 @node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
20963 @anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{191}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{192}
20964 @subsubsection Atomic Variables and Optimization
20969 There are two considerations with regard to performance when
20970 atomic variables are used.
20972 First, the RM only guarantees that access to atomic variables
20973 be atomic, it has nothing to say about how this is achieved,
20974 though there is a strong implication that this should not be
20975 achieved by explicit locking code. Indeed GNAT will never
20976 generate any locking code for atomic variable access (it will
20977 simply reject any attempt to make a variable or type atomic
20978 if the atomic access cannot be achieved without such locking code).
20980 That being said, it is important to understand that you cannot
20981 assume that the entire variable will always be accessed. Consider
20988 A,B,C,D : Character;
20991 for R'Alignment use 4;
20994 pragma Atomic (RV);
21001 You cannot assume that the reference to @code{RV.B}
21002 will read the entire 32-bit
21003 variable with a single load instruction. It is perfectly legitimate if
21004 the hardware allows it to do a byte read of just the B field. This read
21005 is still atomic, which is all the RM requires. GNAT can and does take
21006 advantage of this, depending on the architecture and optimization level.
21007 Any assumption to the contrary is non-portable and risky. Even if you
21008 examine the assembly language and see a full 32-bit load, this might
21009 change in a future version of the compiler.
21011 If your application requires that all accesses to @code{RV} in this
21012 example be full 32-bit loads, you need to make a copy for the access
21019 RV_Copy : constant R := RV;
21026 Now the reference to RV must read the whole variable.
21027 Actually one can imagine some compiler which figures
21028 out that the whole copy is not required (because only
21029 the B field is actually accessed), but GNAT
21030 certainly won’t do that, and we don’t know of any
21031 compiler that would not handle this right, and the
21032 above code will in practice work portably across
21033 all architectures (that permit the Atomic declaration).
21035 The second issue with atomic variables has to do with
21036 the possible requirement of generating synchronization
21037 code. For more details on this, consult the sections on
21038 the pragmas Enable/Disable_Atomic_Synchronization in the
21039 GNAT Reference Manual. If performance is critical, and
21040 such synchronization code is not required, it may be
21041 useful to disable it.
21043 @node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
21044 @anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{193}@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{194}
21045 @subsubsection Passive Task Optimization
21048 @geindex Passive Task
21050 A passive task is one which is sufficiently simple that
21051 in theory a compiler could recognize it an implement it
21052 efficiently without creating a new thread. The original design
21053 of Ada 83 had in mind this kind of passive task optimization, but
21054 only a few Ada 83 compilers attempted it. The problem was that
21055 it was difficult to determine the exact conditions under which
21056 the optimization was possible. The result is a very fragile
21057 optimization where a very minor change in the program can
21058 suddenly silently make a task non-optimizable.
21060 With the revisiting of this issue in Ada 95, there was general
21061 agreement that this approach was fundamentally flawed, and the
21062 notion of protected types was introduced. When using protected
21063 types, the restrictions are well defined, and you KNOW that the
21064 operations will be optimized, and furthermore this optimized
21065 performance is fully portable.
21067 Although it would theoretically be possible for GNAT to attempt to
21068 do this optimization, but it really doesn’t make sense in the
21069 context of Ada 95, and none of the Ada 95 compilers implement
21070 this optimization as far as we know. In particular GNAT never
21071 attempts to perform this optimization.
21073 In any new Ada 95 code that is written, you should always
21074 use protected types in place of tasks that might be able to
21075 be optimized in this manner.
21076 Of course this does not help if you have legacy Ada 83 code
21077 that depends on this optimization, but it is unusual to encounter
21078 a case where the performance gains from this optimization
21081 Your program should work correctly without this optimization. If
21082 you have performance problems, then the most practical
21083 approach is to figure out exactly where these performance problems
21084 arise, and update those particular tasks to be protected types. Note
21085 that typically clients of the tasks who call entries, will not have
21086 to be modified, only the task definition itself.
21088 @node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
21089 @anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{195}@anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{196}
21090 @subsection @code{Text_IO} Suggestions
21093 @geindex Text_IO and performance
21095 The @code{Ada.Text_IO} package has fairly high overheads due in part to
21096 the requirement of maintaining page and line counts. If performance
21097 is critical, a recommendation is to use @code{Stream_IO} instead of
21098 @code{Text_IO} for volume output, since this package has less overhead.
21100 If @code{Text_IO} must be used, note that by default output to the standard
21101 output and standard error files is unbuffered (this provides better
21102 behavior when output statements are used for debugging, or if the
21103 progress of a program is observed by tracking the output, e.g. by
21104 using the Unix `tail -f' command to watch redirected output).
21106 If you are generating large volumes of output with @code{Text_IO} and
21107 performance is an important factor, use a designated file instead
21108 of the standard output file, or change the standard output file to
21109 be buffered using @code{Interfaces.C_Streams.setvbuf}.
21111 @node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
21112 @anchor{gnat_ugn/gnat_and_program_execution id41}@anchor{197}@anchor{gnat_ugn/gnat_and_program_execution reducing-size-of-executables-with-unused-subprogram-data-elimination}@anchor{198}
21113 @subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
21116 @geindex Uunused subprogram/data elimination
21118 This section describes how you can eliminate unused subprograms and data from
21119 your executable just by setting options at compilation time.
21122 * About unused subprogram/data elimination::
21123 * Compilation options::
21124 * Example of unused subprogram/data elimination::
21128 @node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
21129 @anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{199}@anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{19a}
21130 @subsubsection About unused subprogram/data elimination
21133 By default, an executable contains all code and data of its composing objects
21134 (directly linked or coming from statically linked libraries), even data or code
21135 never used by this executable.
21137 This feature will allow you to eliminate such unused code from your
21138 executable, making it smaller (in disk and in memory).
21140 This functionality is available on all Linux platforms except for the IA-64
21141 architecture and on all cross platforms using the ELF binary file format.
21142 In both cases GNU binutils version 2.16 or later are required to enable it.
21144 @node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
21145 @anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{19b}@anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{19c}
21146 @subsubsection Compilation options
21149 The operation of eliminating the unused code and data from the final executable
21150 is directly performed by the linker.
21152 @geindex -ffunction-sections (gcc)
21154 @geindex -fdata-sections (gcc)
21156 In order to do this, it has to work with objects compiled with the
21158 @code{-ffunction-sections} @code{-fdata-sections}.
21160 These options are usable with C and Ada files.
21161 They will place respectively each
21162 function or data in a separate section in the resulting object file.
21164 Once the objects and static libraries are created with these options, the
21165 linker can perform the dead code elimination. You can do this by setting
21166 the @code{-Wl,--gc-sections} option to gcc command or in the
21167 @code{-largs} section of @code{gnatmake}. This will perform a
21168 garbage collection of code and data never referenced.
21170 If the linker performs a partial link (@code{-r} linker option), then you
21171 will need to provide the entry point using the @code{-e} / @code{--entry}
21174 Note that objects compiled without the @code{-ffunction-sections} and
21175 @code{-fdata-sections} options can still be linked with the executable.
21176 However, no dead code elimination will be performed on those objects (they will
21179 The GNAT static library is now compiled with -ffunction-sections and
21180 -fdata-sections on some platforms. This allows you to eliminate the unused code
21181 and data of the GNAT library from your executable.
21183 @node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
21184 @anchor{gnat_ugn/gnat_and_program_execution example-of-unused-subprogram-data-elimination}@anchor{19d}@anchor{gnat_ugn/gnat_and_program_execution id44}@anchor{19e}
21185 @subsubsection Example of unused subprogram/data elimination
21188 Here is a simple example:
21201 Used_Data : Integer;
21202 Unused_Data : Integer;
21204 procedure Used (Data : Integer);
21205 procedure Unused (Data : Integer);
21208 package body Aux is
21209 procedure Used (Data : Integer) is
21214 procedure Unused (Data : Integer) is
21216 Unused_Data := Data;
21222 @code{Unused} and @code{Unused_Data} are never referenced in this code
21223 excerpt, and hence they may be safely removed from the final executable.
21230 $ nm test | grep used
21231 020015f0 T aux__unused
21232 02005d88 B aux__unused_data
21233 020015cc T aux__used
21234 02005d84 B aux__used_data
21236 $ gnatmake test -cargs -fdata-sections -ffunction-sections \\
21237 -largs -Wl,--gc-sections
21239 $ nm test | grep used
21240 02005350 T aux__used
21241 0201ffe0 B aux__used_data
21245 It can be observed that the procedure @code{Unused} and the object
21246 @code{Unused_Data} are removed by the linker when using the
21247 appropriate options.
21249 @geindex Overflow checks
21251 @geindex Checks (overflow)
21253 @node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
21254 @anchor{gnat_ugn/gnat_and_program_execution id45}@anchor{14b}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{19f}
21255 @section Overflow Check Handling in GNAT
21258 This section explains how to control the handling of overflow checks.
21262 * Management of Overflows in GNAT::
21263 * Specifying the Desired Mode::
21264 * Default Settings::
21265 * Implementation Notes::
21269 @node Background,Management of Overflows in GNAT,,Overflow Check Handling in GNAT
21270 @anchor{gnat_ugn/gnat_and_program_execution background}@anchor{1a0}@anchor{gnat_ugn/gnat_and_program_execution id46}@anchor{1a1}
21271 @subsection Background
21274 Overflow checks are checks that the compiler may make to ensure
21275 that intermediate results are not out of range. For example:
21286 If @code{A} has the value @code{Integer'Last}, then the addition may cause
21287 overflow since the result is out of range of the type @code{Integer}.
21288 In this case @code{Constraint_Error} will be raised if checks are
21291 A trickier situation arises in examples like the following:
21302 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
21303 Now the final result of the expression on the right hand side is
21304 @code{Integer'Last} which is in range, but the question arises whether the
21305 intermediate addition of @code{(A + 1)} raises an overflow error.
21307 The (perhaps surprising) answer is that the Ada language
21308 definition does not answer this question. Instead it leaves
21309 it up to the implementation to do one of two things if overflow
21310 checks are enabled.
21316 raise an exception (@code{Constraint_Error}), or
21319 yield the correct mathematical result which is then used in
21320 subsequent operations.
21323 If the compiler chooses the first approach, then the assignment of this
21324 example will indeed raise @code{Constraint_Error} if overflow checking is
21325 enabled, or result in erroneous execution if overflow checks are suppressed.
21327 But if the compiler
21328 chooses the second approach, then it can perform both additions yielding
21329 the correct mathematical result, which is in range, so no exception
21330 will be raised, and the right result is obtained, regardless of whether
21331 overflow checks are suppressed.
21333 Note that in the first example an
21334 exception will be raised in either case, since if the compiler
21335 gives the correct mathematical result for the addition, it will
21336 be out of range of the target type of the assignment, and thus
21337 fails the range check.
21339 This lack of specified behavior in the handling of overflow for
21340 intermediate results is a source of non-portability, and can thus
21341 be problematic when programs are ported. Most typically this arises
21342 in a situation where the original compiler did not raise an exception,
21343 and then the application is moved to a compiler where the check is
21344 performed on the intermediate result and an unexpected exception is
21347 Furthermore, when using Ada 2012’s preconditions and other
21348 assertion forms, another issue arises. Consider:
21353 procedure P (A, B : Integer) with
21354 Pre => A + B <= Integer'Last;
21358 One often wants to regard arithmetic in a context like this from
21359 a mathematical point of view. So for example, if the two actual parameters
21360 for a call to @code{P} are both @code{Integer'Last}, then
21361 the precondition should be regarded as False. If we are executing
21362 in a mode with run-time checks enabled for preconditions, then we would
21363 like this precondition to fail, rather than raising an exception
21364 because of the intermediate overflow.
21366 However, the language definition leaves the specification of
21367 whether the above condition fails (raising @code{Assert_Error}) or
21368 causes an intermediate overflow (raising @code{Constraint_Error})
21369 up to the implementation.
21371 The situation is worse in a case such as the following:
21376 procedure Q (A, B, C : Integer) with
21377 Pre => A + B + C <= Integer'Last;
21386 Q (A => Integer'Last, B => 1, C => -1);
21390 From a mathematical point of view the precondition
21391 is True, but at run time we may (but are not guaranteed to) get an
21392 exception raised because of the intermediate overflow (and we really
21393 would prefer this precondition to be considered True at run time).
21395 @node Management of Overflows in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
21396 @anchor{gnat_ugn/gnat_and_program_execution id47}@anchor{1a2}@anchor{gnat_ugn/gnat_and_program_execution management-of-overflows-in-gnat}@anchor{1a3}
21397 @subsection Management of Overflows in GNAT
21400 To deal with the portability issue, and with the problem of
21401 mathematical versus run-time interpretation of the expressions in
21402 assertions, GNAT provides comprehensive control over the handling
21403 of intermediate overflow. GNAT can operate in three modes, and
21404 furthermore, permits separate selection of operating modes for
21405 the expressions within assertions (here the term ‘assertions’
21406 is used in the technical sense, which includes preconditions and so forth)
21407 and for expressions appearing outside assertions.
21409 The three modes are:
21415 `Use base type for intermediate operations' (@code{STRICT})
21417 In this mode, all intermediate results for predefined arithmetic
21418 operators are computed using the base type, and the result must
21419 be in range of the base type. If this is not the
21420 case then either an exception is raised (if overflow checks are
21421 enabled) or the execution is erroneous (if overflow checks are suppressed).
21422 This is the normal default mode.
21425 `Most intermediate overflows avoided' (@code{MINIMIZED})
21427 In this mode, the compiler attempts to avoid intermediate overflows by
21428 using a larger integer type, typically @code{Long_Long_Integer},
21429 as the type in which arithmetic is
21430 performed for predefined arithmetic operators. This may be slightly more
21432 run time (compared to suppressing intermediate overflow checks), though
21433 the cost is negligible on modern 64-bit machines. For the examples given
21434 earlier, no intermediate overflows would have resulted in exceptions,
21435 since the intermediate results are all in the range of
21436 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
21437 of GNAT). In addition, if checks are enabled, this reduces the number of
21438 checks that must be made, so this choice may actually result in an
21439 improvement in space and time behavior.
21441 However, there are cases where @code{Long_Long_Integer} is not large
21442 enough, consider the following example:
21447 procedure R (A, B, C, D : Integer) with
21448 Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
21452 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
21453 Now the intermediate results are
21454 out of the range of @code{Long_Long_Integer} even though the final result
21455 is in range and the precondition is True (from a mathematical point
21456 of view). In such a case, operating in this mode, an overflow occurs
21457 for the intermediate computation (which is why this mode
21458 says `most' intermediate overflows are avoided). In this case,
21459 an exception is raised if overflow checks are enabled, and the
21460 execution is erroneous if overflow checks are suppressed.
21463 `All intermediate overflows avoided' (@code{ELIMINATED})
21465 In this mode, the compiler avoids all intermediate overflows
21466 by using arbitrary precision arithmetic as required. In this
21467 mode, the above example with @code{A**2 * B**2} would
21468 not cause intermediate overflow, because the intermediate result
21469 would be evaluated using sufficient precision, and the result
21470 of evaluating the precondition would be True.
21472 This mode has the advantage of avoiding any intermediate
21473 overflows, but at the expense of significant run-time overhead,
21474 including the use of a library (included automatically in this
21475 mode) for multiple-precision arithmetic.
21477 This mode provides cleaner semantics for assertions, since now
21478 the run-time behavior emulates true arithmetic behavior for the
21479 predefined arithmetic operators, meaning that there is never a
21480 conflict between the mathematical view of the assertion, and its
21483 Note that in this mode, the behavior is unaffected by whether or
21484 not overflow checks are suppressed, since overflow does not occur.
21485 It is possible for gigantic intermediate expressions to raise
21486 @code{Storage_Error} as a result of attempting to compute the
21487 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
21488 but overflow is impossible.
21491 Note that these modes apply only to the evaluation of predefined
21492 arithmetic, membership, and comparison operators for signed integer
21495 For fixed-point arithmetic, checks can be suppressed. But if checks
21497 then fixed-point values are always checked for overflow against the
21498 base type for intermediate expressions (that is such checks always
21499 operate in the equivalent of @code{STRICT} mode).
21501 For floating-point, on nearly all architectures, @code{Machine_Overflows}
21502 is False, and IEEE infinities are generated, so overflow exceptions
21503 are never raised. If you want to avoid infinities, and check that
21504 final results of expressions are in range, then you can declare a
21505 constrained floating-point type, and range checks will be carried
21506 out in the normal manner (with infinite values always failing all
21509 @node Specifying the Desired Mode,Default Settings,Management of Overflows in GNAT,Overflow Check Handling in GNAT
21510 @anchor{gnat_ugn/gnat_and_program_execution id48}@anchor{1a4}@anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{eb}
21511 @subsection Specifying the Desired Mode
21514 @geindex pragma Overflow_Mode
21516 The desired mode of for handling intermediate overflow can be specified using
21517 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
21518 The pragma has the form
21523 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
21527 where @code{MODE} is one of
21533 @code{STRICT}: intermediate overflows checked (using base type)
21536 @code{MINIMIZED}: minimize intermediate overflows
21539 @code{ELIMINATED}: eliminate intermediate overflows
21542 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
21543 @code{minimized} all have the same effect.
21545 If only the @code{General} parameter is present, then the given @code{MODE} applies
21546 to expressions both within and outside assertions. If both arguments
21547 are present, then @code{General} applies to expressions outside assertions,
21548 and @code{Assertions} applies to expressions within assertions. For example:
21553 pragma Overflow_Mode
21554 (General => Minimized, Assertions => Eliminated);
21558 specifies that general expressions outside assertions be evaluated
21559 in ‘minimize intermediate overflows’ mode, and expressions within
21560 assertions be evaluated in ‘eliminate intermediate overflows’ mode.
21561 This is often a reasonable choice, avoiding excessive overhead
21562 outside assertions, but assuring a high degree of portability
21563 when importing code from another compiler, while incurring
21564 the extra overhead for assertion expressions to ensure that
21565 the behavior at run time matches the expected mathematical
21568 The @code{Overflow_Mode} pragma has the same scoping and placement
21569 rules as pragma @code{Suppress}, so it can occur either as a
21570 configuration pragma, specifying a default for the whole
21571 program, or in a declarative scope, where it applies to the
21572 remaining declarations and statements in that scope.
21574 Note that pragma @code{Overflow_Mode} does not affect whether
21575 overflow checks are enabled or suppressed. It only controls the
21576 method used to compute intermediate values. To control whether
21577 overflow checking is enabled or suppressed, use pragma @code{Suppress}
21578 or @code{Unsuppress} in the usual manner.
21580 @geindex -gnato? (gcc)
21582 @geindex -gnato?? (gcc)
21584 Additionally, a compiler switch @code{-gnato?} or @code{-gnato??}
21585 can be used to control the checking mode default (which can be subsequently
21586 overridden using pragmas).
21588 Here @code{?} is one of the digits @code{1} through @code{3}:
21593 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
21600 use base type for intermediate operations (@code{STRICT})
21608 minimize intermediate overflows (@code{MINIMIZED})
21616 eliminate intermediate overflows (@code{ELIMINATED})
21622 As with the pragma, if only one digit appears then it applies to all
21623 cases; if two digits are given, then the first applies outside
21624 assertions, and the second within assertions. Thus the equivalent
21625 of the example pragma above would be
21628 If no digits follow the @code{-gnato}, then it is equivalent to
21630 causing all intermediate operations to be computed using the base
21631 type (@code{STRICT} mode).
21633 @node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
21634 @anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{1a5}@anchor{gnat_ugn/gnat_and_program_execution id49}@anchor{1a6}
21635 @subsection Default Settings
21638 The default mode for overflow checks is
21647 which causes all computations both inside and outside assertions to use the
21648 base type, and is equivalent to @code{-gnato} (with no digits following).
21650 The pragma @code{Suppress (Overflow_Check)} disables overflow
21651 checking, but it has no effect on the method used for computing
21652 intermediate results.
21654 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
21655 checking, but it has no effect on the method used for computing
21656 intermediate results.
21658 @node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
21659 @anchor{gnat_ugn/gnat_and_program_execution id50}@anchor{1a7}@anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{1a8}
21660 @subsection Implementation Notes
21663 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
21664 reasonably efficient, and can be generally used. It also helps
21665 to ensure compatibility with code imported from some other
21668 Setting all intermediate overflows checking (@code{STRICT} mode)
21669 makes sense if you want to
21670 make sure that your code is compatible with any other possible
21671 Ada implementation. This may be useful in ensuring portability
21672 for code that is to be exported to some other compiler than GNAT.
21674 The Ada standard allows the reassociation of expressions at
21675 the same precedence level if no parentheses are present. For
21676 example, @code{A+B+C} parses as though it were @code{(A+B)+C}, but
21677 the compiler can reintepret this as @code{A+(B+C)}, possibly
21678 introducing or eliminating an overflow exception. The GNAT
21679 compiler never takes advantage of this freedom, and the
21680 expression @code{A+B+C} will be evaluated as @code{(A+B)+C}.
21681 If you need the other order, you can write the parentheses
21682 explicitly @code{A+(B+C)} and GNAT will respect this order.
21684 The use of @code{ELIMINATED} mode will cause the compiler to
21685 automatically include an appropriate arbitrary precision
21686 integer arithmetic package. The compiler will make calls
21687 to this package, though only in cases where it cannot be
21688 sure that @code{Long_Long_Integer} is sufficient to guard against
21689 intermediate overflows. This package does not use dynamic
21690 allocation, but it does use the secondary stack, so an
21691 appropriate secondary stack package must be present (this
21692 is always true for standard full Ada, but may require
21693 specific steps for restricted run times such as ZFP).
21695 Although @code{ELIMINATED} mode causes expressions to use arbitrary
21696 precision arithmetic, avoiding overflow, the final result
21697 must be in an appropriate range. This is true even if the
21698 final result is of type @code{[Long_[Long_]]Integer'Base}, which
21699 still has the same bounds as its associated constrained
21702 Currently, the @code{ELIMINATED} mode is only available on target
21703 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
21706 @node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
21707 @anchor{gnat_ugn/gnat_and_program_execution id51}@anchor{14c}@anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{1a9}
21708 @section Performing Dimensionality Analysis in GNAT
21711 @geindex Dimensionality analysis
21713 The GNAT compiler supports dimensionality checking. The user can
21714 specify physical units for objects, and the compiler will verify that uses
21715 of these objects are compatible with their dimensions, in a fashion that is
21716 familiar to engineering practice. The dimensions of algebraic expressions
21717 (including powers with static exponents) are computed from their constituents.
21719 @geindex Dimension_System aspect
21721 @geindex Dimension aspect
21723 This feature depends on Ada 2012 aspect specifications, and is available from
21724 version 7.0.1 of GNAT onwards.
21725 The GNAT-specific aspect @code{Dimension_System}
21726 allows you to define a system of units; the aspect @code{Dimension}
21727 then allows the user to declare dimensioned quantities within a given system.
21728 (These aspects are described in the `Implementation Defined Aspects'
21729 chapter of the `GNAT Reference Manual').
21731 The major advantage of this model is that it does not require the declaration of
21732 multiple operators for all possible combinations of types: it is only necessary
21733 to use the proper subtypes in object declarations.
21735 @geindex System.Dim.Mks package (GNAT library)
21737 @geindex MKS_Type type
21739 The simplest way to impose dimensionality checking on a computation is to make
21740 use of one of the instantiations of the package @code{System.Dim.Generic_Mks}, which
21741 are part of the GNAT library. This generic package defines a floating-point
21742 type @code{MKS_Type}, for which a sequence of dimension names are specified,
21743 together with their conventional abbreviations. The following should be read
21744 together with the full specification of the package, in file
21745 @code{s-digemk.ads}.
21749 @geindex s-digemk.ads file
21752 type Mks_Type is new Float_Type
21754 Dimension_System => (
21755 (Unit_Name => Meter, Unit_Symbol => 'm', Dim_Symbol => 'L'),
21756 (Unit_Name => Kilogram, Unit_Symbol => "kg", Dim_Symbol => 'M'),
21757 (Unit_Name => Second, Unit_Symbol => 's', Dim_Symbol => 'T'),
21758 (Unit_Name => Ampere, Unit_Symbol => 'A', Dim_Symbol => 'I'),
21759 (Unit_Name => Kelvin, Unit_Symbol => 'K', Dim_Symbol => "Theta"),
21760 (Unit_Name => Mole, Unit_Symbol => "mol", Dim_Symbol => 'N'),
21761 (Unit_Name => Candela, Unit_Symbol => "cd", Dim_Symbol => 'J'));
21765 The package then defines a series of subtypes that correspond to these
21766 conventional units. For example:
21771 subtype Length is Mks_Type
21773 Dimension => (Symbol => 'm', Meter => 1, others => 0);
21777 and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
21778 @code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
21779 @code{Luminous_Intensity} (the standard set of units of the SI system).
21781 The package also defines conventional names for values of each unit, for
21787 m : constant Length := 1.0;
21788 kg : constant Mass := 1.0;
21789 s : constant Time := 1.0;
21790 A : constant Electric_Current := 1.0;
21794 as well as useful multiples of these units:
21799 cm : constant Length := 1.0E-02;
21800 g : constant Mass := 1.0E-03;
21801 min : constant Time := 60.0;
21802 day : constant Time := 60.0 * 24.0 * min;
21807 There are three instantiations of @code{System.Dim.Generic_Mks} defined in the
21814 @code{System.Dim.Float_Mks} based on @code{Float} defined in @code{s-diflmk.ads}.
21817 @code{System.Dim.Long_Mks} based on @code{Long_Float} defined in @code{s-dilomk.ads}.
21820 @code{System.Dim.Mks} based on @code{Long_Long_Float} defined in @code{s-dimmks.ads}.
21823 Using one of these packages, you can then define a derived unit by providing
21824 the aspect that specifies its dimensions within the MKS system, as well as the
21825 string to be used for output of a value of that unit:
21830 subtype Acceleration is Mks_Type
21831 with Dimension => ("m/sec^2",
21838 Here is a complete example of use:
21843 with System.Dim.MKS; use System.Dim.Mks;
21844 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
21845 with Text_IO; use Text_IO;
21846 procedure Free_Fall is
21847 subtype Acceleration is Mks_Type
21848 with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
21849 G : constant acceleration := 9.81 * m / (s ** 2);
21850 T : Time := 10.0*s;
21854 Put ("Gravitational constant: ");
21855 Put (G, Aft => 2, Exp => 0); Put_Line ("");
21856 Distance := 0.5 * G * T ** 2;
21857 Put ("distance travelled in 10 seconds of free fall ");
21858 Put (Distance, Aft => 2, Exp => 0);
21864 Execution of this program yields:
21869 Gravitational constant: 9.81 m/sec^2
21870 distance travelled in 10 seconds of free fall 490.50 m
21874 However, incorrect assignments such as:
21880 Distance := 5.0 * kg;
21884 are rejected with the following diagnoses:
21890 >>> dimensions mismatch in assignment
21891 >>> left-hand side has dimension [L]
21892 >>> right-hand side is dimensionless
21894 Distance := 5.0 * kg:
21895 >>> dimensions mismatch in assignment
21896 >>> left-hand side has dimension [L]
21897 >>> right-hand side has dimension [M]
21901 The dimensions of an expression are properly displayed, even if there is
21902 no explicit subtype for it. If we add to the program:
21907 Put ("Final velocity: ");
21908 Put (G * T, Aft =>2, Exp =>0);
21913 then the output includes:
21918 Final velocity: 98.10 m.s**(-1)
21921 @geindex Dimensionable type
21923 @geindex Dimensioned subtype
21926 The type @code{Mks_Type} is said to be a `dimensionable type' since it has a
21927 @code{Dimension_System} aspect, and the subtypes @code{Length}, @code{Mass}, etc.,
21928 are said to be `dimensioned subtypes' since each one has a @code{Dimension}
21933 @geindex Dimension Vector (for a dimensioned subtype)
21935 @geindex Dimension aspect
21937 @geindex Dimension_System aspect
21940 The @code{Dimension} aspect of a dimensioned subtype @code{S} defines a mapping
21941 from the base type’s Unit_Names to integer (or, more generally, rational)
21942 values. This mapping is the `dimension vector' (also referred to as the
21943 `dimensionality') for that subtype, denoted by @code{DV(S)}, and thus for each
21944 object of that subtype. Intuitively, the value specified for each
21945 @code{Unit_Name} is the exponent associated with that unit; a zero value
21946 means that the unit is not used. For example:
21952 Acc : Acceleration;
21960 Here @code{DV(Acc)} = @code{DV(Acceleration)} =
21961 @code{(Meter=>1, Kilogram=>0, Second=>-2, Ampere=>0, Kelvin=>0, Mole=>0, Candela=>0)}.
21962 Symbolically, we can express this as @code{Meter / Second**2}.
21964 The dimension vector of an arithmetic expression is synthesized from the
21965 dimension vectors of its components, with compile-time dimensionality checks
21966 that help prevent mismatches such as using an @code{Acceleration} where a
21967 @code{Length} is required.
21969 The dimension vector of the result of an arithmetic expression `expr', or
21970 @code{DV(@var{expr})}, is defined as follows, assuming conventional
21971 mathematical definitions for the vector operations that are used:
21977 If `expr' is of the type `universal_real', or is not of a dimensioned subtype,
21978 then `expr' is dimensionless; @code{DV(@var{expr})} is the empty vector.
21981 @code{DV(@var{op expr})}, where `op' is a unary operator, is @code{DV(@var{expr})}
21984 @code{DV(@var{expr1 op expr2})} where `op' is “+” or “-” is @code{DV(@var{expr1})}
21985 provided that @code{DV(@var{expr1})} = @code{DV(@var{expr2})}.
21986 If this condition is not met then the construct is illegal.
21989 @code{DV(@var{expr1} * @var{expr2})} is @code{DV(@var{expr1})} + @code{DV(@var{expr2})},
21990 and @code{DV(@var{expr1} / @var{expr2})} = @code{DV(@var{expr1})} - @code{DV(@var{expr2})}.
21991 In this context if one of the `expr's is dimensionless then its empty
21992 dimension vector is treated as @code{(others => 0)}.
21995 @code{DV(@var{expr} ** @var{power})} is `power' * @code{DV(@var{expr})},
21996 provided that `power' is a static rational value. If this condition is not
21997 met then the construct is illegal.
22000 Note that, by the above rules, it is illegal to use binary “+” or “-” to
22001 combine a dimensioned and dimensionless value. Thus an expression such as
22002 @code{acc-10.0} is illegal, where @code{acc} is an object of subtype
22003 @code{Acceleration}.
22005 The dimensionality checks for relationals use the same rules as
22006 for “+” and “-”, except when comparing to a literal; thus
22024 and is thus illegal, but
22033 is accepted with a warning. Analogously a conditional expression requires the
22034 same dimension vector for each branch (with no exception for literals).
22036 The dimension vector of a type conversion @code{T(@var{expr})} is defined
22037 as follows, based on the nature of @code{T}:
22043 If @code{T} is a dimensioned subtype then @code{DV(T(@var{expr}))} is @code{DV(T)}
22044 provided that either `expr' is dimensionless or
22045 @code{DV(T)} = @code{DV(@var{expr})}. The conversion is illegal
22046 if `expr' is dimensioned and @code{DV(@var{expr})} /= @code{DV(T)}.
22047 Note that vector equality does not require that the corresponding
22048 Unit_Names be the same.
22050 As a consequence of the above rule, it is possible to convert between
22051 different dimension systems that follow the same international system
22052 of units, with the seven physical components given in the standard order
22053 (length, mass, time, etc.). Thus a length in meters can be converted to
22054 a length in inches (with a suitable conversion factor) but cannot be
22055 converted, for example, to a mass in pounds.
22058 If @code{T} is the base type for `expr' (and the dimensionless root type of
22059 the dimension system), then @code{DV(T(@var{expr}))} is @code{DV(expr)}.
22060 Thus, if `expr' is of a dimensioned subtype of @code{T}, the conversion may
22061 be regarded as a “view conversion” that preserves dimensionality.
22063 This rule makes it possible to write generic code that can be instantiated
22064 with compatible dimensioned subtypes. The generic unit will contain
22065 conversions that will consequently be present in instantiations, but
22066 conversions to the base type will preserve dimensionality and make it
22067 possible to write generic code that is correct with respect to
22071 Otherwise (i.e., @code{T} is neither a dimensioned subtype nor a dimensionable
22072 base type), @code{DV(T(@var{expr}))} is the empty vector. Thus a dimensioned
22073 value can be explicitly converted to a non-dimensioned subtype, which
22074 of course then escapes dimensionality analysis.
22077 The dimension vector for a type qualification @code{T'(@var{expr})} is the same
22078 as for the type conversion @code{T(@var{expr})}.
22080 An assignment statement
22089 requires @code{DV(Source)} = @code{DV(Target)}, and analogously for parameter
22090 passing (the dimension vector for the actual parameter must be equal to the
22091 dimension vector for the formal parameter).
22093 @node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
22094 @anchor{gnat_ugn/gnat_and_program_execution id52}@anchor{14d}@anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{1aa}
22095 @section Stack Related Facilities
22098 This section describes some useful tools associated with stack
22099 checking and analysis. In
22100 particular, it deals with dynamic and static stack usage measurements.
22103 * Stack Overflow Checking::
22104 * Static Stack Usage Analysis::
22105 * Dynamic Stack Usage Analysis::
22109 @node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
22110 @anchor{gnat_ugn/gnat_and_program_execution id53}@anchor{1ab}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{e7}
22111 @subsection Stack Overflow Checking
22114 @geindex Stack Overflow Checking
22116 @geindex -fstack-check (gcc)
22118 For most operating systems, @code{gcc} does not perform stack overflow
22119 checking by default. This means that if the main environment task or
22120 some other task exceeds the available stack space, then unpredictable
22121 behavior will occur. Most native systems offer some level of protection by
22122 adding a guard page at the end of each task stack. This mechanism is usually
22123 not enough for dealing properly with stack overflow situations because
22124 a large local variable could “jump” above the guard page.
22125 Furthermore, when the
22126 guard page is hit, there may not be any space left on the stack for executing
22127 the exception propagation code. Enabling stack checking avoids
22130 To activate stack checking, compile all units with the @code{gcc} option
22131 @code{-fstack-check}. For example:
22136 $ gcc -c -fstack-check package1.adb
22140 Units compiled with this option will generate extra instructions to check
22141 that any use of the stack (for procedure calls or for declaring local
22142 variables in declare blocks) does not exceed the available stack space.
22143 If the space is exceeded, then a @code{Storage_Error} exception is raised.
22145 For declared tasks, the default stack size is defined by the GNAT runtime,
22146 whose size may be modified at bind time through the @code{-d} bind switch
22147 (@ref{112,,Switches for gnatbind}). Task specific stack sizes may be set using the
22148 @code{Storage_Size} pragma.
22150 For the environment task, the stack size is determined by the operating system.
22151 Consequently, to modify the size of the environment task please refer to your
22152 operating system documentation.
22154 @node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
22155 @anchor{gnat_ugn/gnat_and_program_execution id54}@anchor{1ac}@anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{e8}
22156 @subsection Static Stack Usage Analysis
22159 @geindex Static Stack Usage Analysis
22161 @geindex -fstack-usage
22163 A unit compiled with @code{-fstack-usage} will generate an extra file
22165 the maximum amount of stack used, on a per-function basis.
22166 The file has the same
22167 basename as the target object file with a @code{.su} extension.
22168 Each line of this file is made up of three fields:
22174 The name of the function.
22180 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
22183 The second field corresponds to the size of the known part of the function
22186 The qualifier @code{static} means that the function frame size
22188 It usually means that all local variables have a static size.
22189 In this case, the second field is a reliable measure of the function stack
22192 The qualifier @code{dynamic} means that the function frame size is not static.
22193 It happens mainly when some local variables have a dynamic size. When this
22194 qualifier appears alone, the second field is not a reliable measure
22195 of the function stack analysis. When it is qualified with @code{bounded}, it
22196 means that the second field is a reliable maximum of the function stack
22199 A unit compiled with @code{-Wstack-usage} will issue a warning for each
22200 subprogram whose stack usage might be larger than the specified amount of
22201 bytes. The wording is in keeping with the qualifier documented above.
22203 @node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
22204 @anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{115}@anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{1ad}
22205 @subsection Dynamic Stack Usage Analysis
22208 It is possible to measure the maximum amount of stack used by a task, by
22209 adding a switch to @code{gnatbind}, as:
22214 $ gnatbind -u0 file
22218 With this option, at each task termination, its stack usage is output on
22220 Note that this switch is not compatible with tools like
22221 Valgrind and DrMemory; they will report errors.
22223 It is not always convenient to output the stack usage when the program
22224 is still running. Hence, it is possible to delay this output until program
22225 termination. for a given number of tasks specified as the argument of the
22226 @code{-u} option. For instance:
22231 $ gnatbind -u100 file
22235 will buffer the stack usage information of the first 100 tasks to terminate and
22236 output this info at program termination. Results are displayed in four
22242 Index | Task Name | Stack Size | Stack Usage
22252 `Index' is a number associated with each task.
22255 `Task Name' is the name of the task analyzed.
22258 `Stack Size' is the maximum size for the stack.
22261 `Stack Usage' is the measure done by the stack analyzer.
22262 In order to prevent overflow, the stack
22263 is not entirely analyzed, and it’s not possible to know exactly how
22264 much has actually been used.
22267 By default the environment task stack, the stack that contains the main unit,
22268 is not processed. To enable processing of the environment task stack, the
22269 environment variable GNAT_STACK_LIMIT needs to be set to the maximum size of
22270 the environment task stack. This amount is given in kilobytes. For example:
22275 $ set GNAT_STACK_LIMIT 1600
22279 would specify to the analyzer that the environment task stack has a limit
22280 of 1.6 megabytes. Any stack usage beyond this will be ignored by the analysis.
22282 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
22283 stack-usage reports at run time. See its body for the details.
22285 @node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
22286 @anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{14e}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{1ae}
22287 @section Memory Management Issues
22290 This section describes some useful memory pools provided in the GNAT library
22291 and in particular the GNAT Debug Pool facility, which can be used to detect
22292 incorrect uses of access values (including ‘dangling references’).
22296 * Some Useful Memory Pools::
22297 * The GNAT Debug Pool Facility::
22301 @node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
22302 @anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{1af}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{1b0}
22303 @subsection Some Useful Memory Pools
22306 @geindex Memory Pool
22311 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
22312 storage pool. Allocations use the standard system call @code{malloc} while
22313 deallocations use the standard system call @code{free}. No reclamation is
22314 performed when the pool goes out of scope. For performance reasons, the
22315 standard default Ada allocators/deallocators do not use any explicit storage
22316 pools but if they did, they could use this storage pool without any change in
22317 behavior. That is why this storage pool is used when the user
22318 manages to make the default implicit allocator explicit as in this example:
22323 type T1 is access Something;
22324 -- no Storage pool is defined for T2
22326 type T2 is access Something_Else;
22327 for T2'Storage_Pool use T1'Storage_Pool;
22328 -- the above is equivalent to
22329 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
22333 The @code{System.Pool_Local} package offers the @code{Unbounded_Reclaim_Pool} storage
22334 pool. The allocation strategy is similar to @code{Pool_Local}
22335 except that the all
22336 storage allocated with this pool is reclaimed when the pool object goes out of
22337 scope. This pool provides a explicit mechanism similar to the implicit one
22338 provided by several Ada 83 compilers for allocations performed through a local
22339 access type and whose purpose was to reclaim memory when exiting the
22340 scope of a given local access. As an example, the following program does not
22341 leak memory even though it does not perform explicit deallocation:
22346 with System.Pool_Local;
22347 procedure Pooloc1 is
22348 procedure Internal is
22349 type A is access Integer;
22350 X : System.Pool_Local.Unbounded_Reclaim_Pool;
22351 for A'Storage_Pool use X;
22354 for I in 1 .. 50 loop
22359 for I in 1 .. 100 loop
22366 The @code{System.Pool_Size} package implements the @code{Stack_Bounded_Pool} used when
22367 @code{Storage_Size} is specified for an access type.
22368 The whole storage for the pool is
22369 allocated at once, usually on the stack at the point where the access type is
22370 elaborated. It is automatically reclaimed when exiting the scope where the
22371 access type is defined. This package is not intended to be used directly by the
22372 user and it is implicitly used for each such declaration:
22377 type T1 is access Something;
22378 for T1'Storage_Size use 10_000;
22382 @node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
22383 @anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{1b1}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{1b2}
22384 @subsection The GNAT Debug Pool Facility
22387 @geindex Debug Pool
22391 @geindex memory corruption
22393 The use of unchecked deallocation and unchecked conversion can easily
22394 lead to incorrect memory references. The problems generated by such
22395 references are usually difficult to tackle because the symptoms can be
22396 very remote from the origin of the problem. In such cases, it is
22397 very helpful to detect the problem as early as possible. This is the
22398 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
22400 In order to use the GNAT specific debugging pool, the user must
22401 associate a debug pool object with each of the access types that may be
22402 related to suspected memory problems. See Ada Reference Manual 13.11.
22407 type Ptr is access Some_Type;
22408 Pool : GNAT.Debug_Pools.Debug_Pool;
22409 for Ptr'Storage_Pool use Pool;
22413 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
22414 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
22415 allow the user to redefine allocation and deallocation strategies. They
22416 also provide a checkpoint for each dereference, through the use of
22417 the primitive operation @code{Dereference} which is implicitly called at
22418 each dereference of an access value.
22420 Once an access type has been associated with a debug pool, operations on
22421 values of the type may raise four distinct exceptions,
22422 which correspond to four potential kinds of memory corruption:
22428 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
22431 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
22434 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
22437 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
22440 For types associated with a Debug_Pool, dynamic allocation is performed using
22441 the standard GNAT allocation routine. References to all allocated chunks of
22442 memory are kept in an internal dictionary. Several deallocation strategies are
22443 provided, whereupon the user can choose to release the memory to the system,
22444 keep it allocated for further invalid access checks, or fill it with an easily
22445 recognizable pattern for debug sessions. The memory pattern is the old IBM
22446 hexadecimal convention: @code{16#DEADBEEF#}.
22448 See the documentation in the file g-debpoo.ads for more information on the
22449 various strategies.
22451 Upon each dereference, a check is made that the access value denotes a
22452 properly allocated memory location. Here is a complete example of use of
22453 @code{Debug_Pools}, that includes typical instances of memory corruption:
22458 with GNAT.IO; use GNAT.IO;
22459 with Ada.Unchecked_Deallocation;
22460 with Ada.Unchecked_Conversion;
22461 with GNAT.Debug_Pools;
22462 with System.Storage_Elements;
22463 with Ada.Exceptions; use Ada.Exceptions;
22464 procedure Debug_Pool_Test is
22466 type T is access Integer;
22467 type U is access all T;
22469 P : GNAT.Debug_Pools.Debug_Pool;
22470 for T'Storage_Pool use P;
22472 procedure Free is new Ada.Unchecked_Deallocation (Integer, T);
22473 function UC is new Ada.Unchecked_Conversion (U, T);
22476 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
22486 Put_Line (Integer'Image(B.all));
22488 when E : others => Put_Line ("raised: " & Exception_Name (E));
22493 when E : others => Put_Line ("raised: " & Exception_Name (E));
22497 Put_Line (Integer'Image(B.all));
22499 when E : others => Put_Line ("raised: " & Exception_Name (E));
22504 when E : others => Put_Line ("raised: " & Exception_Name (E));
22507 end Debug_Pool_Test;
22511 The debug pool mechanism provides the following precise diagnostics on the
22512 execution of this erroneous program:
22518 Total allocated bytes : 0
22519 Total deallocated bytes : 0
22520 Current Water Mark: 0
22524 Total allocated bytes : 8
22525 Total deallocated bytes : 0
22526 Current Water Mark: 8
22529 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
22530 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
22531 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
22532 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
22534 Total allocated bytes : 8
22535 Total deallocated bytes : 4
22536 Current Water Mark: 4
22542 @c -- Non-breaking space in running text
22543 @c -- E.g. Ada |nbsp| 95
22545 @node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
22546 @anchor{gnat_ugn/platform_specific_information doc}@anchor{1b3}@anchor{gnat_ugn/platform_specific_information id1}@anchor{1b4}@anchor{gnat_ugn/platform_specific_information platform-specific-information}@anchor{d}
22547 @chapter Platform-Specific Information
22550 This appendix contains information relating to the implementation
22551 of run-time libraries on various platforms and also covers topics
22552 related to the GNAT implementation on specific Operating Systems.
22555 * Run-Time Libraries::
22556 * Specifying a Run-Time Library::
22557 * GNU/Linux Topics::
22558 * Microsoft Windows Topics::
22563 @node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
22564 @anchor{gnat_ugn/platform_specific_information id2}@anchor{1b5}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{1b6}
22565 @section Run-Time Libraries
22568 @geindex Tasking and threads libraries
22570 @geindex Threads libraries and tasking
22572 @geindex Run-time libraries (platform-specific information)
22574 The GNAT run-time implementation may vary with respect to both the
22575 underlying threads library and the exception-handling scheme.
22576 For threads support, the default run-time will bind to the thread
22577 package of the underlying operating system.
22579 For exception handling, either or both of two models are supplied:
22583 @geindex Zero-Cost Exceptions
22585 @geindex ZCX (Zero-Cost Exceptions)
22592 `Zero-Cost Exceptions' (“ZCX”),
22593 which uses binder-generated tables that
22594 are interrogated at run time to locate a handler.
22596 @geindex setjmp/longjmp Exception Model
22598 @geindex SJLJ (setjmp/longjmp Exception Model)
22601 `setjmp / longjmp' (‘SJLJ’),
22602 which uses dynamically-set data to establish
22603 the set of handlers
22606 Most programs should experience a substantial speed improvement by
22607 being compiled with a ZCX run-time.
22608 This is especially true for
22609 tasking applications or applications with many exception handlers.
22610 Note however that the ZCX run-time does not support asynchronous abort
22611 of tasks (@code{abort} and @code{select-then-abort} constructs) and will instead
22612 implement abort by polling points in the runtime. You can also add additional
22613 polling points explicitly if needed in your application via @code{pragma
22616 This section summarizes which combinations of threads and exception support
22617 are supplied on various GNAT platforms.
22620 * Summary of Run-Time Configurations::
22624 @node Summary of Run-Time Configurations,,,Run-Time Libraries
22625 @anchor{gnat_ugn/platform_specific_information id3}@anchor{1b7}@anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{1b8}
22626 @subsection Summary of Run-Time Configurations
22630 @multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx}
22687 native Win32 threads
22699 native Win32 threads
22724 @node Specifying a Run-Time Library,GNU/Linux Topics,Run-Time Libraries,Platform-Specific Information
22725 @anchor{gnat_ugn/platform_specific_information id4}@anchor{1b9}@anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{1ba}
22726 @section Specifying a Run-Time Library
22729 The @code{adainclude} subdirectory containing the sources of the GNAT
22730 run-time library, and the @code{adalib} subdirectory containing the
22731 @code{ALI} files and the static and/or shared GNAT library, are located
22732 in the gcc target-dependent area:
22737 target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
22741 As indicated above, on some platforms several run-time libraries are supplied.
22742 These libraries are installed in the target dependent area and
22743 contain a complete source and binary subdirectory. The detailed description
22744 below explains the differences between the different libraries in terms of
22745 their thread support.
22747 The default run-time library (when GNAT is installed) is `rts-native'.
22748 This default run-time is selected by the means of soft links.
22749 For example on x86-linux:
22752 @c -- $(target-dir)
22754 @c -- +--- adainclude----------+
22756 @c -- +--- adalib-----------+ |
22758 @c -- +--- rts-native | |
22760 @c -- | +--- adainclude <---+
22762 @c -- | +--- adalib <----+
22764 @c -- +--- rts-sjlj
22766 @c -- +--- adainclude
22774 _______/ / \ \_________________
22777 ADAINCLUDE ADALIB rts-native rts-sjlj
22782 +-------------> adainclude adalib adainclude adalib
22785 +---------------------+
22787 Run-Time Library Directory Structure
22788 (Upper-case names and dotted/dashed arrows represent soft links)
22791 If the `rts-sjlj' library is to be selected on a permanent basis,
22792 these soft links can be modified with the following commands:
22798 $ rm -f adainclude adalib
22799 $ ln -s rts-sjlj/adainclude adainclude
22800 $ ln -s rts-sjlj/adalib adalib
22804 Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
22805 @code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
22806 @code{$target/ada_object_path}.
22808 @geindex --RTS option
22810 Selecting another run-time library temporarily can be
22811 achieved by using the @code{--RTS} switch, e.g., @code{--RTS=sjlj}
22812 @anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy}@anchor{1bb}
22813 @geindex SCHED_FIFO scheduling policy
22815 @geindex SCHED_RR scheduling policy
22817 @geindex SCHED_OTHER scheduling policy
22820 * Choosing the Scheduling Policy::
22824 @node Choosing the Scheduling Policy,,,Specifying a Run-Time Library
22825 @anchor{gnat_ugn/platform_specific_information id5}@anchor{1bc}
22826 @subsection Choosing the Scheduling Policy
22829 When using a POSIX threads implementation, you have a choice of several
22830 scheduling policies: @code{SCHED_FIFO}, @code{SCHED_RR} and @code{SCHED_OTHER}.
22832 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22833 or @code{SCHED_RR} requires special (e.g., root) privileges.
22835 @geindex pragma Time_Slice
22837 @geindex -T0 option
22839 @geindex pragma Task_Dispatching_Policy
22841 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22843 you can use one of the following:
22849 @code{pragma Time_Slice (0.0)}
22852 the corresponding binder option @code{-T0}
22855 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22858 To specify @code{SCHED_RR},
22859 you should use @code{pragma Time_Slice} with a
22860 value greater than 0.0, or else use the corresponding @code{-T}
22863 To make sure a program is running as root, you can put something like
22864 this in a library package body in your application:
22869 function geteuid return Integer;
22870 pragma Import (C, geteuid, "geteuid");
22871 Ignore : constant Boolean :=
22872 (if geteuid = 0 then True else raise Program_Error with "must be root");
22876 It gets the effective user id, and if it’s not 0 (i.e. root), it raises
22877 Program_Error. Note that if you re running the code in a container, this may
22878 not be sufficient, as you may have sufficient priviledge on the container,
22879 but not on the host machine running the container, so check that you also
22880 have sufficient priviledge for running the container image.
22886 @node GNU/Linux Topics,Microsoft Windows Topics,Specifying a Run-Time Library,Platform-Specific Information
22887 @anchor{gnat_ugn/platform_specific_information gnu-linux-topics}@anchor{1bd}@anchor{gnat_ugn/platform_specific_information id6}@anchor{1be}
22888 @section GNU/Linux Topics
22891 This section describes topics that are specific to GNU/Linux platforms.
22894 * Required Packages on GNU/Linux::
22895 * Position Independent Executable (PIE) Enabled by Default on Linux: Position Independent Executable PIE Enabled by Default on Linux.
22896 * A GNU/Linux Debug Quirk::
22900 @node Required Packages on GNU/Linux,Position Independent Executable PIE Enabled by Default on Linux,,GNU/Linux Topics
22901 @anchor{gnat_ugn/platform_specific_information id7}@anchor{1bf}@anchor{gnat_ugn/platform_specific_information required-packages-on-gnu-linux}@anchor{1c0}
22902 @subsection Required Packages on GNU/Linux
22905 GNAT requires the C library developer’s package to be installed.
22906 The name of of that package depends on your GNU/Linux distribution:
22912 RedHat, SUSE: @code{glibc-devel};
22915 Debian, Ubuntu: @code{libc6-dev} (normally installed by default).
22918 If using the 32-bit version of GNAT on a 64-bit version of GNU/Linux,
22919 you’ll need the 32-bit version of the following packages:
22925 RedHat, SUSE: @code{glibc.i686}, @code{glibc-devel.i686}, @code{ncurses-libs.i686}
22928 SUSE: @code{glibc-locale-base-32bit}
22931 Debian, Ubuntu: @code{libc6:i386}, @code{libc6-dev:i386}, @code{lib32ncursesw5}
22934 Other GNU/Linux distributions might be choosing a different name
22935 for those packages.
22937 @node Position Independent Executable PIE Enabled by Default on Linux,A GNU/Linux Debug Quirk,Required Packages on GNU/Linux,GNU/Linux Topics
22938 @anchor{gnat_ugn/platform_specific_information pie-enabled-by-default-on-linux}@anchor{1c1}@anchor{gnat_ugn/platform_specific_information position-independent-executable-pie-enabled-by-default-on-linux}@anchor{1c2}
22939 @subsection Position Independent Executable (PIE) Enabled by Default on Linux
22942 GNAT generates Position Independent Executable (PIE) code by default.
22943 PIE binaries are loaded into random memory locations, introducing
22944 an additional layer of protection against attacks.
22946 Building PIE binaries requires that all of their dependencies also be
22947 built as Position Independent. If the link of your project fails with
22951 /[...]/ld: /path/to/object/file: relocation R_X86_64_32S against symbol
22952 `symbol name' can not be used when making a PIE object;
22953 recompile with -fPIE
22956 it means the identified object file has not been built as Position
22959 If you are not interested in building PIE binaries, you can simply
22960 turn this feature off by first compiling your code with @code{-fno-pie}
22961 and then by linking with @code{-no-pie} (note the subtle but important
22962 difference in the names of the options – the linker option does `not'
22963 have an @cite{f} after the dash!). When using gprbuild, this is
22964 achieved by updating the `Required_Switches' attribute in package @cite{Compiler}
22965 and, depending on your type of project, either attribute `Switches'
22966 or attribute `Library_Options' in package @cite{Linker}.
22968 On the other hand, if you would like to build PIE binaries and you are
22969 getting the error above, a quick and easy workaround to allow linking
22970 to succeed again is to disable PIE during the link, thus temporarily
22971 lifting the requirement that all dependencies also be Position
22972 Independent code. To do so, you simply need to add @code{-no-pie} to
22973 the list of switches passed to the linker. As part of this workaround,
22974 there is no need to adjust the compiler switches.
22976 From there, to be able to link your binaries with PIE and therefore
22977 drop the @code{-no-pie} workaround, you’ll need to get the identified
22978 dependencies rebuilt with PIE enabled (compiled with @code{-fPIE}
22979 and linked with @code{-pie}).
22981 @node A GNU/Linux Debug Quirk,,Position Independent Executable PIE Enabled by Default on Linux,GNU/Linux Topics
22982 @anchor{gnat_ugn/platform_specific_information a-gnu-linux-debug-quirk}@anchor{1c3}@anchor{gnat_ugn/platform_specific_information id8}@anchor{1c4}
22983 @subsection A GNU/Linux Debug Quirk
22986 On SuSE 15, some kernels have a defect causing issues when debugging
22987 programs using threads or Ada tasks. Due to the lack of documentation
22988 found regarding this kernel issue, we can only provide limited
22989 information about which kernels are impacted: kernel version 5.3.18 is
22990 known to be impacted, and kernels in the 5.14 range or newer are
22991 believed to fix this problem.
22993 The bug affects the debugging of 32-bit processes on a 64-bit system.
22994 Symptoms can vary: Unexpected @code{SIGABRT} signals being received by
22995 the program, “The futex facility returned an unexpected error code”
22996 error message, and inferior programs hanging indefinitely range among
22997 the symptoms most commonly observed.
23001 @node Microsoft Windows Topics,Mac OS Topics,GNU/Linux Topics,Platform-Specific Information
23002 @anchor{gnat_ugn/platform_specific_information id9}@anchor{1c5}@anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{1c6}
23003 @section Microsoft Windows Topics
23006 This section describes topics that are specific to the Microsoft Windows
23011 * Using GNAT on Windows::
23012 * Using a network installation of GNAT::
23013 * CONSOLE and WINDOWS subsystems::
23014 * Temporary Files::
23015 * Disabling Command Line Argument Expansion::
23016 * Windows Socket Timeouts::
23017 * Mixed-Language Programming on Windows::
23018 * Windows Specific Add-Ons::
23022 @node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
23023 @anchor{gnat_ugn/platform_specific_information id10}@anchor{1c7}@anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{1c8}
23024 @subsection Using GNAT on Windows
23027 One of the strengths of the GNAT technology is that its tool set
23028 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
23029 @code{gdb} debugger, etc.) is used in the same way regardless of the
23032 On Windows this tool set is complemented by a number of Microsoft-specific
23033 tools that have been provided to facilitate interoperability with Windows
23034 when this is required. With these tools:
23040 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
23044 You can use any Dynamically Linked Library (DLL) in your Ada code (both
23045 relocatable and non-relocatable DLLs are supported).
23048 You can build Ada DLLs for use in other applications. These applications
23049 can be written in a language other than Ada (e.g., C, C++, etc). Again both
23050 relocatable and non-relocatable Ada DLLs are supported.
23053 You can include Windows resources in your Ada application.
23056 You can use or create COM/DCOM objects.
23059 Immediately below are listed all known general GNAT-for-Windows restrictions.
23060 Other restrictions about specific features like Windows Resources and DLLs
23061 are listed in separate sections below.
23067 It is not possible to use @code{GetLastError} and @code{SetLastError}
23068 when tasking, protected records, or exceptions are used. In these
23069 cases, in order to implement Ada semantics, the GNAT run-time system
23070 calls certain Win32 routines that set the last error variable to 0 upon
23071 success. It should be possible to use @code{GetLastError} and
23072 @code{SetLastError} when tasking, protected record, and exception
23073 features are not used, but it is not guaranteed to work.
23076 It is not possible to link against Microsoft C++ libraries except for
23077 import libraries. Interfacing must be done by the mean of DLLs.
23080 It is possible to link against Microsoft C libraries. Yet the preferred
23081 solution is to use C/C++ compiler that comes with GNAT, since it
23082 doesn’t require having two different development environments and makes the
23083 inter-language debugging experience smoother.
23086 When the compilation environment is located on FAT32 drives, users may
23087 experience recompilations of the source files that have not changed if
23088 Daylight Saving Time (DST) state has changed since the last time files
23089 were compiled. NTFS drives do not have this problem.
23092 No components of the GNAT toolset use any entries in the Windows
23093 registry. The only entries that can be created are file associations and
23094 PATH settings, provided the user has chosen to create them at installation
23095 time, as well as some minimal book-keeping information needed to correctly
23096 uninstall or integrate different GNAT products.
23099 @node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
23100 @anchor{gnat_ugn/platform_specific_information id11}@anchor{1c9}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{1ca}
23101 @subsection Using a network installation of GNAT
23104 Make sure the system on which GNAT is installed is accessible from the
23105 current machine, i.e., the install location is shared over the network.
23106 Shared resources are accessed on Windows by means of UNC paths, which
23107 have the format @code{\\\\server\\sharename\\path}
23109 In order to use such a network installation, simply add the UNC path of the
23110 @code{bin} directory of your GNAT installation in front of your PATH. For
23111 example, if GNAT is installed in @code{\GNAT} directory of a share location
23112 called @code{c-drive} on a machine @code{LOKI}, the following command will
23118 $ path \\loki\c-drive\gnat\bin;%path%`
23122 Be aware that every compilation using the network installation results in the
23123 transfer of large amounts of data across the network and will likely cause
23124 serious performance penalty.
23126 @node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
23127 @anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{1cb}@anchor{gnat_ugn/platform_specific_information id12}@anchor{1cc}
23128 @subsection CONSOLE and WINDOWS subsystems
23131 @geindex CONSOLE Subsystem
23133 @geindex WINDOWS Subsystem
23137 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
23138 (which is the default subsystem) will always create a console when
23139 launching the application. This is not something desirable when the
23140 application has a Windows GUI. To get rid of this console the
23141 application must be using the @code{WINDOWS} subsystem. To do so
23142 the @code{-mwindows} linker option must be specified.
23147 $ gnatmake winprog -largs -mwindows
23151 @node Temporary Files,Disabling Command Line Argument Expansion,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
23152 @anchor{gnat_ugn/platform_specific_information id13}@anchor{1cd}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{1ce}
23153 @subsection Temporary Files
23156 @geindex Temporary files
23158 It is possible to control where temporary files gets created by setting
23161 @geindex environment variable; TMP
23162 @code{TMP} environment variable. The file will be created:
23168 Under the directory pointed to by the
23170 @geindex environment variable; TMP
23171 @code{TMP} environment variable if
23172 this directory exists.
23175 Under @code{c:\temp}, if the
23177 @geindex environment variable; TMP
23178 @code{TMP} environment variable is not
23179 set (or not pointing to a directory) and if this directory exists.
23182 Under the current working directory otherwise.
23185 This allows you to determine exactly where the temporary
23186 file will be created. This is particularly useful in networked
23187 environments where you may not have write access to some
23190 @node Disabling Command Line Argument Expansion,Windows Socket Timeouts,Temporary Files,Microsoft Windows Topics
23191 @anchor{gnat_ugn/platform_specific_information disabling-command-line-argument-expansion}@anchor{1cf}
23192 @subsection Disabling Command Line Argument Expansion
23195 @geindex Command Line Argument Expansion
23197 By default, an executable compiled for the Windows platform will do
23198 the following postprocessing on the arguments passed on the command
23205 If the argument contains the characters @code{*} and/or @code{?}, then
23206 file expansion will be attempted. For example, if the current directory
23207 contains @code{a.txt} and @code{b.txt}, then when calling:
23210 $ my_ada_program *.txt
23213 The following arguments will effectively be passed to the main program
23214 (for example when using @code{Ada.Command_Line.Argument}):
23217 Ada.Command_Line.Argument (1) -> "a.txt"
23218 Ada.Command_Line.Argument (2) -> "b.txt"
23222 Filename expansion can be disabled for a given argument by using single
23223 quotes. Thus, calling:
23226 $ my_ada_program '*.txt'
23232 Ada.Command_Line.Argument (1) -> "*.txt"
23236 Note that if the program is launched from a shell such as Cygwin Bash
23237 then quote removal might be performed by the shell.
23239 In some contexts it might be useful to disable this feature (for example if
23240 the program performs its own argument expansion). In order to do this, a C
23241 symbol needs to be defined and set to @code{0}. You can do this by
23242 adding the following code fragment in one of your Ada units:
23245 Do_Argv_Expansion : Integer := 0;
23246 pragma Export (C, Do_Argv_Expansion, "__gnat_do_argv_expansion");
23249 The results of previous examples will be respectively:
23252 Ada.Command_Line.Argument (1) -> "*.txt"
23258 Ada.Command_Line.Argument (1) -> "'*.txt'"
23261 @node Windows Socket Timeouts,Mixed-Language Programming on Windows,Disabling Command Line Argument Expansion,Microsoft Windows Topics
23262 @anchor{gnat_ugn/platform_specific_information windows-socket-timeouts}@anchor{1d0}
23263 @subsection Windows Socket Timeouts
23266 Microsoft Windows desktops older than @code{8.0} and Microsoft Windows Servers
23267 older than @code{2019} set a socket timeout 500 milliseconds longer than the value
23268 set by setsockopt with @code{SO_RCVTIMEO} and @code{SO_SNDTIMEO} options. The GNAT
23269 runtime makes a correction for the difference in the corresponding Windows
23270 versions. For Windows Server starting with version @code{2019}, the user must
23271 provide a manifest file for the GNAT runtime to be able to recognize that
23272 the Windows version does not need the timeout correction. The manifest file
23273 should be located in the same directory as the executable file, and its file
23274 name must match the executable name suffixed by @code{.manifest}. For example,
23275 if the executable name is @code{sock_wto.exe}, then the manifest file name
23276 has to be @code{sock_wto.exe.manifest}. The manifest file must contain at
23277 least the following data:
23280 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
23281 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
23282 <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
23284 <!-- Windows Vista -->
23285 <supportedOS Id="@{e2011457-1546-43c5-a5fe-008deee3d3f0@}"/>
23287 <supportedOS Id="@{35138b9a-5d96-4fbd-8e2d-a2440225f93a@}"/>
23289 <supportedOS Id="@{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38@}"/>
23290 <!-- Windows 8.1 -->
23291 <supportedOS Id="@{1f676c76-80e1-4239-95bb-83d0f6d0da78@}"/>
23292 <!-- Windows 10 -->
23293 <supportedOS Id="@{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a@}"/>
23299 Without the manifest file, the socket timeout is going to be overcorrected on
23300 these Windows Server versions and the actual time is going to be 500
23301 milliseconds shorter than what was set with GNAT.Sockets.Set_Socket_Option.
23302 Note that on Microsoft Windows versions where correction is necessary, there
23303 is no way to set a socket timeout shorter than 500 ms. If a socket timeout
23304 shorter than 500 ms is needed on these Windows versions, a call to
23305 Check_Selector should be added before any socket read or write operations.
23307 @node Mixed-Language Programming on Windows,Windows Specific Add-Ons,Windows Socket Timeouts,Microsoft Windows Topics
23308 @anchor{gnat_ugn/platform_specific_information id14}@anchor{1d1}@anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{1d2}
23309 @subsection Mixed-Language Programming on Windows
23312 Developing pure Ada applications on Windows is no different than on
23313 other GNAT-supported platforms. However, when developing or porting an
23314 application that contains a mix of Ada and C/C++, the choice of your
23315 Windows C/C++ development environment conditions your overall
23316 interoperability strategy.
23318 If you use @code{gcc} or Microsoft C to compile the non-Ada part of
23319 your application, there are no Windows-specific restrictions that
23320 affect the overall interoperability with your Ada code. If you do want
23321 to use the Microsoft tools for your C++ code, you have two choices:
23327 Encapsulate your C++ code in a DLL to be linked with your Ada
23328 application. In this case, use the Microsoft or whatever environment to
23329 build the DLL and use GNAT to build your executable
23330 (@ref{1d3,,Using DLLs with GNAT}).
23333 Or you can encapsulate your Ada code in a DLL to be linked with the
23334 other part of your application. In this case, use GNAT to build the DLL
23335 (@ref{1d4,,Building DLLs with GNAT Project files}) and use the Microsoft
23336 or whatever environment to build your executable.
23339 In addition to the description about C main in
23340 @ref{2c,,Mixed Language Programming} section, if the C main uses a
23341 stand-alone library it is required on x86-windows to
23342 setup the SEH context. For this the C main must looks like this:
23348 extern void adainit (void);
23349 extern void adafinal (void);
23350 extern void __gnat_initialize(void*);
23351 extern void call_to_ada (void);
23353 int main (int argc, char *argv[])
23357 /* Initialize the SEH context */
23358 __gnat_initialize (&SEH);
23362 /* Then call Ada services in the stand-alone library */
23371 Note that this is not needed on x86_64-windows where the Windows
23372 native SEH support is used.
23375 * Windows Calling Conventions::
23376 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs.
23377 * Using DLLs with GNAT::
23378 * Building DLLs with GNAT Project files::
23379 * Building DLLs with GNAT::
23380 * Building DLLs with gnatdll::
23381 * Ada DLLs and Finalization::
23382 * Creating a Spec for Ada DLLs::
23383 * GNAT and Windows Resources::
23384 * Using GNAT DLLs from Microsoft Visual Studio Applications::
23385 * Debugging a DLL::
23386 * Setting Stack Size from gnatlink::
23387 * Setting Heap Size from gnatlink::
23391 @node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
23392 @anchor{gnat_ugn/platform_specific_information id15}@anchor{1d5}@anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{1d6}
23393 @subsubsection Windows Calling Conventions
23400 This section pertain only to Win32. On Win64 there is a single native
23401 calling convention. All convention specifiers are ignored on this
23404 When a subprogram @code{F} (caller) calls a subprogram @code{G}
23405 (callee), there are several ways to push @code{G}‘s parameters on the
23406 stack and there are several possible scenarios to clean up the stack
23407 upon @code{G}‘s return. A calling convention is an agreed upon software
23408 protocol whereby the responsibilities between the caller (@code{F}) and
23409 the callee (@code{G}) are clearly defined. Several calling conventions
23410 are available for Windows:
23416 @code{C} (Microsoft defined)
23419 @code{Stdcall} (Microsoft defined)
23422 @code{Win32} (GNAT specific)
23425 @code{DLL} (GNAT specific)
23429 * C Calling Convention::
23430 * Stdcall Calling Convention::
23431 * Win32 Calling Convention::
23432 * DLL Calling Convention::
23436 @node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
23437 @anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{1d7}@anchor{gnat_ugn/platform_specific_information id16}@anchor{1d8}
23438 @subsubsection @code{C} Calling Convention
23441 This is the default calling convention used when interfacing to C/C++
23442 routines compiled with either @code{gcc} or Microsoft Visual C++.
23444 In the @code{C} calling convention subprogram parameters are pushed on the
23445 stack by the caller from right to left. The caller itself is in charge of
23446 cleaning up the stack after the call. In addition, the name of a routine
23447 with @code{C} calling convention is mangled by adding a leading underscore.
23449 The name to use on the Ada side when importing (or exporting) a routine
23450 with @code{C} calling convention is the name of the routine. For
23451 instance the C function:
23456 int get_val (long);
23460 should be imported from Ada as follows:
23465 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23466 pragma Import (C, Get_Val, External_Name => "get_val");
23470 Note that in this particular case the @code{External_Name} parameter could
23471 have been omitted since, when missing, this parameter is taken to be the
23472 name of the Ada entity in lower case. When the @code{Link_Name} parameter
23473 is missing, as in the above example, this parameter is set to be the
23474 @code{External_Name} with a leading underscore.
23476 When importing a variable defined in C, you should always use the @code{C}
23477 calling convention unless the object containing the variable is part of a
23478 DLL (in which case you should use the @code{Stdcall} calling
23479 convention, @ref{1d9,,Stdcall Calling Convention}).
23481 @node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
23482 @anchor{gnat_ugn/platform_specific_information id17}@anchor{1da}@anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{1d9}
23483 @subsubsection @code{Stdcall} Calling Convention
23486 This convention, which was the calling convention used for Pascal
23487 programs, is used by Microsoft for all the routines in the Win32 API for
23488 efficiency reasons. It must be used to import any routine for which this
23489 convention was specified.
23491 In the @code{Stdcall} calling convention subprogram parameters are pushed
23492 on the stack by the caller from right to left. The callee (and not the
23493 caller) is in charge of cleaning the stack on routine exit. In addition,
23494 the name of a routine with @code{Stdcall} calling convention is mangled by
23495 adding a leading underscore (as for the @code{C} calling convention) and a
23496 trailing @code{@@@var{nn}}, where @code{nn} is the overall size (in
23497 bytes) of the parameters passed to the routine.
23499 The name to use on the Ada side when importing a C routine with a
23500 @code{Stdcall} calling convention is the name of the C routine. The leading
23501 underscore and trailing @code{@@@var{nn}} are added automatically by
23502 the compiler. For instance the Win32 function:
23507 APIENTRY int get_val (long);
23511 should be imported from Ada as follows:
23516 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23517 pragma Import (Stdcall, Get_Val);
23518 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
23522 As for the @code{C} calling convention, when the @code{External_Name}
23523 parameter is missing, it is taken to be the name of the Ada entity in lower
23524 case. If instead of writing the above import pragma you write:
23529 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23530 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
23534 then the imported routine is @code{_retrieve_val@@4}. However, if instead
23535 of specifying the @code{External_Name} parameter you specify the
23536 @code{Link_Name} as in the following example:
23541 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23542 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
23546 then the imported routine is @code{retrieve_val}, that is, there is no
23547 decoration at all. No leading underscore and no Stdcall suffix
23550 This is especially important as in some special cases a DLL’s entry
23551 point name lacks a trailing @code{@@@var{nn}} while the exported
23552 name generated for a call has it.
23554 It is also possible to import variables defined in a DLL by using an
23555 import pragma for a variable. As an example, if a DLL contains a
23556 variable defined as:
23565 then, to access this variable from Ada you should write:
23570 My_Var : Interfaces.C.int;
23571 pragma Import (Stdcall, My_Var);
23575 Note that to ease building cross-platform bindings this convention
23576 will be handled as a @code{C} calling convention on non-Windows platforms.
23578 @node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
23579 @anchor{gnat_ugn/platform_specific_information id18}@anchor{1db}@anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{1dc}
23580 @subsubsection @code{Win32} Calling Convention
23583 This convention, which is GNAT-specific is fully equivalent to the
23584 @code{Stdcall} calling convention described above.
23586 @node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
23587 @anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{1dd}@anchor{gnat_ugn/platform_specific_information id19}@anchor{1de}
23588 @subsubsection @code{DLL} Calling Convention
23591 This convention, which is GNAT-specific is fully equivalent to the
23592 @code{Stdcall} calling convention described above.
23594 @node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
23595 @anchor{gnat_ugn/platform_specific_information id20}@anchor{1df}@anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{1e0}
23596 @subsubsection Introduction to Dynamic Link Libraries (DLLs)
23601 A Dynamically Linked Library (DLL) is a library that can be shared by
23602 several applications running under Windows. A DLL can contain any number of
23603 routines and variables.
23605 One advantage of DLLs is that you can change and enhance them without
23606 forcing all the applications that depend on them to be relinked or
23607 recompiled. However, you should be aware than all calls to DLL routines are
23608 slower since, as you will understand below, such calls are indirect.
23610 To illustrate the remainder of this section, suppose that an application
23611 wants to use the services of a DLL @code{API.dll}. To use the services
23612 provided by @code{API.dll} you must statically link against the DLL or
23613 an import library which contains a jump table with an entry for each
23614 routine and variable exported by the DLL. In the Microsoft world this
23615 import library is called @code{API.lib}. When using GNAT this import
23616 library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
23617 @code{libAPI.a} or @code{libapi.a} (names are case insensitive).
23619 After you have linked your application with the DLL or the import library
23620 and you run your application, here is what happens:
23626 Your application is loaded into memory.
23629 The DLL @code{API.dll} is mapped into the address space of your
23630 application. This means that:
23636 The DLL will use the stack of the calling thread.
23639 The DLL will use the virtual address space of the calling process.
23642 The DLL will allocate memory from the virtual address space of the calling
23646 Handles (pointers) can be safely exchanged between routines in the DLL
23647 routines and routines in the application using the DLL.
23651 The entries in the jump table (from the import library @code{libAPI.dll.a}
23652 or @code{API.lib} or automatically created when linking against a DLL)
23653 which is part of your application are initialized with the addresses
23654 of the routines and variables in @code{API.dll}.
23657 If present in @code{API.dll}, routines @code{DllMain} or
23658 @code{DllMainCRTStartup} are invoked. These routines typically contain
23659 the initialization code needed for the well-being of the routines and
23660 variables exported by the DLL.
23663 There is an additional point which is worth mentioning. In the Windows
23664 world there are two kind of DLLs: relocatable and non-relocatable
23665 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
23666 in the target application address space. If the addresses of two
23667 non-relocatable DLLs overlap and these happen to be used by the same
23668 application, a conflict will occur and the application will run
23669 incorrectly. Hence, when possible, it is always preferable to use and
23670 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
23671 supported by GNAT. Note that the @code{-s} linker option (see GNU Linker
23672 User’s Guide) removes the debugging symbols from the DLL but the DLL can
23673 still be relocated.
23675 As a side note, an interesting difference between Microsoft DLLs and
23676 Unix shared libraries, is the fact that on most Unix systems all public
23677 routines are exported by default in a Unix shared library, while under
23678 Windows it is possible (but not required) to list exported routines in
23679 a definition file (see @ref{1e1,,The Definition File}).
23681 @node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
23682 @anchor{gnat_ugn/platform_specific_information id21}@anchor{1e2}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{1d3}
23683 @subsubsection Using DLLs with GNAT
23686 To use the services of a DLL, say @code{API.dll}, in your Ada application
23693 The Ada spec for the routines and/or variables you want to access in
23694 @code{API.dll}. If not available this Ada spec must be built from the C/C++
23695 header files provided with the DLL.
23698 The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
23699 mentioned an import library is a statically linked library containing the
23700 import table which will be filled at load time to point to the actual
23701 @code{API.dll} routines. Sometimes you don’t have an import library for the
23702 DLL you want to use. The following sections will explain how to build
23703 one. Note that this is optional.
23706 The actual DLL, @code{API.dll}.
23709 Once you have all the above, to compile an Ada application that uses the
23710 services of @code{API.dll} and whose main subprogram is @code{My_Ada_App},
23711 you simply issue the command
23716 $ gnatmake my_ada_app -largs -lAPI
23720 The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
23721 tells the GNAT linker to look for an import library. The linker will
23722 look for a library name in this specific order:
23728 @code{libAPI.dll.a}
23746 The first three are the GNU style import libraries. The third is the
23747 Microsoft style import libraries. The last two are the actual DLL names.
23749 Note that if the Ada package spec for @code{API.dll} contains the
23755 pragma Linker_Options ("-lAPI");
23759 you do not have to add @code{-largs -lAPI} at the end of the
23760 @code{gnatmake} command.
23762 If any one of the items above is missing you will have to create it
23763 yourself. The following sections explain how to do so using as an
23764 example a fictitious DLL called @code{API.dll}.
23767 * Creating an Ada Spec for the DLL Services::
23768 * Creating an Import Library::
23772 @node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
23773 @anchor{gnat_ugn/platform_specific_information creating-an-ada-spec-for-the-dll-services}@anchor{1e3}@anchor{gnat_ugn/platform_specific_information id22}@anchor{1e4}
23774 @subsubsection Creating an Ada Spec for the DLL Services
23777 A DLL typically comes with a C/C++ header file which provides the
23778 definitions of the routines and variables exported by the DLL. The Ada
23779 equivalent of this header file is a package spec that contains definitions
23780 for the imported entities. If the DLL you intend to use does not come with
23781 an Ada spec you have to generate one such spec yourself. For example if
23782 the header file of @code{API.dll} is a file @code{api.h} containing the
23783 following two definitions:
23793 then the equivalent Ada spec could be:
23798 with Interfaces.C.Strings;
23803 function Get (Str : C.Strings.Chars_Ptr) return C.int;
23806 pragma Import (C, Get);
23807 pragma Import (DLL, Some_Var);
23812 @node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
23813 @anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{1e5}@anchor{gnat_ugn/platform_specific_information id23}@anchor{1e6}
23814 @subsubsection Creating an Import Library
23817 @geindex Import library
23819 If a Microsoft-style import library @code{API.lib} or a GNAT-style
23820 import library @code{libAPI.dll.a} or @code{libAPI.a} is available
23821 with @code{API.dll} you can skip this section. You can also skip this
23822 section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
23823 as in this case it is possible to link directly against the
23824 DLL. Otherwise read on.
23826 @geindex Definition file
23827 @anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{1e1}
23828 @subsubheading The Definition File
23831 As previously mentioned, and unlike Unix systems, the list of symbols
23832 that are exported from a DLL must be provided explicitly in Windows.
23833 The main goal of a definition file is precisely that: list the symbols
23834 exported by a DLL. A definition file (usually a file with a @code{.def}
23835 suffix) has the following structure:
23840 [LIBRARY `@w{`}name`@w{`}]
23841 [DESCRIPTION `@w{`}string`@w{`}]
23843 `@w{`}symbol1`@w{`}
23844 `@w{`}symbol2`@w{`}
23852 @item `LIBRARY name'
23854 This section, which is optional, gives the name of the DLL.
23856 @item `DESCRIPTION string'
23858 This section, which is optional, gives a description string that will be
23859 embedded in the import library.
23863 This section gives the list of exported symbols (procedures, functions or
23864 variables). For instance in the case of @code{API.dll} the @code{EXPORTS}
23865 section of @code{API.def} looks like:
23874 Note that you must specify the correct suffix (@code{@@@var{nn}})
23875 (see @ref{1d6,,Windows Calling Conventions}) for a Stdcall
23876 calling convention function in the exported symbols list.
23878 There can actually be other sections in a definition file, but these
23879 sections are not relevant to the discussion at hand.
23880 @anchor{gnat_ugn/platform_specific_information create-def-file-automatically}@anchor{1e7}
23881 @subsubheading Creating a Definition File Automatically
23884 You can automatically create the definition file @code{API.def}
23885 (see @ref{1e1,,The Definition File}) from a DLL.
23886 For that use the @code{dlltool} program as follows:
23891 $ dlltool API.dll -z API.def --export-all-symbols
23894 Note that if some routines in the DLL have the @code{Stdcall} convention
23895 (@ref{1d6,,Windows Calling Conventions}) with stripped @code{@@@var{nn}}
23896 suffix then you’ll have to edit @code{api.def} to add it, and specify
23897 @code{-k} to @code{gnatdll} when creating the import library.
23899 Here are some hints to find the right @code{@@@var{nn}} suffix.
23905 If you have the Microsoft import library (.lib), it is possible to get
23906 the right symbols by using Microsoft @code{dumpbin} tool (see the
23907 corresponding Microsoft documentation for further details).
23910 $ dumpbin /exports api.lib
23914 If you have a message about a missing symbol at link time the compiler
23915 tells you what symbol is expected. You just have to go back to the
23916 definition file and add the right suffix.
23919 @anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{1e8}
23920 @subsubheading GNAT-Style Import Library
23923 To create a static import library from @code{API.dll} with the GNAT tools
23924 you should create the .def file, then use @code{gnatdll} tool
23925 (see @ref{1e9,,Using gnatdll}) as follows:
23930 $ gnatdll -e API.def -d API.dll
23933 @code{gnatdll} takes as input a definition file @code{API.def} and the
23934 name of the DLL containing the services listed in the definition file
23935 @code{API.dll}. The name of the static import library generated is
23936 computed from the name of the definition file as follows: if the
23937 definition file name is @code{xyz.def}, the import library name will
23938 be @code{libxyz.a}. Note that in the previous example option
23939 @code{-e} could have been removed because the name of the definition
23940 file (before the @code{.def} suffix) is the same as the name of the
23941 DLL (@ref{1e9,,Using gnatdll} for more information about @code{gnatdll}).
23943 @anchor{gnat_ugn/platform_specific_information msvs-style-import-library}@anchor{1ea}
23944 @subsubheading Microsoft-Style Import Library
23947 A Microsoft import library is needed only if you plan to make an
23948 Ada DLL available to applications developed with Microsoft
23949 tools (@ref{1d2,,Mixed-Language Programming on Windows}).
23951 To create a Microsoft-style import library for @code{API.dll} you
23952 should create the .def file, then build the actual import library using
23953 Microsoft’s @code{lib} utility:
23958 $ lib -machine:IX86 -def:API.def -out:API.lib
23961 If you use the above command the definition file @code{API.def} must
23962 contain a line giving the name of the DLL:
23968 See the Microsoft documentation for further details about the usage of
23972 @node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
23973 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{1d4}@anchor{gnat_ugn/platform_specific_information id24}@anchor{1eb}
23974 @subsubsection Building DLLs with GNAT Project files
23980 There is nothing specific to Windows in the build process.
23981 See the `Library Projects' section in the `GNAT Project Manager'
23982 chapter of the `GPRbuild User’s Guide'.
23984 Due to a system limitation, it is not possible under Windows to create threads
23985 when inside the @code{DllMain} routine which is used for auto-initialization
23986 of shared libraries, so it is not possible to have library level tasks in SALs.
23988 @node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
23989 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{1ec}@anchor{gnat_ugn/platform_specific_information id25}@anchor{1ed}
23990 @subsubsection Building DLLs with GNAT
23996 This section explain how to build DLLs using the GNAT built-in DLL
23997 support. With the following procedure it is straight forward to build
23998 and use DLLs with GNAT.
24004 Building object files.
24005 The first step is to build all objects files that are to be included
24006 into the DLL. This is done by using the standard @code{gnatmake} tool.
24010 To build the DLL you must use the @code{gcc} @code{-shared} and
24011 @code{-shared-libgcc} options. It is quite simple to use this method:
24014 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
24017 It is important to note that in this case all symbols found in the
24018 object files are automatically exported. It is possible to restrict
24019 the set of symbols to export by passing to @code{gcc} a definition
24020 file (see @ref{1e1,,The Definition File}).
24024 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
24027 If you use a definition file you must export the elaboration procedures
24028 for every package that required one. Elaboration procedures are named
24029 using the package name followed by “_E”.
24032 Preparing DLL to be used.
24033 For the DLL to be used by client programs the bodies must be hidden
24034 from it and the .ali set with read-only attribute. This is very important
24035 otherwise GNAT will recompile all packages and will not actually use
24036 the code in the DLL. For example:
24040 $ copy *.ads *.ali api.dll apilib
24041 $ attrib +R apilib\\*.ali
24045 At this point it is possible to use the DLL by directly linking
24046 against it. Note that you must use the GNAT shared runtime when using
24047 GNAT shared libraries. This is achieved by using the @code{-shared} binder
24053 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
24057 @node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
24058 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{1ee}@anchor{gnat_ugn/platform_specific_information id26}@anchor{1ef}
24059 @subsubsection Building DLLs with gnatdll
24065 Note that it is preferred to use GNAT Project files
24066 (@ref{1d4,,Building DLLs with GNAT Project files}) or the built-in GNAT
24067 DLL support (@ref{1ec,,Building DLLs with GNAT}) or to build DLLs.
24069 This section explains how to build DLLs containing Ada code using
24070 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
24071 remainder of this section.
24073 The steps required to build an Ada DLL that is to be used by Ada as well as
24074 non-Ada applications are as follows:
24080 You need to mark each Ada entity exported by the DLL with a @code{C} or
24081 @code{Stdcall} calling convention to avoid any Ada name mangling for the
24082 entities exported by the DLL
24083 (see @ref{1f0,,Exporting Ada Entities}). You can
24084 skip this step if you plan to use the Ada DLL only from Ada applications.
24087 Your Ada code must export an initialization routine which calls the routine
24088 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
24089 the Ada code in the DLL (@ref{1f1,,Ada DLLs and Elaboration}). The initialization
24090 routine exported by the Ada DLL must be invoked by the clients of the DLL
24091 to initialize the DLL.
24094 When useful, the DLL should also export a finalization routine which calls
24095 routine @code{adafinal} generated by @code{gnatbind} to perform the
24096 finalization of the Ada code in the DLL (@ref{1f2,,Ada DLLs and Finalization}).
24097 The finalization routine exported by the Ada DLL must be invoked by the
24098 clients of the DLL when the DLL services are no further needed.
24101 You must provide a spec for the services exported by the Ada DLL in each
24102 of the programming languages to which you plan to make the DLL available.
24105 You must provide a definition file listing the exported entities
24106 (@ref{1e1,,The Definition File}).
24109 Finally you must use @code{gnatdll} to produce the DLL and the import
24110 library (@ref{1e9,,Using gnatdll}).
24113 Note that a relocatable DLL stripped using the @code{strip}
24114 binutils tool will not be relocatable anymore. To build a DLL without
24115 debug information pass @code{-largs -s} to @code{gnatdll}. This
24116 restriction does not apply to a DLL built using a Library Project.
24117 See the `Library Projects' section in the `GNAT Project Manager'
24118 chapter of the `GPRbuild User’s Guide'.
24120 @c Limitations_When_Using_Ada_DLLs_from Ada:
24123 * Limitations When Using Ada DLLs from Ada::
24124 * Exporting Ada Entities::
24125 * Ada DLLs and Elaboration::
24129 @node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
24130 @anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{1f3}
24131 @subsubsection Limitations When Using Ada DLLs from Ada
24134 When using Ada DLLs from Ada applications there is a limitation users
24135 should be aware of. Because on Windows the GNAT run-time is not in a DLL of
24136 its own, each Ada DLL includes a part of the GNAT run-time. Specifically,
24137 each Ada DLL includes the services of the GNAT run-time that are necessary
24138 to the Ada code inside the DLL. As a result, when an Ada program uses an
24139 Ada DLL there are two independent GNAT run-times: one in the Ada DLL and
24140 one in the main program.
24142 It is therefore not possible to exchange GNAT run-time objects between the
24143 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
24144 handles (e.g., @code{Text_IO.File_Type}), tasks types, protected objects
24147 It is completely safe to exchange plain elementary, array or record types,
24148 Windows object handles, etc.
24150 @node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
24151 @anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{1f0}@anchor{gnat_ugn/platform_specific_information id27}@anchor{1f4}
24152 @subsubsection Exporting Ada Entities
24155 @geindex Export table
24157 Building a DLL is a way to encapsulate a set of services usable from any
24158 application. As a result, the Ada entities exported by a DLL should be
24159 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
24160 any Ada name mangling. As an example here is an Ada package
24161 @code{API}, spec and body, exporting two procedures, a function, and a
24167 with Interfaces.C; use Interfaces;
24169 Count : C.int := 0;
24170 function Factorial (Val : C.int) return C.int;
24172 procedure Initialize_API;
24173 procedure Finalize_API;
24174 -- Initialization & Finalization routines. More in the next section.
24176 pragma Export (C, Initialize_API);
24177 pragma Export (C, Finalize_API);
24178 pragma Export (C, Count);
24179 pragma Export (C, Factorial);
24184 package body API is
24185 function Factorial (Val : C.int) return C.int is
24188 Count := Count + 1;
24189 for K in 1 .. Val loop
24195 procedure Initialize_API is
24197 pragma Import (C, Adainit);
24200 end Initialize_API;
24202 procedure Finalize_API is
24203 procedure Adafinal;
24204 pragma Import (C, Adafinal);
24212 If the Ada DLL you are building will only be used by Ada applications
24213 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
24214 convention. As an example, the previous package could be written as
24221 Count : Integer := 0;
24222 function Factorial (Val : Integer) return Integer;
24224 procedure Initialize_API;
24225 procedure Finalize_API;
24226 -- Initialization and Finalization routines.
24231 package body API is
24232 function Factorial (Val : Integer) return Integer is
24233 Fact : Integer := 1;
24235 Count := Count + 1;
24236 for K in 1 .. Val loop
24243 -- The remainder of this package body is unchanged.
24248 Note that if you do not export the Ada entities with a @code{C} or
24249 @code{Stdcall} convention you will have to provide the mangled Ada names
24250 in the definition file of the Ada DLL
24251 (@ref{1f5,,Creating the Definition File}).
24253 @node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
24254 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{1f1}@anchor{gnat_ugn/platform_specific_information id28}@anchor{1f6}
24255 @subsubsection Ada DLLs and Elaboration
24258 @geindex DLLs and elaboration
24260 The DLL that you are building contains your Ada code as well as all the
24261 routines in the Ada library that are needed by it. The first thing a
24262 user of your DLL must do is elaborate the Ada code
24263 (@ref{f,,Elaboration Order Handling in GNAT}).
24265 To achieve this you must export an initialization routine
24266 (@code{Initialize_API} in the previous example), which must be invoked
24267 before using any of the DLL services. This elaboration routine must call
24268 the Ada elaboration routine @code{adainit} generated by the GNAT binder
24269 (@ref{a0,,Binding with Non-Ada Main Programs}). See the body of
24270 @code{Initialize_Api} for an example. Note that the GNAT binder is
24271 automatically invoked during the DLL build process by the @code{gnatdll}
24272 tool (@ref{1e9,,Using gnatdll}).
24274 When a DLL is loaded, Windows systematically invokes a routine called
24275 @code{DllMain}. It would therefore be possible to call @code{adainit}
24276 directly from @code{DllMain} without having to provide an explicit
24277 initialization routine. Unfortunately, it is not possible to call
24278 @code{adainit} from the @code{DllMain} if your program has library level
24279 tasks because access to the @code{DllMain} entry point is serialized by
24280 the system (that is, only a single thread can execute ‘through’ it at a
24281 time), which means that the GNAT run-time will deadlock waiting for the
24282 newly created task to complete its initialization.
24284 @node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
24285 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{1f2}@anchor{gnat_ugn/platform_specific_information id29}@anchor{1f7}
24286 @subsubsection Ada DLLs and Finalization
24289 @geindex DLLs and finalization
24291 When the services of an Ada DLL are no longer needed, the client code should
24292 invoke the DLL finalization routine, if available. The DLL finalization
24293 routine is in charge of releasing all resources acquired by the DLL. In the
24294 case of the Ada code contained in the DLL, this is achieved by calling
24295 routine @code{adafinal} generated by the GNAT binder
24296 (@ref{a0,,Binding with Non-Ada Main Programs}).
24297 See the body of @code{Finalize_Api} for an
24298 example. As already pointed out the GNAT binder is automatically invoked
24299 during the DLL build process by the @code{gnatdll} tool
24300 (@ref{1e9,,Using gnatdll}).
24302 @node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
24303 @anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{1f8}@anchor{gnat_ugn/platform_specific_information id30}@anchor{1f9}
24304 @subsubsection Creating a Spec for Ada DLLs
24307 To use the services exported by the Ada DLL from another programming
24308 language (e.g., C), you have to translate the specs of the exported Ada
24309 entities in that language. For instance in the case of @code{API.dll},
24310 the corresponding C header file could look like:
24315 extern int *_imp__count;
24316 #define count (*_imp__count)
24317 int factorial (int);
24321 It is important to understand that when building an Ada DLL to be used by
24322 other Ada applications, you need two different specs for the packages
24323 contained in the DLL: one for building the DLL and the other for using
24324 the DLL. This is because the @code{DLL} calling convention is needed to
24325 use a variable defined in a DLL, but when building the DLL, the variable
24326 must have either the @code{Ada} or @code{C} calling convention. As an
24327 example consider a DLL comprising the following package @code{API}:
24333 Count : Integer := 0;
24335 -- Remainder of the package omitted.
24340 After producing a DLL containing package @code{API}, the spec that
24341 must be used to import @code{API.Count} from Ada code outside of the
24349 pragma Import (DLL, Count);
24355 * Creating the Definition File::
24360 @node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
24361 @anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{1f5}@anchor{gnat_ugn/platform_specific_information id31}@anchor{1fa}
24362 @subsubsection Creating the Definition File
24365 The definition file is the last file needed to build the DLL. It lists
24366 the exported symbols. As an example, the definition file for a DLL
24367 containing only package @code{API} (where all the entities are exported
24368 with a @code{C} calling convention) is:
24381 If the @code{C} calling convention is missing from package @code{API},
24382 then the definition file contains the mangled Ada names of the above
24383 entities, which in this case are:
24392 api__initialize_api
24396 @node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
24397 @anchor{gnat_ugn/platform_specific_information id32}@anchor{1fb}@anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{1e9}
24398 @subsubsection Using @code{gnatdll}
24403 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
24404 and non-Ada sources that make up your DLL have been compiled.
24405 @code{gnatdll} is actually in charge of two distinct tasks: build the
24406 static import library for the DLL and the actual DLL. The form of the
24407 @code{gnatdll} command is
24412 $ gnatdll [ switches ] list-of-files [ -largs opts ]
24416 where @code{list-of-files} is a list of ALI and object files. The object
24417 file list must be the exact list of objects corresponding to the non-Ada
24418 sources whose services are to be included in the DLL. The ALI file list
24419 must be the exact list of ALI files for the corresponding Ada sources
24420 whose services are to be included in the DLL. If @code{list-of-files} is
24421 missing, only the static import library is generated.
24423 You may specify any of the following switches to @code{gnatdll}:
24427 @geindex -a (gnatdll)
24433 @item @code{-a[`address']}
24435 Build a non-relocatable DLL at @code{address}. If @code{address} is not
24436 specified the default address @code{0x11000000} will be used. By default,
24437 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
24438 advise the reader to build relocatable DLL.
24440 @geindex -b (gnatdll)
24442 @item @code{-b `address'}
24444 Set the relocatable DLL base address. By default the address is
24447 @geindex -bargs (gnatdll)
24449 @item @code{-bargs `opts'}
24451 Binder options. Pass @code{opts} to the binder.
24453 @geindex -d (gnatdll)
24455 @item @code{-d `dllfile'}
24457 @code{dllfile} is the name of the DLL. This switch must be present for
24458 @code{gnatdll} to do anything. The name of the generated import library is
24459 obtained algorithmically from @code{dllfile} as shown in the following
24460 example: if @code{dllfile} is @code{xyz.dll}, the import library name is
24461 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
24462 by option @code{-e}) is obtained algorithmically from @code{dllfile}
24463 as shown in the following example:
24464 if @code{dllfile} is @code{xyz.dll}, the definition
24465 file used is @code{xyz.def}.
24467 @geindex -e (gnatdll)
24469 @item @code{-e `deffile'}
24471 @code{deffile} is the name of the definition file.
24473 @geindex -g (gnatdll)
24477 Generate debugging information. This information is stored in the object
24478 file and copied from there to the final DLL file by the linker,
24479 where it can be read by the debugger. You must use the
24480 @code{-g} switch if you plan on using the debugger or the symbolic
24483 @geindex -h (gnatdll)
24487 Help mode. Displays @code{gnatdll} switch usage information.
24489 @geindex -I (gnatdll)
24491 @item @code{-I`dir'}
24493 Direct @code{gnatdll} to search the @code{dir} directory for source and
24494 object files needed to build the DLL.
24495 (@ref{73,,Search Paths and the Run-Time Library (RTL)}).
24497 @geindex -k (gnatdll)
24501 Removes the @code{@@@var{nn}} suffix from the import library’s exported
24502 names, but keeps them for the link names. You must specify this
24503 option if you want to use a @code{Stdcall} function in a DLL for which
24504 the @code{@@@var{nn}} suffix has been removed. This is the case for most
24505 of the Windows NT DLL for example. This option has no effect when
24506 @code{-n} option is specified.
24508 @geindex -l (gnatdll)
24510 @item @code{-l `file'}
24512 The list of ALI and object files used to build the DLL are listed in
24513 @code{file}, instead of being given in the command line. Each line in
24514 @code{file} contains the name of an ALI or object file.
24516 @geindex -n (gnatdll)
24520 No Import. Do not create the import library.
24522 @geindex -q (gnatdll)
24526 Quiet mode. Do not display unnecessary messages.
24528 @geindex -v (gnatdll)
24532 Verbose mode. Display extra information.
24534 @geindex -largs (gnatdll)
24536 @item @code{-largs `opts'}
24538 Linker options. Pass @code{opts} to the linker.
24541 @subsubheading @code{gnatdll} Example
24544 As an example the command to build a relocatable DLL from @code{api.adb}
24545 once @code{api.adb} has been compiled and @code{api.def} created is
24550 $ gnatdll -d api.dll api.ali
24554 The above command creates two files: @code{libapi.dll.a} (the import
24555 library) and @code{api.dll} (the actual DLL). If you want to create
24556 only the DLL, just type:
24561 $ gnatdll -d api.dll -n api.ali
24565 Alternatively if you want to create just the import library, type:
24570 $ gnatdll -d api.dll
24574 @subsubheading @code{gnatdll} behind the Scenes
24577 This section details the steps involved in creating a DLL. @code{gnatdll}
24578 does these steps for you. Unless you are interested in understanding what
24579 goes on behind the scenes, you should skip this section.
24581 We use the previous example of a DLL containing the Ada package @code{API},
24582 to illustrate the steps necessary to build a DLL. The starting point is a
24583 set of objects that will make up the DLL and the corresponding ALI
24584 files. In the case of this example this means that @code{api.o} and
24585 @code{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
24592 @code{gnatdll} builds the base file (@code{api.base}). A base file gives
24593 the information necessary to generate relocation information for the
24598 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
24601 In addition to the base file, the @code{gnatlink} command generates an
24602 output file @code{api.jnk} which can be discarded. The @code{-mdll} switch
24603 asks @code{gnatlink} to generate the routines @code{DllMain} and
24604 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
24605 is loaded into memory.
24608 @code{gnatdll} uses @code{dlltool} (see @ref{1fc,,Using dlltool}) to build the
24609 export table (@code{api.exp}). The export table contains the relocation
24610 information in a form which can be used during the final link to ensure
24611 that the Windows loader is able to place the DLL anywhere in memory.
24614 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
24615 --output-exp api.exp
24619 @code{gnatdll} builds the base file using the new export table. Note that
24620 @code{gnatbind} must be called once again since the binder generated file
24621 has been deleted during the previous call to @code{gnatlink}.
24625 $ gnatlink api -o api.jnk api.exp -mdll
24626 -Wl,--base-file,api.base
24630 @code{gnatdll} builds the new export table using the new base file and
24631 generates the DLL import library @code{libAPI.dll.a}.
24634 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
24635 --output-exp api.exp --output-lib libAPI.a
24639 Finally @code{gnatdll} builds the relocatable DLL using the final export
24644 $ gnatlink api api.exp -o api.dll -mdll
24647 @anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{1fc}
24648 @subsubheading Using @code{dlltool}
24651 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
24652 DLLs and static import libraries. This section summarizes the most
24653 common @code{dlltool} switches. The form of the @code{dlltool} command
24659 $ dlltool [`switches`]
24663 @code{dlltool} switches include:
24665 @geindex --base-file (dlltool)
24670 @item @code{--base-file `basefile'}
24672 Read the base file @code{basefile} generated by the linker. This switch
24673 is used to create a relocatable DLL.
24676 @geindex --def (dlltool)
24681 @item @code{--def `deffile'}
24683 Read the definition file.
24686 @geindex --dllname (dlltool)
24691 @item @code{--dllname `name'}
24693 Gives the name of the DLL. This switch is used to embed the name of the
24694 DLL in the static import library generated by @code{dlltool} with switch
24695 @code{--output-lib}.
24698 @geindex -k (dlltool)
24705 Kill @code{@@@var{nn}} from exported names
24706 (@ref{1d6,,Windows Calling Conventions}
24707 for a discussion about @code{Stdcall}-style symbols).
24710 @geindex --help (dlltool)
24715 @item @code{--help}
24717 Prints the @code{dlltool} switches with a concise description.
24720 @geindex --output-exp (dlltool)
24725 @item @code{--output-exp `exportfile'}
24727 Generate an export file @code{exportfile}. The export file contains the
24728 export table (list of symbols in the DLL) and is used to create the DLL.
24731 @geindex --output-lib (dlltool)
24736 @item @code{--output-lib `libfile'}
24738 Generate a static import library @code{libfile}.
24741 @geindex -v (dlltool)
24751 @geindex --as (dlltool)
24756 @item @code{--as `assembler-name'}
24758 Use @code{assembler-name} as the assembler. The default is @code{as}.
24761 @node GNAT and Windows Resources,Using GNAT DLLs from Microsoft Visual Studio Applications,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
24762 @anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{1fd}@anchor{gnat_ugn/platform_specific_information id33}@anchor{1fe}
24763 @subsubsection GNAT and Windows Resources
24769 Resources are an easy way to add Windows specific objects to your
24770 application. The objects that can be added as resources include:
24800 version information
24803 For example, a version information resource can be defined as follow and
24804 embedded into an executable or DLL:
24806 A version information resource can be used to embed information into an
24807 executable or a DLL. These information can be viewed using the file properties
24808 from the Windows Explorer. Here is an example of a version information
24815 FILEVERSION 1,0,0,0
24816 PRODUCTVERSION 1,0,0,0
24818 BLOCK "StringFileInfo"
24822 VALUE "CompanyName", "My Company Name"
24823 VALUE "FileDescription", "My application"
24824 VALUE "FileVersion", "1.0"
24825 VALUE "InternalName", "my_app"
24826 VALUE "LegalCopyright", "My Name"
24827 VALUE "OriginalFilename", "my_app.exe"
24828 VALUE "ProductName", "My App"
24829 VALUE "ProductVersion", "1.0"
24833 BLOCK "VarFileInfo"
24835 VALUE "Translation", 0x809, 1252
24841 The value @code{0809} (langID) is for the U.K English language and
24842 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
24845 This section explains how to build, compile and use resources. Note that this
24846 section does not cover all resource objects, for a complete description see
24847 the corresponding Microsoft documentation.
24850 * Building Resources::
24851 * Compiling Resources::
24852 * Using Resources::
24856 @node Building Resources,Compiling Resources,,GNAT and Windows Resources
24857 @anchor{gnat_ugn/platform_specific_information building-resources}@anchor{1ff}@anchor{gnat_ugn/platform_specific_information id34}@anchor{200}
24858 @subsubsection Building Resources
24864 A resource file is an ASCII file. By convention resource files have an
24865 @code{.rc} extension.
24866 The easiest way to build a resource file is to use Microsoft tools
24867 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
24868 @code{dlgedit.exe} to build dialogs.
24869 It is always possible to build an @code{.rc} file yourself by writing a
24872 It is not our objective to explain how to write a resource file. A
24873 complete description of the resource script language can be found in the
24874 Microsoft documentation.
24876 @node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
24877 @anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{201}@anchor{gnat_ugn/platform_specific_information id35}@anchor{202}
24878 @subsubsection Compiling Resources
24888 This section describes how to build a GNAT-compatible (COFF) object file
24889 containing the resources. This is done using the Resource Compiler
24890 @code{windres} as follows:
24895 $ windres -i myres.rc -o myres.o
24899 By default @code{windres} will run @code{gcc} to preprocess the @code{.rc}
24900 file. You can specify an alternate preprocessor (usually named
24901 @code{cpp.exe}) using the @code{windres} @code{--preprocessor}
24902 parameter. A list of all possible options may be obtained by entering
24903 the command @code{windres} @code{--help}.
24905 It is also possible to use the Microsoft resource compiler @code{rc.exe}
24906 to produce a @code{.res} file (binary resource file). See the
24907 corresponding Microsoft documentation for further details. In this case
24908 you need to use @code{windres} to translate the @code{.res} file to a
24909 GNAT-compatible object file as follows:
24914 $ windres -i myres.res -o myres.o
24918 @node Using Resources,,Compiling Resources,GNAT and Windows Resources
24919 @anchor{gnat_ugn/platform_specific_information id36}@anchor{203}@anchor{gnat_ugn/platform_specific_information using-resources}@anchor{204}
24920 @subsubsection Using Resources
24926 To include the resource file in your program just add the
24927 GNAT-compatible object file for the resource(s) to the linker
24928 arguments. With @code{gnatmake} this is done by using the @code{-largs}
24934 $ gnatmake myprog -largs myres.o
24938 @node Using GNAT DLLs from Microsoft Visual Studio Applications,Debugging a DLL,GNAT and Windows Resources,Mixed-Language Programming on Windows
24939 @anchor{gnat_ugn/platform_specific_information using-gnat-dll-from-msvs}@anchor{205}@anchor{gnat_ugn/platform_specific_information using-gnat-dlls-from-microsoft-visual-studio-applications}@anchor{206}
24940 @subsubsection Using GNAT DLLs from Microsoft Visual Studio Applications
24943 @geindex Microsoft Visual Studio
24944 @geindex use with GNAT DLLs
24946 This section describes a common case of mixed GNAT/Microsoft Visual Studio
24947 application development, where the main program is developed using MSVS, and
24948 is linked with a DLL developed using GNAT. Such a mixed application should
24949 be developed following the general guidelines outlined above; below is the
24950 cookbook-style sequence of steps to follow:
24956 First develop and build the GNAT shared library using a library project
24957 (let’s assume the project is @code{mylib.gpr}, producing the library @code{libmylib.dll}):
24963 $ gprbuild -p mylib.gpr
24971 Produce a .def file for the symbols you need to interface with, either by
24972 hand or automatically with possibly some manual adjustments
24973 (see @ref{1e7,,Creating Definition File Automatically}):
24979 $ dlltool libmylib.dll -z libmylib.def --export-all-symbols
24987 Make sure that MSVS command-line tools are accessible on the path.
24990 Create the Microsoft-style import library (see @ref{1ea,,MSVS-Style Import Library}):
24996 $ lib -machine:IX86 -def:libmylib.def -out:libmylib.lib
25000 If you are using a 64-bit toolchain, the above becomes…
25005 $ lib -machine:X64 -def:libmylib.def -out:libmylib.lib
25019 $ cl /O2 /MD main.c libmylib.lib
25027 Before running the executable, make sure you have set the PATH to the DLL,
25028 or copy the DLL into into the directory containing the .exe.
25031 @node Debugging a DLL,Setting Stack Size from gnatlink,Using GNAT DLLs from Microsoft Visual Studio Applications,Mixed-Language Programming on Windows
25032 @anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{207}@anchor{gnat_ugn/platform_specific_information id37}@anchor{208}
25033 @subsubsection Debugging a DLL
25036 @geindex DLL debugging
25038 Debugging a DLL is similar to debugging a standard program. But
25039 we have to deal with two different executable parts: the DLL and the
25040 program that uses it. We have the following four possibilities:
25046 The program and the DLL are built with GCC/GNAT.
25049 The program is built with foreign tools and the DLL is built with
25053 The program is built with GCC/GNAT and the DLL is built with
25057 In this section we address only cases one and two above.
25058 There is no point in trying to debug
25059 a DLL with GNU/GDB, if there is no GDB-compatible debugging
25060 information in it. To do so you must use a debugger compatible with the
25061 tools suite used to build the DLL.
25064 * Program and DLL Both Built with GCC/GNAT::
25065 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
25069 @node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
25070 @anchor{gnat_ugn/platform_specific_information id38}@anchor{209}@anchor{gnat_ugn/platform_specific_information program-and-dll-both-built-with-gcc-gnat}@anchor{20a}
25071 @subsubsection Program and DLL Both Built with GCC/GNAT
25074 This is the simplest case. Both the DLL and the program have @code{GDB}
25075 compatible debugging information. It is then possible to break anywhere in
25076 the process. Let’s suppose here that the main procedure is named
25077 @code{ada_main} and that in the DLL there is an entry point named
25080 The DLL (@ref{1e0,,Introduction to Dynamic Link Libraries (DLLs)}) and
25081 program must have been built with the debugging information (see GNAT -g
25082 switch). Here are the step-by-step instructions for debugging it:
25088 Launch @code{GDB} on the main program.
25095 Start the program and stop at the beginning of the main procedure
25101 This step is required to be able to set a breakpoint inside the DLL. As long
25102 as the program is not run, the DLL is not loaded. This has the
25103 consequence that the DLL debugging information is also not loaded, so it is not
25104 possible to set a breakpoint in the DLL.
25107 Set a breakpoint inside the DLL
25110 (gdb) break ada_dll
25115 At this stage a breakpoint is set inside the DLL. From there on
25116 you can use the standard approach to debug the whole program
25117 (@ref{14f,,Running and Debugging Ada Programs}).
25119 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
25120 @anchor{gnat_ugn/platform_specific_information id39}@anchor{20b}@anchor{gnat_ugn/platform_specific_information program-built-with-foreign-tools-and-dll-built-with-gcc-gnat}@anchor{20c}
25121 @subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
25124 In this case things are slightly more complex because it is not possible to
25125 start the main program and then break at the beginning to load the DLL and the
25126 associated DLL debugging information. It is not possible to break at the
25127 beginning of the program because there is no @code{GDB} debugging information,
25128 and therefore there is no direct way of getting initial control. This
25129 section addresses this issue by describing some methods that can be used
25130 to break somewhere in the DLL to debug it.
25132 First suppose that the main procedure is named @code{main} (this is for
25133 example some C code built with Microsoft Visual C) and that there is a
25134 DLL named @code{test.dll} containing an Ada entry point named
25137 The DLL (see @ref{1e0,,Introduction to Dynamic Link Libraries (DLLs)}) must have
25138 been built with debugging information (see the GNAT @code{-g} option).
25140 @subsubheading Debugging the DLL Directly
25147 Find out the executable starting address
25150 $ objdump --file-header main.exe
25153 The starting address is reported on the last line. For example:
25156 main.exe: file format pei-i386
25157 architecture: i386, flags 0x0000010a:
25158 EXEC_P, HAS_DEBUG, D_PAGED
25159 start address 0x00401010
25163 Launch the debugger on the executable.
25170 Set a breakpoint at the starting address, and launch the program.
25173 $ (gdb) break *0x00401010
25177 The program will stop at the given address.
25180 Set a breakpoint on a DLL subroutine.
25183 (gdb) break ada_dll.adb:45
25186 Or if you want to break using a symbol on the DLL, you need first to
25187 select the Ada language (language used by the DLL).
25190 (gdb) set language ada
25191 (gdb) break ada_dll
25195 Continue the program.
25201 This will run the program until it reaches the breakpoint that has been
25202 set. From that point you can use the standard way to debug a program
25203 as described in (@ref{14f,,Running and Debugging Ada Programs}).
25206 It is also possible to debug the DLL by attaching to a running process.
25208 @subsubheading Attaching to a Running Process
25211 @geindex DLL debugging
25212 @geindex attach to process
25214 With @code{GDB} it is always possible to debug a running process by
25215 attaching to it. It is possible to debug a DLL this way. The limitation
25216 of this approach is that the DLL must run long enough to perform the
25217 attach operation. It may be useful for instance to insert a time wasting
25218 loop in the code of the DLL to meet this criterion.
25224 Launch the main program @code{main.exe}.
25231 Use the Windows `Task Manager' to find the process ID. Let’s say
25232 that the process PID for @code{main.exe} is 208.
25242 Attach to the running process to be debugged.
25249 Load the process debugging information.
25252 (gdb) symbol-file main.exe
25256 Break somewhere in the DLL.
25259 (gdb) break ada_dll
25263 Continue process execution.
25270 This last step will resume the process execution, and stop at
25271 the breakpoint we have set. From there you can use the standard
25272 approach to debug a program as described in
25273 @ref{14f,,Running and Debugging Ada Programs}.
25275 @node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
25276 @anchor{gnat_ugn/platform_specific_information id40}@anchor{20d}@anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{129}
25277 @subsubsection Setting Stack Size from @code{gnatlink}
25280 It is possible to specify the program stack size at link time. On modern
25281 versions of Windows, starting with XP, this is mostly useful to set the size of
25282 the main stack (environment task). The other task stacks are set with pragma
25283 Storage_Size or with the `gnatbind -d' command.
25285 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
25286 reserve size of individual tasks, the link-time stack size applies to all
25287 tasks, and pragma Storage_Size has no effect.
25288 In particular, Stack Overflow checks are made against this
25289 link-time specified size.
25291 This setting can be done with @code{gnatlink} using either of the following:
25297 @code{-Xlinker} linker option
25300 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
25303 This sets the stack reserve size to 0x10000 bytes and the stack commit
25304 size to 0x1000 bytes.
25307 @code{-Wl} linker option
25310 $ gnatlink hello -Wl,--stack=0x1000000
25313 This sets the stack reserve size to 0x1000000 bytes. Note that with
25314 @code{-Wl} option it is not possible to set the stack commit size
25315 because the comma is a separator for this option.
25318 @node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
25319 @anchor{gnat_ugn/platform_specific_information id41}@anchor{20e}@anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{12a}
25320 @subsubsection Setting Heap Size from @code{gnatlink}
25323 Under Windows systems, it is possible to specify the program heap size from
25324 @code{gnatlink} using either of the following:
25330 @code{-Xlinker} linker option
25333 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
25336 This sets the heap reserve size to 0x10000 bytes and the heap commit
25337 size to 0x1000 bytes.
25340 @code{-Wl} linker option
25343 $ gnatlink hello -Wl,--heap=0x1000000
25346 This sets the heap reserve size to 0x1000000 bytes. Note that with
25347 @code{-Wl} option it is not possible to set the heap commit size
25348 because the comma is a separator for this option.
25351 @node Windows Specific Add-Ons,,Mixed-Language Programming on Windows,Microsoft Windows Topics
25352 @anchor{gnat_ugn/platform_specific_information win32-specific-addons}@anchor{20f}@anchor{gnat_ugn/platform_specific_information windows-specific-add-ons}@anchor{210}
25353 @subsection Windows Specific Add-Ons
25356 This section describes the Windows specific add-ons.
25364 @node Win32Ada,wPOSIX,,Windows Specific Add-Ons
25365 @anchor{gnat_ugn/platform_specific_information id42}@anchor{211}@anchor{gnat_ugn/platform_specific_information win32ada}@anchor{212}
25366 @subsubsection Win32Ada
25369 Win32Ada is a binding for the Microsoft Win32 API. This binding can be
25370 easily installed from the provided installer. To use the Win32Ada
25371 binding you need to use a project file, and adding a single with_clause
25372 will give you full access to the Win32Ada binding sources and ensure
25373 that the proper libraries are passed to the linker.
25380 for Sources use ...;
25385 To build the application you just need to call gprbuild for the
25386 application’s project, here p.gpr:
25395 @node wPOSIX,,Win32Ada,Windows Specific Add-Ons
25396 @anchor{gnat_ugn/platform_specific_information id43}@anchor{213}@anchor{gnat_ugn/platform_specific_information wposix}@anchor{214}
25397 @subsubsection wPOSIX
25400 wPOSIX is a minimal POSIX binding whose goal is to help with building
25401 cross-platforms applications. This binding is not complete though, as
25402 the Win32 API does not provide the necessary support for all POSIX APIs.
25404 To use the wPOSIX binding you need to use a project file, and adding
25405 a single with_clause will give you full access to the wPOSIX binding
25406 sources and ensure that the proper libraries are passed to the linker.
25413 for Sources use ...;
25418 To build the application you just need to call gprbuild for the
25419 application’s project, here p.gpr:
25428 @node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
25429 @anchor{gnat_ugn/platform_specific_information id44}@anchor{215}@anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{216}
25430 @section Mac OS Topics
25435 This section describes topics that are specific to Apple’s OS X
25439 * Codesigning the Debugger::
25443 @node Codesigning the Debugger,,,Mac OS Topics
25444 @anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{217}
25445 @subsection Codesigning the Debugger
25448 The Darwin Kernel requires the debugger to have special permissions
25449 before it is allowed to control other processes. These permissions
25450 are granted by codesigning the GDB executable. Without these
25451 permissions, the debugger will report error messages such as:
25454 Starting program: /x/y/foo
25455 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
25456 (please check gdb is codesigned - see taskgated(8))
25459 Codesigning requires a certificate. The following procedure explains
25466 Start the Keychain Access application (in
25467 /Applications/Utilities/Keychain Access.app)
25470 Select the Keychain Access -> Certificate Assistant ->
25471 Create a Certificate… menu
25480 Choose a name for the new certificate (this procedure will use
25481 “gdb-cert” as an example)
25484 Set “Identity Type” to “Self Signed Root”
25487 Set “Certificate Type” to “Code Signing”
25490 Activate the “Let me override defaults” option
25494 Click several times on “Continue” until the “Specify a Location
25495 For The Certificate” screen appears, then set “Keychain” to “System”
25498 Click on “Continue” until the certificate is created
25501 Finally, in the view, double-click on the new certificate,
25502 and set “When using this certificate” to “Always Trust”
25505 Exit the Keychain Access application and restart the computer
25506 (this is unfortunately required)
25509 Once a certificate has been created, the debugger can be codesigned
25510 as follow. In a Terminal, run the following command:
25515 $ codesign -f -s "gdb-cert" <gnat_install_prefix>/bin/gdb
25519 where “gdb-cert” should be replaced by the actual certificate
25520 name chosen above, and <gnat_install_prefix> should be replaced by
25521 the location where you installed GNAT. Also, be sure that users are
25522 in the Unix group @code{_developer}.
25524 @node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
25525 @anchor{gnat_ugn/example_of_binder_output doc}@anchor{218}@anchor{gnat_ugn/example_of_binder_output example-of-binder-output-file}@anchor{e}@anchor{gnat_ugn/example_of_binder_output id1}@anchor{219}
25526 @chapter Example of Binder Output File
25529 @geindex Binder output (example)
25531 This Appendix displays the source code for the output file
25532 generated by `gnatbind' for a simple ‘Hello World’ program.
25533 Comments have been added for clarification purposes.
25536 -- The package is called Ada_Main unless this name is actually used
25537 -- as a unit name in the partition, in which case some other unique
25542 package ada_main is
25543 pragma Warnings (Off);
25545 -- The main program saves the parameters (argument count,
25546 -- argument values, environment pointer) in global variables
25547 -- for later access by other units including
25548 -- Ada.Command_Line.
25550 gnat_argc : Integer;
25551 gnat_argv : System.Address;
25552 gnat_envp : System.Address;
25554 -- The actual variables are stored in a library routine. This
25555 -- is useful for some shared library situations, where there
25556 -- are problems if variables are not in the library.
25558 pragma Import (C, gnat_argc);
25559 pragma Import (C, gnat_argv);
25560 pragma Import (C, gnat_envp);
25562 -- The exit status is similarly an external location
25564 gnat_exit_status : Integer;
25565 pragma Import (C, gnat_exit_status);
25567 GNAT_Version : constant String :=
25568 "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
25569 pragma Export (C, GNAT_Version, "__gnat_version");
25571 Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
25572 pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
25574 -- This is the generated adainit routine that performs
25575 -- initialization at the start of execution. In the case
25576 -- where Ada is the main program, this main program makes
25577 -- a call to adainit at program startup.
25580 pragma Export (C, adainit, "adainit");
25582 -- This is the generated adafinal routine that performs
25583 -- finalization at the end of execution. In the case where
25584 -- Ada is the main program, this main program makes a call
25585 -- to adafinal at program termination.
25587 procedure adafinal;
25588 pragma Export (C, adafinal, "adafinal");
25590 -- This routine is called at the start of execution. It is
25591 -- a dummy routine that is used by the debugger to breakpoint
25592 -- at the start of execution.
25594 -- This is the actual generated main program (it would be
25595 -- suppressed if the no main program switch were used). As
25596 -- required by standard system conventions, this program has
25597 -- the external name main.
25601 argv : System.Address;
25602 envp : System.Address)
25604 pragma Export (C, main, "main");
25606 -- The following set of constants give the version
25607 -- identification values for every unit in the bound
25608 -- partition. This identification is computed from all
25609 -- dependent semantic units, and corresponds to the
25610 -- string that would be returned by use of the
25611 -- Body_Version or Version attributes.
25613 -- The following Export pragmas export the version numbers
25614 -- with symbolic names ending in B (for body) or S
25615 -- (for spec) so that they can be located in a link. The
25616 -- information provided here is sufficient to track down
25617 -- the exact versions of units used in a given build.
25619 type Version_32 is mod 2 ** 32;
25620 u00001 : constant Version_32 := 16#8ad6e54a#;
25621 pragma Export (C, u00001, "helloB");
25622 u00002 : constant Version_32 := 16#fbff4c67#;
25623 pragma Export (C, u00002, "system__standard_libraryB");
25624 u00003 : constant Version_32 := 16#1ec6fd90#;
25625 pragma Export (C, u00003, "system__standard_libraryS");
25626 u00004 : constant Version_32 := 16#3ffc8e18#;
25627 pragma Export (C, u00004, "adaS");
25628 u00005 : constant Version_32 := 16#28f088c2#;
25629 pragma Export (C, u00005, "ada__text_ioB");
25630 u00006 : constant Version_32 := 16#f372c8ac#;
25631 pragma Export (C, u00006, "ada__text_ioS");
25632 u00007 : constant Version_32 := 16#2c143749#;
25633 pragma Export (C, u00007, "ada__exceptionsB");
25634 u00008 : constant Version_32 := 16#f4f0cce8#;
25635 pragma Export (C, u00008, "ada__exceptionsS");
25636 u00009 : constant Version_32 := 16#a46739c0#;
25637 pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
25638 u00010 : constant Version_32 := 16#3aac8c92#;
25639 pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
25640 u00011 : constant Version_32 := 16#1d274481#;
25641 pragma Export (C, u00011, "systemS");
25642 u00012 : constant Version_32 := 16#a207fefe#;
25643 pragma Export (C, u00012, "system__soft_linksB");
25644 u00013 : constant Version_32 := 16#467d9556#;
25645 pragma Export (C, u00013, "system__soft_linksS");
25646 u00014 : constant Version_32 := 16#b01dad17#;
25647 pragma Export (C, u00014, "system__parametersB");
25648 u00015 : constant Version_32 := 16#630d49fe#;
25649 pragma Export (C, u00015, "system__parametersS");
25650 u00016 : constant Version_32 := 16#b19b6653#;
25651 pragma Export (C, u00016, "system__secondary_stackB");
25652 u00017 : constant Version_32 := 16#b6468be8#;
25653 pragma Export (C, u00017, "system__secondary_stackS");
25654 u00018 : constant Version_32 := 16#39a03df9#;
25655 pragma Export (C, u00018, "system__storage_elementsB");
25656 u00019 : constant Version_32 := 16#30e40e85#;
25657 pragma Export (C, u00019, "system__storage_elementsS");
25658 u00020 : constant Version_32 := 16#41837d1e#;
25659 pragma Export (C, u00020, "system__stack_checkingB");
25660 u00021 : constant Version_32 := 16#93982f69#;
25661 pragma Export (C, u00021, "system__stack_checkingS");
25662 u00022 : constant Version_32 := 16#393398c1#;
25663 pragma Export (C, u00022, "system__exception_tableB");
25664 u00023 : constant Version_32 := 16#b33e2294#;
25665 pragma Export (C, u00023, "system__exception_tableS");
25666 u00024 : constant Version_32 := 16#ce4af020#;
25667 pragma Export (C, u00024, "system__exceptionsB");
25668 u00025 : constant Version_32 := 16#75442977#;
25669 pragma Export (C, u00025, "system__exceptionsS");
25670 u00026 : constant Version_32 := 16#37d758f1#;
25671 pragma Export (C, u00026, "system__exceptions__machineS");
25672 u00027 : constant Version_32 := 16#b895431d#;
25673 pragma Export (C, u00027, "system__exceptions_debugB");
25674 u00028 : constant Version_32 := 16#aec55d3f#;
25675 pragma Export (C, u00028, "system__exceptions_debugS");
25676 u00029 : constant Version_32 := 16#570325c8#;
25677 pragma Export (C, u00029, "system__img_intB");
25678 u00030 : constant Version_32 := 16#1ffca443#;
25679 pragma Export (C, u00030, "system__img_intS");
25680 u00031 : constant Version_32 := 16#b98c3e16#;
25681 pragma Export (C, u00031, "system__tracebackB");
25682 u00032 : constant Version_32 := 16#831a9d5a#;
25683 pragma Export (C, u00032, "system__tracebackS");
25684 u00033 : constant Version_32 := 16#9ed49525#;
25685 pragma Export (C, u00033, "system__traceback_entriesB");
25686 u00034 : constant Version_32 := 16#1d7cb2f1#;
25687 pragma Export (C, u00034, "system__traceback_entriesS");
25688 u00035 : constant Version_32 := 16#8c33a517#;
25689 pragma Export (C, u00035, "system__wch_conB");
25690 u00036 : constant Version_32 := 16#065a6653#;
25691 pragma Export (C, u00036, "system__wch_conS");
25692 u00037 : constant Version_32 := 16#9721e840#;
25693 pragma Export (C, u00037, "system__wch_stwB");
25694 u00038 : constant Version_32 := 16#2b4b4a52#;
25695 pragma Export (C, u00038, "system__wch_stwS");
25696 u00039 : constant Version_32 := 16#92b797cb#;
25697 pragma Export (C, u00039, "system__wch_cnvB");
25698 u00040 : constant Version_32 := 16#09eddca0#;
25699 pragma Export (C, u00040, "system__wch_cnvS");
25700 u00041 : constant Version_32 := 16#6033a23f#;
25701 pragma Export (C, u00041, "interfacesS");
25702 u00042 : constant Version_32 := 16#ece6fdb6#;
25703 pragma Export (C, u00042, "system__wch_jisB");
25704 u00043 : constant Version_32 := 16#899dc581#;
25705 pragma Export (C, u00043, "system__wch_jisS");
25706 u00044 : constant Version_32 := 16#10558b11#;
25707 pragma Export (C, u00044, "ada__streamsB");
25708 u00045 : constant Version_32 := 16#2e6701ab#;
25709 pragma Export (C, u00045, "ada__streamsS");
25710 u00046 : constant Version_32 := 16#db5c917c#;
25711 pragma Export (C, u00046, "ada__io_exceptionsS");
25712 u00047 : constant Version_32 := 16#12c8cd7d#;
25713 pragma Export (C, u00047, "ada__tagsB");
25714 u00048 : constant Version_32 := 16#ce72c228#;
25715 pragma Export (C, u00048, "ada__tagsS");
25716 u00049 : constant Version_32 := 16#c3335bfd#;
25717 pragma Export (C, u00049, "system__htableB");
25718 u00050 : constant Version_32 := 16#99e5f76b#;
25719 pragma Export (C, u00050, "system__htableS");
25720 u00051 : constant Version_32 := 16#089f5cd0#;
25721 pragma Export (C, u00051, "system__string_hashB");
25722 u00052 : constant Version_32 := 16#3bbb9c15#;
25723 pragma Export (C, u00052, "system__string_hashS");
25724 u00053 : constant Version_32 := 16#807fe041#;
25725 pragma Export (C, u00053, "system__unsigned_typesS");
25726 u00054 : constant Version_32 := 16#d27be59e#;
25727 pragma Export (C, u00054, "system__val_lluB");
25728 u00055 : constant Version_32 := 16#fa8db733#;
25729 pragma Export (C, u00055, "system__val_lluS");
25730 u00056 : constant Version_32 := 16#27b600b2#;
25731 pragma Export (C, u00056, "system__val_utilB");
25732 u00057 : constant Version_32 := 16#b187f27f#;
25733 pragma Export (C, u00057, "system__val_utilS");
25734 u00058 : constant Version_32 := 16#d1060688#;
25735 pragma Export (C, u00058, "system__case_utilB");
25736 u00059 : constant Version_32 := 16#392e2d56#;
25737 pragma Export (C, u00059, "system__case_utilS");
25738 u00060 : constant Version_32 := 16#84a27f0d#;
25739 pragma Export (C, u00060, "interfaces__c_streamsB");
25740 u00061 : constant Version_32 := 16#8bb5f2c0#;
25741 pragma Export (C, u00061, "interfaces__c_streamsS");
25742 u00062 : constant Version_32 := 16#6db6928f#;
25743 pragma Export (C, u00062, "system__crtlS");
25744 u00063 : constant Version_32 := 16#4e6a342b#;
25745 pragma Export (C, u00063, "system__file_ioB");
25746 u00064 : constant Version_32 := 16#ba56a5e4#;
25747 pragma Export (C, u00064, "system__file_ioS");
25748 u00065 : constant Version_32 := 16#b7ab275c#;
25749 pragma Export (C, u00065, "ada__finalizationB");
25750 u00066 : constant Version_32 := 16#19f764ca#;
25751 pragma Export (C, u00066, "ada__finalizationS");
25752 u00067 : constant Version_32 := 16#95817ed8#;
25753 pragma Export (C, u00067, "system__finalization_rootB");
25754 u00068 : constant Version_32 := 16#52d53711#;
25755 pragma Export (C, u00068, "system__finalization_rootS");
25756 u00069 : constant Version_32 := 16#769e25e6#;
25757 pragma Export (C, u00069, "interfaces__cB");
25758 u00070 : constant Version_32 := 16#4a38bedb#;
25759 pragma Export (C, u00070, "interfaces__cS");
25760 u00071 : constant Version_32 := 16#07e6ee66#;
25761 pragma Export (C, u00071, "system__os_libB");
25762 u00072 : constant Version_32 := 16#d7b69782#;
25763 pragma Export (C, u00072, "system__os_libS");
25764 u00073 : constant Version_32 := 16#1a817b8e#;
25765 pragma Export (C, u00073, "system__stringsB");
25766 u00074 : constant Version_32 := 16#639855e7#;
25767 pragma Export (C, u00074, "system__stringsS");
25768 u00075 : constant Version_32 := 16#e0b8de29#;
25769 pragma Export (C, u00075, "system__file_control_blockS");
25770 u00076 : constant Version_32 := 16#b5b2aca1#;
25771 pragma Export (C, u00076, "system__finalization_mastersB");
25772 u00077 : constant Version_32 := 16#69316dc1#;
25773 pragma Export (C, u00077, "system__finalization_mastersS");
25774 u00078 : constant Version_32 := 16#57a37a42#;
25775 pragma Export (C, u00078, "system__address_imageB");
25776 u00079 : constant Version_32 := 16#bccbd9bb#;
25777 pragma Export (C, u00079, "system__address_imageS");
25778 u00080 : constant Version_32 := 16#7268f812#;
25779 pragma Export (C, u00080, "system__img_boolB");
25780 u00081 : constant Version_32 := 16#e8fe356a#;
25781 pragma Export (C, u00081, "system__img_boolS");
25782 u00082 : constant Version_32 := 16#d7aac20c#;
25783 pragma Export (C, u00082, "system__ioB");
25784 u00083 : constant Version_32 := 16#8365b3ce#;
25785 pragma Export (C, u00083, "system__ioS");
25786 u00084 : constant Version_32 := 16#6d4d969a#;
25787 pragma Export (C, u00084, "system__storage_poolsB");
25788 u00085 : constant Version_32 := 16#e87cc305#;
25789 pragma Export (C, u00085, "system__storage_poolsS");
25790 u00086 : constant Version_32 := 16#e34550ca#;
25791 pragma Export (C, u00086, "system__pool_globalB");
25792 u00087 : constant Version_32 := 16#c88d2d16#;
25793 pragma Export (C, u00087, "system__pool_globalS");
25794 u00088 : constant Version_32 := 16#9d39c675#;
25795 pragma Export (C, u00088, "system__memoryB");
25796 u00089 : constant Version_32 := 16#445a22b5#;
25797 pragma Export (C, u00089, "system__memoryS");
25798 u00090 : constant Version_32 := 16#6a859064#;
25799 pragma Export (C, u00090, "system__storage_pools__subpoolsB");
25800 u00091 : constant Version_32 := 16#e3b008dc#;
25801 pragma Export (C, u00091, "system__storage_pools__subpoolsS");
25802 u00092 : constant Version_32 := 16#63f11652#;
25803 pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
25804 u00093 : constant Version_32 := 16#fe2f4b3a#;
25805 pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
25807 -- BEGIN ELABORATION ORDER
25811 -- system.case_util%s
25812 -- system.case_util%b
25814 -- system.img_bool%s
25815 -- system.img_bool%b
25816 -- system.img_int%s
25817 -- system.img_int%b
25820 -- system.parameters%s
25821 -- system.parameters%b
25823 -- interfaces.c_streams%s
25824 -- interfaces.c_streams%b
25825 -- system.standard_library%s
25826 -- system.exceptions_debug%s
25827 -- system.exceptions_debug%b
25828 -- system.storage_elements%s
25829 -- system.storage_elements%b
25830 -- system.stack_checking%s
25831 -- system.stack_checking%b
25832 -- system.string_hash%s
25833 -- system.string_hash%b
25835 -- system.strings%s
25836 -- system.strings%b
25838 -- system.traceback_entries%s
25839 -- system.traceback_entries%b
25840 -- ada.exceptions%s
25841 -- system.soft_links%s
25842 -- system.unsigned_types%s
25843 -- system.val_llu%s
25844 -- system.val_util%s
25845 -- system.val_util%b
25846 -- system.val_llu%b
25847 -- system.wch_con%s
25848 -- system.wch_con%b
25849 -- system.wch_cnv%s
25850 -- system.wch_jis%s
25851 -- system.wch_jis%b
25852 -- system.wch_cnv%b
25853 -- system.wch_stw%s
25854 -- system.wch_stw%b
25855 -- ada.exceptions.last_chance_handler%s
25856 -- ada.exceptions.last_chance_handler%b
25857 -- system.address_image%s
25858 -- system.exception_table%s
25859 -- system.exception_table%b
25860 -- ada.io_exceptions%s
25865 -- system.exceptions%s
25866 -- system.exceptions%b
25867 -- system.exceptions.machine%s
25868 -- system.finalization_root%s
25869 -- system.finalization_root%b
25870 -- ada.finalization%s
25871 -- ada.finalization%b
25872 -- system.storage_pools%s
25873 -- system.storage_pools%b
25874 -- system.finalization_masters%s
25875 -- system.storage_pools.subpools%s
25876 -- system.storage_pools.subpools.finalization%s
25877 -- system.storage_pools.subpools.finalization%b
25880 -- system.standard_library%b
25881 -- system.pool_global%s
25882 -- system.pool_global%b
25883 -- system.file_control_block%s
25884 -- system.file_io%s
25885 -- system.secondary_stack%s
25886 -- system.file_io%b
25887 -- system.storage_pools.subpools%b
25888 -- system.finalization_masters%b
25891 -- system.soft_links%b
25893 -- system.secondary_stack%b
25894 -- system.address_image%b
25895 -- system.traceback%s
25896 -- ada.exceptions%b
25897 -- system.traceback%b
25901 -- END ELABORATION ORDER
25908 -- The following source file name pragmas allow the generated file
25909 -- names to be unique for different main programs. They are needed
25910 -- since the package name will always be Ada_Main.
25912 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
25913 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
25915 pragma Suppress (Overflow_Check);
25916 with Ada.Exceptions;
25918 -- Generated package body for Ada_Main starts here
25920 package body ada_main is
25921 pragma Warnings (Off);
25923 -- These values are reference counter associated to units which have
25924 -- been elaborated. It is also used to avoid elaborating the
25925 -- same unit twice.
25927 E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
25928 E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
25929 E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
25930 E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
25931 E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
25932 E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
25933 E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
25934 E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
25935 E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
25936 E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
25937 E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
25938 E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
25939 E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
25940 E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
25941 E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
25942 E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
25943 E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
25944 E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
25946 Local_Priority_Specific_Dispatching : constant String := "";
25947 Local_Interrupt_States : constant String := "";
25949 Is_Elaborated : Boolean := False;
25951 procedure finalize_library is
25956 pragma Import (Ada, F1, "ada__text_io__finalize_spec");
25964 pragma Import (Ada, F2, "system__file_io__finalize_body");
25971 pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
25979 pragma Import (Ada, F4, "system__pool_global__finalize_spec");
25985 pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
25991 pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
25996 procedure Reraise_Library_Exception_If_Any;
25997 pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
25999 Reraise_Library_Exception_If_Any;
26001 end finalize_library;
26007 procedure adainit is
26009 Main_Priority : Integer;
26010 pragma Import (C, Main_Priority, "__gl_main_priority");
26011 Time_Slice_Value : Integer;
26012 pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
26013 WC_Encoding : Character;
26014 pragma Import (C, WC_Encoding, "__gl_wc_encoding");
26015 Locking_Policy : Character;
26016 pragma Import (C, Locking_Policy, "__gl_locking_policy");
26017 Queuing_Policy : Character;
26018 pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
26019 Task_Dispatching_Policy : Character;
26020 pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
26021 Priority_Specific_Dispatching : System.Address;
26022 pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
26023 Num_Specific_Dispatching : Integer;
26024 pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
26025 Main_CPU : Integer;
26026 pragma Import (C, Main_CPU, "__gl_main_cpu");
26027 Interrupt_States : System.Address;
26028 pragma Import (C, Interrupt_States, "__gl_interrupt_states");
26029 Num_Interrupt_States : Integer;
26030 pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
26031 Unreserve_All_Interrupts : Integer;
26032 pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
26033 Detect_Blocking : Integer;
26034 pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
26035 Default_Stack_Size : Integer;
26036 pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
26037 Leap_Seconds_Support : Integer;
26038 pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
26040 procedure Runtime_Initialize;
26041 pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
26043 Finalize_Library_Objects : No_Param_Proc;
26044 pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
26046 -- Start of processing for adainit
26050 -- Record various information for this partition. The values
26051 -- are derived by the binder from information stored in the ali
26052 -- files by the compiler.
26054 if Is_Elaborated then
26057 Is_Elaborated := True;
26058 Main_Priority := -1;
26059 Time_Slice_Value := -1;
26060 WC_Encoding := 'b';
26061 Locking_Policy := ' ';
26062 Queuing_Policy := ' ';
26063 Task_Dispatching_Policy := ' ';
26064 Priority_Specific_Dispatching :=
26065 Local_Priority_Specific_Dispatching'Address;
26066 Num_Specific_Dispatching := 0;
26068 Interrupt_States := Local_Interrupt_States'Address;
26069 Num_Interrupt_States := 0;
26070 Unreserve_All_Interrupts := 0;
26071 Detect_Blocking := 0;
26072 Default_Stack_Size := -1;
26073 Leap_Seconds_Support := 0;
26075 Runtime_Initialize;
26077 Finalize_Library_Objects := finalize_library'access;
26079 -- Now we have the elaboration calls for all units in the partition.
26080 -- The Elab_Spec and Elab_Body attributes generate references to the
26081 -- implicit elaboration procedures generated by the compiler for
26082 -- each unit that requires elaboration. Increment a counter of
26083 -- reference for each unit.
26085 System.Soft_Links'Elab_Spec;
26086 System.Exception_Table'Elab_Body;
26088 Ada.Io_Exceptions'Elab_Spec;
26090 Ada.Tags'Elab_Spec;
26091 Ada.Streams'Elab_Spec;
26093 Interfaces.C'Elab_Spec;
26094 System.Exceptions'Elab_Spec;
26096 System.Finalization_Root'Elab_Spec;
26098 Ada.Finalization'Elab_Spec;
26100 System.Storage_Pools'Elab_Spec;
26102 System.Finalization_Masters'Elab_Spec;
26103 System.Storage_Pools.Subpools'Elab_Spec;
26104 System.Pool_Global'Elab_Spec;
26106 System.File_Control_Block'Elab_Spec;
26108 System.File_Io'Elab_Body;
26111 System.Finalization_Masters'Elab_Body;
26114 Ada.Tags'Elab_Body;
26116 System.Soft_Links'Elab_Body;
26118 System.Os_Lib'Elab_Body;
26120 System.Secondary_Stack'Elab_Body;
26122 Ada.Text_Io'Elab_Spec;
26123 Ada.Text_Io'Elab_Body;
26131 procedure adafinal is
26132 procedure s_stalib_adafinal;
26133 pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
26135 procedure Runtime_Finalize;
26136 pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
26139 if not Is_Elaborated then
26142 Is_Elaborated := False;
26147 -- We get to the main program of the partition by using
26148 -- pragma Import because if we try to with the unit and
26149 -- call it Ada style, then not only do we waste time
26150 -- recompiling it, but also, we don't really know the right
26151 -- switches (e.g.@@: identifier character set) to be used
26154 procedure Ada_Main_Program;
26155 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26161 -- main is actually a function, as in the ANSI C standard,
26162 -- defined to return the exit status. The three parameters
26163 -- are the argument count, argument values and environment
26168 argv : System.Address;
26169 envp : System.Address)
26172 -- The initialize routine performs low level system
26173 -- initialization using a standard library routine which
26174 -- sets up signal handling and performs any other
26175 -- required setup. The routine can be found in file
26178 procedure initialize;
26179 pragma Import (C, initialize, "__gnat_initialize");
26181 -- The finalize routine performs low level system
26182 -- finalization using a standard library routine. The
26183 -- routine is found in file a-final.c and in the standard
26184 -- distribution is a dummy routine that does nothing, so
26185 -- really this is a hook for special user finalization.
26187 procedure finalize;
26188 pragma Import (C, finalize, "__gnat_finalize");
26190 -- The following is to initialize the SEH exceptions
26192 SEH : aliased array (1 .. 2) of Integer;
26194 Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
26195 pragma Volatile (Ensure_Reference);
26197 -- Start of processing for main
26200 -- Save global variables
26206 -- Call low level system initialization
26208 Initialize (SEH'Address);
26210 -- Call our generated Ada initialization routine
26214 -- Now we call the main program of the partition
26218 -- Perform Ada finalization
26222 -- Perform low level system finalization
26226 -- Return the proper exit status
26227 return (gnat_exit_status);
26230 -- This section is entirely comments, so it has no effect on the
26231 -- compilation of the Ada_Main package. It provides the list of
26232 -- object files and linker options, as well as some standard
26233 -- libraries needed for the link. The gnatlink utility parses
26234 -- this b~hello.adb file to read these comment lines to generate
26235 -- the appropriate command line arguments for the call to the
26236 -- system linker. The BEGIN/END lines are used for sentinels for
26237 -- this parsing operation.
26239 -- The exact file names will of course depend on the environment,
26240 -- host/target and location of files on the host system.
26242 -- BEGIN Object file/option list
26245 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
26246 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
26247 -- END Object file/option list
26252 The Ada code in the above example is exactly what is generated by the
26253 binder. We have added comments to more clearly indicate the function
26254 of each part of the generated @code{Ada_Main} package.
26256 The code is standard Ada in all respects, and can be processed by any
26257 tools that handle Ada. In particular, it is possible to use the debugger
26258 in Ada mode to debug the generated @code{Ada_Main} package. For example,
26259 suppose that for reasons that you do not understand, your program is crashing
26260 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
26261 you can place a breakpoint on the call:
26266 Ada.Text_Io'Elab_Body;
26270 and trace the elaboration routine for this package to find out where
26271 the problem might be (more usually of course you would be debugging
26272 elaboration code in your own application).
26274 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
26276 @node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
26277 @anchor{gnat_ugn/elaboration_order_handling_in_gnat doc}@anchor{21a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order-handling-in-gnat}@anchor{f}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id1}@anchor{21b}
26278 @chapter Elaboration Order Handling in GNAT
26281 @geindex Order of elaboration
26283 @geindex Elaboration control
26285 This appendix describes the handling of elaboration code in Ada and GNAT, and
26286 discusses how the order of elaboration of program units can be controlled in
26287 GNAT, either automatically or with explicit programming features.
26290 * Elaboration Code::
26291 * Elaboration Order::
26292 * Checking the Elaboration Order::
26293 * Controlling the Elaboration Order in Ada::
26294 * Controlling the Elaboration Order in GNAT::
26295 * Mixing Elaboration Models::
26296 * ABE Diagnostics::
26297 * SPARK Diagnostics::
26298 * Elaboration Circularities::
26299 * Resolving Elaboration Circularities::
26300 * Elaboration-related Compiler Switches::
26301 * Summary of Procedures for Elaboration Control::
26302 * Inspecting the Chosen Elaboration Order::
26306 @node Elaboration Code,Elaboration Order,,Elaboration Order Handling in GNAT
26307 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{21c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{21d}
26308 @section Elaboration Code
26311 Ada defines the term `execution' as the process by which a construct achieves
26312 its run-time effect. This process is also referred to as `elaboration' for
26313 declarations and `evaluation' for expressions.
26315 The execution model in Ada allows for certain sections of an Ada program to be
26316 executed prior to execution of the program itself, primarily with the intent of
26317 initializing data. These sections are referred to as `elaboration code'.
26318 Elaboration code is executed as follows:
26324 All partitions of an Ada program are executed in parallel with one another,
26325 possibly in a separate address space, and possibly on a separate computer.
26328 The execution of a partition involves running the environment task for that
26332 The environment task executes all elaboration code (if available) for all
26333 units within that partition. This code is said to be executed at
26334 `elaboration time'.
26337 The environment task executes the Ada program (if available) for that
26341 In addition to the Ada terminology, this appendix defines the following terms:
26349 The act of calling a subprogram, instantiating a generic, or activating a
26355 A construct that is elaborated or invoked by elaboration code is referred to
26356 as an `elaboration scenario' or simply a `scenario'. GNAT recognizes the
26357 following scenarios:
26363 @code{'Access} of entries, operators, and subprograms
26366 Activation of tasks
26369 Calls to entries, operators, and subprograms
26372 Instantiations of generic templates
26378 A construct elaborated by a scenario is referred to as `elaboration target'
26379 or simply `target'. GNAT recognizes the following targets:
26385 For @code{'Access} of entries, operators, and subprograms, the target is the
26386 entry, operator, or subprogram being aliased.
26389 For activation of tasks, the target is the task body
26392 For calls to entries, operators, and subprograms, the target is the entry,
26393 operator, or subprogram being invoked.
26396 For instantiations of generic templates, the target is the generic template
26397 being instantiated.
26401 Elaboration code may appear in two distinct contexts:
26409 A scenario appears at the library level when it is encapsulated by a package
26410 [body] compilation unit, ignoring any other package [body] declarations in
26419 Val : ... := Server.Func;
26424 In the example above, the call to @code{Server.Func} is an elaboration scenario
26425 because it appears at the library level of package @code{Client}. Note that the
26426 declaration of package @code{Nested} is ignored according to the definition
26427 given above. As a result, the call to @code{Server.Func} will be invoked when
26428 the spec of unit @code{Client} is elaborated.
26431 `Package body statements'
26433 A scenario appears within the statement sequence of a package body when it is
26434 bounded by the region starting from the @code{begin} keyword of the package body
26435 and ending at the @code{end} keyword of the package body.
26438 package body Client is
26448 In the example above, the call to @code{Proc} is an elaboration scenario because
26449 it appears within the statement sequence of package body @code{Client}. As a
26450 result, the call to @code{Proc} will be invoked when the body of @code{Client} is
26454 @node Elaboration Order,Checking the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
26455 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order}@anchor{21e}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{21f}
26456 @section Elaboration Order
26459 The sequence by which the elaboration code of all units within a partition is
26460 executed is referred to as `elaboration order'.
26462 Within a single unit, elaboration code is executed in sequential order.
26467 package body Client is
26468 Result : ... := Server.Func;
26471 package Inst is new Server.Gen;
26473 Inst.Eval (Result);
26481 In the example above, the elaboration order within package body @code{Client} is
26488 The object declaration of @code{Result} is elaborated.
26494 Function @code{Server.Func} is invoked.
26498 The subprogram body of @code{Proc} is elaborated.
26501 Procedure @code{Proc} is invoked.
26507 Generic unit @code{Server.Gen} is instantiated as @code{Inst}.
26510 Instance @code{Inst} is elaborated.
26513 Procedure @code{Inst.Eval} is invoked.
26517 The elaboration order of all units within a partition depends on the following
26533 preelaborability of units
26536 presence of elaboration-control pragmas
26539 invocations performed in elaboration code
26542 A program may have several elaboration orders depending on its structure.
26548 function Func (Index : Integer) return Integer;
26553 package body Server is
26554 Results : array (1 .. 5) of Integer := (1, 2, 3, 4, 5);
26556 function Func (Index : Integer) return Integer is
26558 return Results (Index);
26566 Val : constant Integer := Server.Func (3);
26572 procedure Main is begin null; end Main;
26576 The following elaboration order exhibits a fundamental problem referred to as
26577 `access-before-elaboration' or simply `ABE'.
26589 The elaboration of @code{Server}’s spec materializes function @code{Func}, making it
26590 callable. The elaboration of @code{Client}’s spec elaborates the declaration of
26591 @code{Val}. This invokes function @code{Server.Func}, however the body of
26592 @code{Server.Func} has not been elaborated yet because @code{Server}’s body comes
26593 after @code{Client}’s spec in the elaboration order. As a result, the value of
26594 constant @code{Val} is now undefined.
26596 Without any guarantees from the language, an undetected ABE problem may hinder
26597 proper initialization of data, which in turn may lead to undefined behavior at
26598 run time. To prevent such ABE problems, Ada employs dynamic checks in the same
26599 vein as index or null exclusion checks. A failed ABE check raises exception
26600 @code{Program_Error}.
26602 The following elaboration order avoids the ABE problem and the program can be
26603 successfully elaborated.
26615 Ada states that a total elaboration order must exist, but it does not define
26616 what this order is. A compiler is thus tasked with choosing a suitable
26617 elaboration order which satisfies the dependencies imposed by `with' clauses,
26618 unit categorization, elaboration-control pragmas, and invocations performed in
26619 elaboration code. Ideally an order that avoids ABE problems should be chosen,
26620 however a compiler may not always find such an order due to complications with
26621 respect to control and data flow.
26623 @node Checking the Elaboration Order,Controlling the Elaboration Order in Ada,Elaboration Order,Elaboration Order Handling in GNAT
26624 @anchor{gnat_ugn/elaboration_order_handling_in_gnat checking-the-elaboration-order}@anchor{220}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id4}@anchor{221}
26625 @section Checking the Elaboration Order
26628 To avoid placing the entire elaboration-order burden on the programmer, Ada
26629 provides three lines of defense:
26637 Static semantic rules restrict the possible choice of elaboration order. For
26638 instance, if unit Client `with's unit Server, then the spec of Server is
26639 always elaborated prior to Client. The same principle applies to child units
26640 - the spec of a parent unit is always elaborated prior to the child unit.
26643 `Dynamic semantics'
26645 Dynamic checks are performed at run time, to ensure that a target is
26646 elaborated prior to a scenario that invokes it, thus avoiding ABE problems.
26647 A failed run-time check raises exception @code{Program_Error}. The following
26648 restrictions apply:
26654 `Restrictions on calls'
26656 An entry, operator, or subprogram can be called from elaboration code only
26657 when the corresponding body has been elaborated.
26660 `Restrictions on instantiations'
26662 A generic unit can be instantiated by elaboration code only when the
26663 corresponding body has been elaborated.
26666 `Restrictions on task activation'
26668 A task can be activated by elaboration code only when the body of the
26669 associated task type has been elaborated.
26672 The restrictions above can be summarized by the following rule:
26674 `If a target has a body, then this body must be elaborated prior to the
26675 scenario that invokes the target.'
26678 `Elaboration control'
26680 Pragmas are provided for the programmer to specify the desired elaboration
26684 @node Controlling the Elaboration Order in Ada,Controlling the Elaboration Order in GNAT,Checking the Elaboration Order,Elaboration Order Handling in GNAT
26685 @anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order-in-ada}@anchor{222}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id5}@anchor{223}
26686 @section Controlling the Elaboration Order in Ada
26689 Ada provides several idioms and pragmas to aid the programmer with specifying
26690 the desired elaboration order and avoiding ABE problems altogether.
26696 `Packages without a body'
26698 A library package which does not require a completing body does not suffer
26704 type Element is private;
26705 package Containers is
26706 type Element_Array is array (1 .. 10) of Element;
26711 In the example above, package @code{Pack} does not require a body because it
26712 does not contain any constructs which require completion in a body. As a
26713 result, generic @code{Pack.Containers} can be instantiated without encountering
26717 @geindex pragma Pure
26725 Pragma @code{Pure} places sufficient restrictions on a unit to guarantee that no
26726 scenario within the unit can result in an ABE problem.
26729 @geindex pragma Preelaborate
26735 `pragma Preelaborate'
26737 Pragma @code{Preelaborate} is slightly less restrictive than pragma @code{Pure},
26738 but still strong enough to prevent ABE problems within a unit.
26741 @geindex pragma Elaborate_Body
26747 `pragma Elaborate_Body'
26749 Pragma @code{Elaborate_Body} requires that the body of a unit is elaborated
26750 immediately after its spec. This restriction guarantees that no client
26751 scenario can invoke a server target before the target body has been
26752 elaborated because the spec and body are effectively “glued” together.
26756 pragma Elaborate_Body;
26758 function Func return Integer;
26763 package body Server is
26764 function Func return Integer is
26774 Val : constant Integer := Server.Func;
26778 In the example above, pragma @code{Elaborate_Body} guarantees the following
26787 because the spec of @code{Server} must be elaborated prior to @code{Client} by
26788 virtue of the `with' clause, and in addition the body of @code{Server} must be
26789 elaborated immediately after the spec of @code{Server}.
26791 Removing pragma @code{Elaborate_Body} could result in the following incorrect
26800 where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func} has
26801 not been elaborated yet.
26804 The pragmas outlined above allow a server unit to guarantee safe elaboration
26805 use by client units. Thus it is a good rule to mark units as @code{Pure} or
26806 @code{Preelaborate}, and if this is not possible, mark them as @code{Elaborate_Body}.
26808 There are however situations where @code{Pure}, @code{Preelaborate}, and
26809 @code{Elaborate_Body} are not applicable. Ada provides another set of pragmas for
26810 use by client units to help ensure the elaboration safety of server units they
26813 @geindex pragma Elaborate (Unit)
26819 `pragma Elaborate (Unit)'
26821 Pragma @code{Elaborate} can be placed in the context clauses of a unit, after a
26822 `with' clause. It guarantees that both the spec and body of its argument will
26823 be elaborated prior to the unit with the pragma. Note that other unrelated
26824 units may be elaborated in between the spec and the body.
26828 function Func return Integer;
26833 package body Server is
26834 function Func return Integer is
26843 pragma Elaborate (Server);
26845 Val : constant Integer := Server.Func;
26849 In the example above, pragma @code{Elaborate} guarantees the following
26858 Removing pragma @code{Elaborate} could result in the following incorrect
26867 where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func}
26868 has not been elaborated yet.
26871 @geindex pragma Elaborate_All (Unit)
26877 `pragma Elaborate_All (Unit)'
26879 Pragma @code{Elaborate_All} is placed in the context clauses of a unit, after
26880 a `with' clause. It guarantees that both the spec and body of its argument
26881 will be elaborated prior to the unit with the pragma, as well as all units
26882 `with'ed by the spec and body of the argument, recursively. Note that other
26883 unrelated units may be elaborated in between the spec and the body.
26887 function Factorial (Val : Natural) return Natural;
26892 package body Math is
26893 function Factorial (Val : Natural) return Natural is
26901 package Computer is
26902 type Operation_Kind is (None, Op_Factorial);
26906 Op : Operation_Kind) return Natural;
26912 package body Computer is
26915 Op : Operation_Kind) return Natural
26917 if Op = Op_Factorial then
26918 return Math.Factorial (Val);
26928 pragma Elaborate_All (Computer);
26930 Val : constant Natural :=
26931 Computer.Compute (123, Computer.Op_Factorial);
26935 In the example above, pragma @code{Elaborate_All} can result in the following
26946 Note that there are several allowable suborders for the specs and bodies of
26947 @code{Math} and @code{Computer}, but the point is that these specs and bodies will
26948 be elaborated prior to @code{Client}.
26950 Removing pragma @code{Elaborate_All} could result in the following incorrect
26961 where @code{Client} invokes @code{Computer.Compute}, which in turn invokes
26962 @code{Math.Factorial}, but the body of @code{Math.Factorial} has not been
26966 All pragmas shown above can be summarized by the following rule:
26968 `If a client unit elaborates a server target directly or indirectly, then if
26969 the server unit requires a body and does not have pragma Pure, Preelaborate,
26970 or Elaborate_Body, then the client unit should have pragma Elaborate or
26971 Elaborate_All for the server unit.'
26973 If the rule outlined above is not followed, then a program may fall in one of
26974 the following states:
26980 `No elaboration order exists'
26982 In this case a compiler must diagnose the situation, and refuse to build an
26983 executable program.
26986 `One or more incorrect elaboration orders exist'
26988 In this case a compiler can build an executable program, but
26989 @code{Program_Error} will be raised when the program is run.
26992 `Several elaboration orders exist, some correct, some incorrect'
26994 In this case the programmer has not controlled the elaboration order. As a
26995 result, a compiler may or may not pick one of the correct orders, and the
26996 program may or may not raise @code{Program_Error} when it is run. This is the
26997 worst possible state because the program may fail on another compiler, or
26998 even another version of the same compiler.
27001 `One or more correct orders exist'
27003 In this case a compiler can build an executable program, and the program is
27004 run successfully. This state may be guaranteed by following the outlined
27005 rules, or may be the result of good program architecture.
27008 Note that one additional advantage of using @code{Elaborate} and @code{Elaborate_All}
27009 is that the program continues to stay in the last state (one or more correct
27010 orders exist) even if maintenance changes the bodies of targets.
27012 @node Controlling the Elaboration Order in GNAT,Mixing Elaboration Models,Controlling the Elaboration Order in Ada,Elaboration Order Handling in GNAT
27013 @anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order-in-gnat}@anchor{224}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id6}@anchor{225}
27014 @section Controlling the Elaboration Order in GNAT
27017 In addition to Ada semantics and rules synthesized from them, GNAT offers
27018 three elaboration models to aid the programmer with specifying the correct
27019 elaboration order and to diagnose elaboration problems.
27021 @geindex Dynamic elaboration model
27027 `Dynamic elaboration model'
27029 This is the most permissive of the three elaboration models and emulates the
27030 behavior specified by the Ada Reference Manual. When the dynamic model is in
27031 effect, GNAT makes the following assumptions:
27037 All code within all units in a partition is considered to be elaboration
27041 Some of the invocations in elaboration code may not take place at run time
27042 due to conditional execution.
27045 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
27046 that invoke internal targets. In addition, GNAT generates run-time checks for
27047 all external targets and for all scenarios that may exhibit ABE problems.
27049 The elaboration order is obtained by honoring all `with' clauses, purity and
27050 preelaborability of units, and elaboration-control pragmas. The dynamic model
27051 attempts to take all invocations in elaboration code into account. If an
27052 invocation leads to a circularity, GNAT ignores the invocation based on the
27053 assumptions stated above. An order obtained using the dynamic model may fail
27054 an ABE check at run time when GNAT ignored an invocation.
27056 The dynamic model is enabled with compiler switch @code{-gnatE}.
27059 @geindex Static elaboration model
27065 `Static elaboration model'
27067 This is the middle ground of the three models. When the static model is in
27068 effect, GNAT makes the following assumptions:
27074 Only code at the library level and in package body statements within all
27075 units in a partition is considered to be elaboration code.
27078 All invocations in elaboration will take place at run time, regardless of
27079 conditional execution.
27082 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
27083 that invoke internal targets. In addition, GNAT generates run-time checks for
27084 all external targets and for all scenarios that may exhibit ABE problems.
27086 The elaboration order is obtained by honoring all `with' clauses, purity and
27087 preelaborability of units, presence of elaboration-control pragmas, and all
27088 invocations in elaboration code. An order obtained using the static model is
27089 guaranteed to be ABE problem-free, excluding dispatching calls and
27090 access-to-subprogram types.
27092 The static model is the default model in GNAT.
27095 @geindex SPARK elaboration model
27101 `SPARK elaboration model'
27103 This is the most conservative of the three models and enforces the SPARK
27104 rules of elaboration as defined in the SPARK Reference Manual, section 7.7.
27105 The SPARK model is in effect only when a scenario and a target reside in a
27106 region subject to @code{SPARK_Mode On}, otherwise the dynamic or static model
27109 The SPARK model is enabled with compiler switch @code{-gnatd.v}.
27112 @geindex Legacy elaboration models
27118 `Legacy elaboration models'
27120 In addition to the three elaboration models outlined above, GNAT provides the
27121 following legacy models:
27127 @cite{Legacy elaboration-checking model} available in pre-18.x versions of GNAT.
27128 This model is enabled with compiler switch @code{-gnatH}.
27131 @cite{Legacy elaboration-order model} available in pre-20.x versions of GNAT.
27132 This model is enabled with binder switch @code{-H}.
27136 @geindex Relaxed elaboration mode
27138 The dynamic, legacy, and static models can be relaxed using compiler switch
27139 @code{-gnatJ}, making them more permissive. Note that in this mode, GNAT
27140 may not diagnose certain elaboration issues or install run-time checks.
27142 @node Mixing Elaboration Models,ABE Diagnostics,Controlling the Elaboration Order in GNAT,Elaboration Order Handling in GNAT
27143 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{226}@anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{227}
27144 @section Mixing Elaboration Models
27147 It is possible to mix units compiled with a different elaboration model,
27148 however the following rules must be observed:
27154 A client unit compiled with the dynamic model can only `with' a server unit
27155 that meets at least one of the following criteria:
27161 The server unit is compiled with the dynamic model.
27164 The server unit is a GNAT implementation unit from the @code{Ada}, @code{GNAT},
27165 @code{Interfaces}, or @code{System} hierarchies.
27168 The server unit has pragma @code{Pure} or @code{Preelaborate}.
27171 The client unit has an explicit @code{Elaborate_All} pragma for the server
27176 These rules ensure that elaboration checks are not omitted. If the rules are
27177 violated, the binder emits a warning:
27182 warning: "x.ads" has dynamic elaboration checks and with's
27183 warning: "y.ads" which has static elaboration checks
27187 The warnings can be suppressed by binder switch @code{-ws}.
27189 @node ABE Diagnostics,SPARK Diagnostics,Mixing Elaboration Models,Elaboration Order Handling in GNAT
27190 @anchor{gnat_ugn/elaboration_order_handling_in_gnat abe-diagnostics}@anchor{228}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{229}
27191 @section ABE Diagnostics
27194 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
27195 that invoke internal targets, regardless of whether the dynamic, SPARK, or
27196 static model is in effect.
27198 Note that GNAT emits warnings rather than hard errors whenever it encounters an
27199 elaboration problem. This is because the elaboration model in effect may be too
27200 conservative, or a particular scenario may not be invoked due conditional
27201 execution. The warnings can be suppressed selectively with @code{pragma Warnings
27202 (Off)} or globally with compiler switch @code{-gnatwL}.
27204 A `guaranteed ABE' arises when the body of a target is not elaborated early
27205 enough, and causes `all' scenarios that directly invoke the target to fail.
27210 package body Guaranteed_ABE is
27211 function ABE return Integer;
27213 Val : constant Integer := ABE;
27215 function ABE return Integer is
27219 end Guaranteed_ABE;
27223 In the example above, the elaboration of @code{Guaranteed_ABE}’s body elaborates
27224 the declaration of @code{Val}. This invokes function @code{ABE}, however the body of
27225 @code{ABE} has not been elaborated yet. GNAT emits the following diagnostic:
27230 4. Val : constant Integer := ABE;
27232 >>> warning: cannot call "ABE" before body seen
27233 >>> warning: Program_Error will be raised at run time
27237 A `conditional ABE' arises when the body of a target is not elaborated early
27238 enough, and causes `some' scenarios that directly invoke the target to fail.
27243 1. package body Conditional_ABE is
27244 2. procedure Force_Body is null;
27247 5. with function Func return Integer;
27249 7. Val : constant Integer := Func;
27252 10. function ABE return Integer;
27254 12. function Cause_ABE return Boolean is
27255 13. package Inst is new Gen (ABE);
27260 18. Val : constant Boolean := Cause_ABE;
27262 20. function ABE return Integer is
27267 25. Safe : constant Boolean := Cause_ABE;
27268 26. end Conditional_ABE;
27272 In the example above, the elaboration of package body @code{Conditional_ABE}
27273 elaborates the declaration of @code{Val}. This invokes function @code{Cause_ABE},
27274 which instantiates generic unit @code{Gen} as @code{Inst}. The elaboration of
27275 @code{Inst} invokes function @code{ABE}, however the body of @code{ABE} has not been
27276 elaborated yet. GNAT emits the following diagnostic:
27281 13. package Inst is new Gen (ABE);
27283 >>> warning: in instantiation at line 7
27284 >>> warning: cannot call "ABE" before body seen
27285 >>> warning: Program_Error may be raised at run time
27286 >>> warning: body of unit "Conditional_ABE" elaborated
27287 >>> warning: function "Cause_ABE" called at line 18
27288 >>> warning: function "ABE" called at line 7, instance at line 13
27292 Note that the same ABE problem does not occur with the elaboration of
27293 declaration @code{Safe} because the body of function @code{ABE} has already been
27294 elaborated at that point.
27296 @node SPARK Diagnostics,Elaboration Circularities,ABE Diagnostics,Elaboration Order Handling in GNAT
27297 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{22a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat spark-diagnostics}@anchor{22b}
27298 @section SPARK Diagnostics
27301 GNAT enforces the SPARK rules of elaboration as defined in the SPARK Reference
27302 Manual section 7.7 when compiler switch @code{-gnatd.v} is in effect. Note
27303 that GNAT emits hard errors whenever it encounters a violation of the SPARK
27310 2. package body SPARK_Diagnostics with SPARK_Mode is
27311 3. Val : constant Integer := Server.Func;
27313 >>> call to "Func" during elaboration in SPARK
27314 >>> unit "SPARK_Diagnostics" requires pragma "Elaborate_All" for "Server"
27315 >>> body of unit "SPARK_Model" elaborated
27316 >>> function "Func" called at line 3
27318 4. end SPARK_Diagnostics;
27322 @node Elaboration Circularities,Resolving Elaboration Circularities,SPARK Diagnostics,Elaboration Order Handling in GNAT
27323 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-circularities}@anchor{22c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{22d}
27324 @section Elaboration Circularities
27327 An `elaboration circularity' occurs whenever the elaboration of a set of
27328 units enters a deadlocked state, where each unit is waiting for another unit
27329 to be elaborated. This situation may be the result of improper use of `with'
27330 clauses, elaboration-control pragmas, or invocations in elaboration code.
27332 The following example exhibits an elaboration circularity.
27337 with B; pragma Elaborate (B);
27344 procedure Force_Body;
27351 procedure Force_Body is null;
27353 Elab : constant Integer := C.Func;
27359 function Func return Integer;
27366 function Func return Integer is
27374 The binder emits the following diagnostic:
27379 error: Elaboration circularity detected
27383 info: unit "a (spec)" depends on its own elaboration
27387 info: unit "a (spec)" has with clause and pragma Elaborate for unit "b (spec)"
27388 info: unit "b (body)" is in the closure of pragma Elaborate
27389 info: unit "b (body)" invokes a construct of unit "c (body)" at elaboration time
27390 info: unit "c (body)" has with clause for unit "a (spec)"
27394 info: remove pragma Elaborate for unit "b (body)" in unit "a (spec)"
27395 info: use the dynamic elaboration model (compiler switch -gnatE)
27399 The diagnostic consist of the following sections:
27407 This section provides a short explanation describing why the set of units
27408 could not be ordered.
27413 This section enumerates the units comprising the deadlocked set, along with
27414 their interdependencies.
27419 This section enumerates various tactics for eliminating the circularity.
27422 @node Resolving Elaboration Circularities,Elaboration-related Compiler Switches,Elaboration Circularities,Elaboration Order Handling in GNAT
27423 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{22e}@anchor{gnat_ugn/elaboration_order_handling_in_gnat resolving-elaboration-circularities}@anchor{22f}
27424 @section Resolving Elaboration Circularities
27427 The most desirable option from the point of view of long-term maintenance is to
27428 rearrange the program so that the elaboration problems are avoided. One useful
27429 technique is to place the elaboration code into separate child packages.
27430 Another is to move some of the initialization code to explicitly invoked
27431 subprograms, where the program controls the order of initialization explicitly.
27432 Although this is the most desirable option, it may be impractical and involve
27433 too much modification, especially in the case of complex legacy code.
27435 When faced with an elaboration circularity, the programmer should also consider
27436 the tactics given in the suggestions section of the circularity diagnostic.
27437 Depending on the units involved in the circularity, their `with' clauses,
27438 purity, preelaborability, presence of elaboration-control pragmas and
27439 invocations at elaboration time, the binder may suggest one or more of the
27440 following tactics to eliminate the circularity:
27446 Pragma Elaborate elimination
27449 remove pragma Elaborate for unit "..." in unit "..."
27452 This tactic is suggested when the binder has determined that pragma
27459 Prevents a set of units from being elaborated.
27462 The removal of the pragma will not eliminate the semantic effects of the
27463 pragma. In other words, the argument of the pragma will still be elaborated
27464 prior to the unit containing the pragma.
27467 The removal of the pragma will enable the successful ordering of the units.
27470 The programmer should remove the pragma as advised, and rebuild the program.
27473 Pragma Elaborate_All elimination
27476 remove pragma Elaborate_All for unit "..." in unit "..."
27479 This tactic is suggested when the binder has determined that pragma
27480 @code{Elaborate_All}:
27486 Prevents a set of units from being elaborated.
27489 The removal of the pragma will not eliminate the semantic effects of the
27490 pragma. In other words, the argument of the pragma along with its `with'
27491 closure will still be elaborated prior to the unit containing the pragma.
27494 The removal of the pragma will enable the successful ordering of the units.
27497 The programmer should remove the pragma as advised, and rebuild the program.
27500 Pragma Elaborate_All downgrade
27503 change pragma Elaborate_All for unit "..." to Elaborate in unit "..."
27506 This tactic is always suggested with the pragma @code{Elaborate_All} elimination
27507 tactic. It offers a different alternative of guaranteeing that the argument
27508 of the pragma will still be elaborated prior to the unit containing the
27511 The programmer should update the pragma as advised, and rebuild the program.
27514 Pragma Elaborate_Body elimination
27517 remove pragma Elaborate_Body in unit "..."
27520 This tactic is suggested when the binder has determined that pragma
27521 @code{Elaborate_Body}:
27527 Prevents a set of units from being elaborated.
27530 The removal of the pragma will enable the successful ordering of the units.
27533 Note that the binder cannot determine whether the pragma is required for
27534 other purposes, such as guaranteeing the initialization of a variable
27535 declared in the spec by elaboration code in the body.
27537 The programmer should remove the pragma as advised, and rebuild the program.
27540 Use of pragma Restrictions
27543 use pragma Restrictions (No_Entry_Calls_In_Elaboration_Code)
27546 This tactic is suggested when the binder has determined that a task
27547 activation at elaboration time:
27553 Prevents a set of units from being elaborated.
27556 Note that the binder cannot determine with certainty whether the task will
27557 block at elaboration time.
27559 The programmer should create a configuration file, place the pragma within,
27560 update the general compilation arguments, and rebuild the program.
27563 Use of dynamic elaboration model
27566 use the dynamic elaboration model (compiler switch -gnatE)
27569 This tactic is suggested when the binder has determined that an invocation at
27576 Prevents a set of units from being elaborated.
27579 The use of the dynamic model will enable the successful ordering of the
27583 The programmer has two options:
27589 Determine the units involved in the invocation using the detailed
27590 invocation information, and add compiler switch @code{-gnatE} to the
27591 compilation arguments of selected files only. This approach will yield
27592 safer elaboration orders compared to the other option because it will
27593 minimize the opportunities presented to the dynamic model for ignoring
27597 Add compiler switch @code{-gnatE} to the general compilation arguments.
27601 Use of detailed invocation information
27604 use detailed invocation information (compiler switch -gnatd_F)
27607 This tactic is always suggested with the use of the dynamic model tactic. It
27608 causes the circularity section of the circularity diagnostic to describe the
27609 flow of elaboration code from a unit to a unit, enumerating all such paths in
27612 The programmer should analyze this information to determine which units
27613 should be compiled with the dynamic model.
27616 Forced-dependency elimination
27619 remove the dependency of unit "..." on unit "..." from the argument of switch -f
27622 This tactic is suggested when the binder has determined that a dependency
27623 present in the forced-elaboration-order file indicated by binder switch
27630 Prevents a set of units from being elaborated.
27633 The removal of the dependency will enable the successful ordering of the
27637 The programmer should edit the forced-elaboration-order file, remove the
27638 dependency, and rebind the program.
27641 All forced-dependency elimination
27647 This tactic is suggested in case editing the forced-elaboration-order file is
27650 The programmer should remove binder switch @code{-f} from the binder
27651 arguments, and rebind.
27654 Multiple-circularities diagnostic
27657 diagnose all circularities (binder switch -d_C)
27660 By default, the binder will diagnose only the highest-precedence circularity.
27661 If the program contains multiple circularities, the binder will suggest the
27662 use of binder switch @code{-d_C} in order to obtain the diagnostics of all
27665 The programmer should add binder switch @code{-d_C} to the binder
27666 arguments, and rebind.
27669 If none of the tactics suggested by the binder eliminate the elaboration
27670 circularity, the programmer should consider using one of the legacy elaboration
27671 models, in the following order:
27677 Use the pre-20.x legacy elaboration-order model, with binder switch
27681 Use both pre-18.x and pre-20.x legacy elaboration models, with compiler
27682 switch @code{-gnatH} and binder switch @code{-H}.
27685 Use the relaxed static-elaboration model, with compiler switches
27686 @code{-gnatH} @code{-gnatJ} and binder switch @code{-H}.
27689 Use the relaxed dynamic-elaboration model, with compiler switches
27690 @code{-gnatH} @code{-gnatJ} @code{-gnatE} and binder switch
27694 @node Elaboration-related Compiler Switches,Summary of Procedures for Elaboration Control,Resolving Elaboration Circularities,Elaboration Order Handling in GNAT
27695 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-related-compiler-switches}@anchor{230}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id12}@anchor{231}
27696 @section Elaboration-related Compiler Switches
27699 GNAT has several switches that affect the elaboration model and consequently
27700 the elaboration order chosen by the binder.
27702 @geindex -gnatE (gnat)
27707 @item @code{-gnatE}
27709 Dynamic elaboration checking mode enabled
27711 When this switch is in effect, GNAT activates the dynamic model.
27714 @geindex -gnatel (gnat)
27719 @item @code{-gnatel}
27721 Turn on info messages on generated Elaborate[_All] pragmas
27723 This switch is only applicable to the pre-20.x legacy elaboration models.
27724 The post-20.x elaboration model no longer relies on implicitly generated
27725 @code{Elaborate} and @code{Elaborate_All} pragmas to order units.
27727 When this switch is in effect, GNAT will emit the following supplementary
27728 information depending on the elaboration model in effect.
27736 GNAT will indicate missing @code{Elaborate} and @code{Elaborate_All} pragmas for
27737 all library-level scenarios within the partition.
27742 GNAT will indicate all scenarios invoked during elaboration. In addition,
27743 it will provide detailed traceback when an implicit @code{Elaborate} or
27744 @code{Elaborate_All} pragma is generated.
27749 GNAT will indicate how an elaboration requirement is met by the context of
27750 a unit. This diagnostic requires compiler switch @code{-gnatd.v}.
27753 1. with Server; pragma Elaborate_All (Server);
27754 2. package Client with SPARK_Mode is
27755 3. Val : constant Integer := Server.Func;
27757 >>> info: call to "Func" during elaboration in SPARK
27758 >>> info: "Elaborate_All" requirement for unit "Server" met by pragma at line 1
27765 @geindex -gnatH (gnat)
27770 @item @code{-gnatH}
27772 Legacy elaboration checking mode enabled
27774 When this switch is in effect, GNAT will utilize the pre-18.x elaboration
27778 @geindex -gnatJ (gnat)
27783 @item @code{-gnatJ}
27785 Relaxed elaboration checking mode enabled
27787 When this switch is in effect, GNAT will not process certain scenarios,
27788 resulting in a more permissive elaboration model. Note that this may
27789 eliminate some diagnostics and run-time checks.
27792 @geindex -gnatw.f (gnat)
27797 @item @code{-gnatw.f}
27799 Turn on warnings for suspicious Subp’Access
27801 When this switch is in effect, GNAT will treat @code{'Access} of an entry,
27802 operator, or subprogram as a potential call to the target and issue warnings:
27805 1. package body Attribute_Call is
27806 2. function Func return Integer;
27807 3. type Func_Ptr is access function return Integer;
27809 5. Ptr : constant Func_Ptr := Func'Access;
27811 >>> warning: "Access" attribute of "Func" before body seen
27812 >>> warning: possible Program_Error on later references
27813 >>> warning: body of unit "Attribute_Call" elaborated
27814 >>> warning: "Access" of "Func" taken at line 5
27817 7. function Func return Integer is
27821 11. end Attribute_Call;
27824 In the example above, the elaboration of declaration @code{Ptr} is assigned
27825 @code{Func'Access} before the body of @code{Func} has been elaborated.
27828 @geindex -gnatwl (gnat)
27833 @item @code{-gnatwl}
27835 Turn on warnings for elaboration problems
27837 When this switch is in effect, GNAT emits diagnostics in the form of warnings
27838 concerning various elaboration problems. The warnings are enabled by default.
27839 The switch is provided in case all warnings are suppressed, but elaboration
27840 warnings are still desired.
27842 @item @code{-gnatwL}
27844 Turn off warnings for elaboration problems
27846 When this switch is in effect, GNAT no longer emits any diagnostics in the
27847 form of warnings. Selective suppression of elaboration problems is possible
27848 using @code{pragma Warnings (Off)}.
27851 1. package body Selective_Suppression is
27852 2. function ABE return Integer;
27854 4. Val_1 : constant Integer := ABE;
27856 >>> warning: cannot call "ABE" before body seen
27857 >>> warning: Program_Error will be raised at run time
27860 6. pragma Warnings (Off);
27861 7. Val_2 : constant Integer := ABE;
27862 8. pragma Warnings (On);
27864 10. function ABE return Integer is
27868 14. end Selective_Suppression;
27871 Note that suppressing elaboration warnings does not eliminate run-time
27872 checks. The example above will still fail at run time with an ABE.
27875 @node Summary of Procedures for Elaboration Control,Inspecting the Chosen Elaboration Order,Elaboration-related Compiler Switches,Elaboration Order Handling in GNAT
27876 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id13}@anchor{232}@anchor{gnat_ugn/elaboration_order_handling_in_gnat summary-of-procedures-for-elaboration-control}@anchor{233}
27877 @section Summary of Procedures for Elaboration Control
27880 A programmer should first compile the program with the default options, using
27881 none of the binder or compiler switches. If the binder succeeds in finding an
27882 elaboration order, then apart from possible cases involving dispatching calls
27883 and access-to-subprogram types, the program is free of elaboration errors.
27885 If it is important for the program to be portable to compilers other than GNAT,
27886 then the programmer should use compiler switch @code{-gnatel} and consider
27887 the messages about missing or implicitly created @code{Elaborate} and
27888 @code{Elaborate_All} pragmas.
27890 If the binder reports an elaboration circularity, the programmer has several
27897 Ensure that elaboration warnings are enabled. This will allow the static
27898 model to output trace information of elaboration issues. The trace
27899 information could shed light on previously unforeseen dependencies, as well
27900 as their origins. Elaboration warnings are enabled with compiler switch
27904 Cosider the tactics given in the suggestions section of the circularity
27908 If none of the steps outlined above resolve the circularity, use a more
27909 permissive elaboration model, in the following order:
27915 Use the pre-20.x legacy elaboration-order model, with binder switch
27919 Use both pre-18.x and pre-20.x legacy elaboration models, with compiler
27920 switch @code{-gnatH} and binder switch @code{-H}.
27923 Use the relaxed static elaboration model, with compiler switches
27924 @code{-gnatH} @code{-gnatJ} and binder switch @code{-H}.
27927 Use the relaxed dynamic elaboration model, with compiler switches
27928 @code{-gnatH} @code{-gnatJ} @code{-gnatE} and binder switch
27933 @node Inspecting the Chosen Elaboration Order,,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
27934 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id14}@anchor{234}@anchor{gnat_ugn/elaboration_order_handling_in_gnat inspecting-the-chosen-elaboration-order}@anchor{235}
27935 @section Inspecting the Chosen Elaboration Order
27938 To see the elaboration order chosen by the binder, inspect the contents of file
27939 @cite{b~xxx.adb}. On certain targets, this file appears as @cite{b_xxx.adb}. The
27940 elaboration order appears as a sequence of calls to @code{Elab_Body} and
27941 @code{Elab_Spec}, interspersed with assignments to @cite{Exxx} which indicates that a
27942 particular unit is elaborated. For example:
27947 System.Soft_Links'Elab_Body;
27949 System.Secondary_Stack'Elab_Body;
27951 System.Exception_Table'Elab_Body;
27953 Ada.Io_Exceptions'Elab_Spec;
27955 Ada.Tags'Elab_Spec;
27956 Ada.Streams'Elab_Spec;
27958 Interfaces.C'Elab_Spec;
27960 System.Finalization_Root'Elab_Spec;
27962 System.Os_Lib'Elab_Body;
27964 System.Finalization_Implementation'Elab_Spec;
27965 System.Finalization_Implementation'Elab_Body;
27967 Ada.Finalization'Elab_Spec;
27969 Ada.Finalization.List_Controller'Elab_Spec;
27971 System.File_Control_Block'Elab_Spec;
27973 System.File_Io'Elab_Body;
27975 Ada.Tags'Elab_Body;
27977 Ada.Text_Io'Elab_Spec;
27978 Ada.Text_Io'Elab_Body;
27983 Note also binder switch @code{-l}, which outputs the chosen elaboration
27984 order and provides a more readable form of the above:
27992 system.case_util (spec)
27993 system.case_util (body)
27994 system.concat_2 (spec)
27995 system.concat_2 (body)
27996 system.concat_3 (spec)
27997 system.concat_3 (body)
27998 system.htable (spec)
27999 system.parameters (spec)
28000 system.parameters (body)
28002 interfaces.c_streams (spec)
28003 interfaces.c_streams (body)
28004 system.restrictions (spec)
28005 system.restrictions (body)
28006 system.standard_library (spec)
28007 system.exceptions (spec)
28008 system.exceptions (body)
28009 system.storage_elements (spec)
28010 system.storage_elements (body)
28011 system.secondary_stack (spec)
28012 system.stack_checking (spec)
28013 system.stack_checking (body)
28014 system.string_hash (spec)
28015 system.string_hash (body)
28016 system.htable (body)
28017 system.strings (spec)
28018 system.strings (body)
28019 system.traceback (spec)
28020 system.traceback (body)
28021 system.traceback_entries (spec)
28022 system.traceback_entries (body)
28023 ada.exceptions (spec)
28024 ada.exceptions.last_chance_handler (spec)
28025 system.soft_links (spec)
28026 system.soft_links (body)
28027 ada.exceptions.last_chance_handler (body)
28028 system.secondary_stack (body)
28029 system.exception_table (spec)
28030 system.exception_table (body)
28031 ada.io_exceptions (spec)
28034 interfaces.c (spec)
28035 interfaces.c (body)
28036 system.finalization_root (spec)
28037 system.finalization_root (body)
28038 system.memory (spec)
28039 system.memory (body)
28040 system.standard_library (body)
28041 system.os_lib (spec)
28042 system.os_lib (body)
28043 system.unsigned_types (spec)
28044 system.stream_attributes (spec)
28045 system.stream_attributes (body)
28046 system.finalization_implementation (spec)
28047 system.finalization_implementation (body)
28048 ada.finalization (spec)
28049 ada.finalization (body)
28050 ada.finalization.list_controller (spec)
28051 ada.finalization.list_controller (body)
28052 system.file_control_block (spec)
28053 system.file_io (spec)
28054 system.file_io (body)
28055 system.val_uns (spec)
28056 system.val_util (spec)
28057 system.val_util (body)
28058 system.val_uns (body)
28059 system.wch_con (spec)
28060 system.wch_con (body)
28061 system.wch_cnv (spec)
28062 system.wch_jis (spec)
28063 system.wch_jis (body)
28064 system.wch_cnv (body)
28065 system.wch_stw (spec)
28066 system.wch_stw (body)
28068 ada.exceptions (body)
28076 @node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
28077 @anchor{gnat_ugn/inline_assembler doc}@anchor{236}@anchor{gnat_ugn/inline_assembler id1}@anchor{237}@anchor{gnat_ugn/inline_assembler inline-assembler}@anchor{10}
28078 @chapter Inline Assembler
28081 @geindex Inline Assembler
28083 If you need to write low-level software that interacts directly
28084 with the hardware, Ada provides two ways to incorporate assembly
28085 language code into your program. First, you can import and invoke
28086 external routines written in assembly language, an Ada feature fully
28087 supported by GNAT. However, for small sections of code it may be simpler
28088 or more efficient to include assembly language statements directly
28089 in your Ada source program, using the facilities of the implementation-defined
28090 package @code{System.Machine_Code}, which incorporates the gcc
28091 Inline Assembler. The Inline Assembler approach offers a number of advantages,
28092 including the following:
28098 No need to use non-Ada tools
28101 Consistent interface over different targets
28104 Automatic usage of the proper calling conventions
28107 Access to Ada constants and variables
28110 Definition of intrinsic routines
28113 Possibility of inlining a subprogram comprising assembler code
28116 Code optimizer can take Inline Assembler code into account
28119 This appendix presents a series of examples to show you how to use
28120 the Inline Assembler. Although it focuses on the Intel x86,
28121 the general approach applies also to other processors.
28122 It is assumed that you are familiar with Ada
28123 and with assembly language programming.
28126 * Basic Assembler Syntax::
28127 * A Simple Example of Inline Assembler::
28128 * Output Variables in Inline Assembler::
28129 * Input Variables in Inline Assembler::
28130 * Inlining Inline Assembler Code::
28131 * Other Asm Functionality::
28135 @node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
28136 @anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{238}@anchor{gnat_ugn/inline_assembler id2}@anchor{239}
28137 @section Basic Assembler Syntax
28140 The assembler used by GNAT and gcc is based not on the Intel assembly
28141 language, but rather on a language that descends from the AT&T Unix
28142 assembler @code{as} (and which is often referred to as ‘AT&T syntax’).
28143 The following table summarizes the main features of @code{as} syntax
28144 and points out the differences from the Intel conventions.
28145 See the gcc @code{as} and @code{gas} (an @code{as} macro
28146 pre-processor) documentation for further information.
28150 `Register names'@w{ }
28152 gcc / @code{as}: Prefix with ‘%’; for example @code{%eax}@w{ }
28153 Intel: No extra punctuation; for example @code{eax}@w{ }
28161 `Immediate operand'@w{ }
28163 gcc / @code{as}: Prefix with ‘$’; for example @code{$4}@w{ }
28164 Intel: No extra punctuation; for example @code{4}@w{ }
28174 gcc / @code{as}: Prefix with ‘$’; for example @code{$loc}@w{ }
28175 Intel: No extra punctuation; for example @code{loc}@w{ }
28183 `Memory contents'@w{ }
28185 gcc / @code{as}: No extra punctuation; for example @code{loc}@w{ }
28186 Intel: Square brackets; for example @code{[loc]}@w{ }
28194 `Register contents'@w{ }
28196 gcc / @code{as}: Parentheses; for example @code{(%eax)}@w{ }
28197 Intel: Square brackets; for example @code{[eax]}@w{ }
28205 `Hexadecimal numbers'@w{ }
28207 gcc / @code{as}: Leading ‘0x’ (C language syntax); for example @code{0xA0}@w{ }
28208 Intel: Trailing ‘h’; for example @code{A0h}@w{ }
28216 `Operand size'@w{ }
28218 gcc / @code{as}: Explicit in op code; for example @code{movw} to move a 16-bit word@w{ }
28219 Intel: Implicit, deduced by assembler; for example @code{mov}@w{ }
28227 `Instruction repetition'@w{ }
28229 gcc / @code{as}: Split into two lines; for example@w{ }
28234 Intel: Keep on one line; for example @code{rep stosl}@w{ }
28242 `Order of operands'@w{ }
28244 gcc / @code{as}: Source first; for example @code{movw $4, %eax}@w{ }
28245 Intel: Destination first; for example @code{mov eax, 4}@w{ }
28251 @node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
28252 @anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{23a}@anchor{gnat_ugn/inline_assembler id3}@anchor{23b}
28253 @section A Simple Example of Inline Assembler
28256 The following example will generate a single assembly language statement,
28257 @code{nop}, which does nothing. Despite its lack of run-time effect,
28258 the example will be useful in illustrating the basics of
28259 the Inline Assembler facility.
28264 with System.Machine_Code; use System.Machine_Code;
28265 procedure Nothing is
28272 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
28273 here it takes one parameter, a `template string' that must be a static
28274 expression and that will form the generated instruction.
28275 @code{Asm} may be regarded as a compile-time procedure that parses
28276 the template string and additional parameters (none here),
28277 from which it generates a sequence of assembly language instructions.
28279 The examples in this chapter will illustrate several of the forms
28280 for invoking @code{Asm}; a complete specification of the syntax
28281 is found in the @code{Machine_Code_Insertions} section of the
28282 @cite{GNAT Reference Manual}.
28284 Under the standard GNAT conventions, the @code{Nothing} procedure
28285 should be in a file named @code{nothing.adb}.
28286 You can build the executable in the usual way:
28295 However, the interesting aspect of this example is not its run-time behavior
28296 but rather the generated assembly code.
28297 To see this output, invoke the compiler as follows:
28302 $ gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
28306 where the options are:
28317 compile only (no bind or link)
28326 generate assembler listing
28333 @item @code{-fomit-frame-pointer}
28335 do not set up separate stack frames
28342 @item @code{-gnatp}
28344 do not add runtime checks
28348 This gives a human-readable assembler version of the code. The resulting
28349 file will have the same name as the Ada source file, but with a @code{.s}
28350 extension. In our example, the file @code{nothing.s} has the following
28356 .file "nothing.adb"
28358 ___gnu_compiled_ada:
28361 .globl __ada_nothing
28373 The assembly code you included is clearly indicated by
28374 the compiler, between the @code{#APP} and @code{#NO_APP}
28375 delimiters. The character before the ‘APP’ and ‘NOAPP’
28376 can differ on different targets. For example, GNU/Linux uses ‘#APP’ while
28377 on NT you will see ‘/APP’.
28379 If you make a mistake in your assembler code (such as using the
28380 wrong size modifier, or using a wrong operand for the instruction) GNAT
28381 will report this error in a temporary file, which will be deleted when
28382 the compilation is finished. Generating an assembler file will help
28383 in such cases, since you can assemble this file separately using the
28384 @code{as} assembler that comes with gcc.
28386 Assembling the file using the command
28395 will give you error messages whose lines correspond to the assembler
28396 input file, so you can easily find and correct any mistakes you made.
28397 If there are no errors, @code{as} will generate an object file
28398 @code{nothing.out}.
28400 @node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
28401 @anchor{gnat_ugn/inline_assembler id4}@anchor{23c}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{23d}
28402 @section Output Variables in Inline Assembler
28405 The examples in this section, showing how to access the processor flags,
28406 illustrate how to specify the destination operands for assembly language
28412 with Interfaces; use Interfaces;
28413 with Ada.Text_IO; use Ada.Text_IO;
28414 with System.Machine_Code; use System.Machine_Code;
28415 procedure Get_Flags is
28416 Flags : Unsigned_32;
28419 Asm ("pushfl" & LF & HT & -- push flags on stack
28420 "popl %%eax" & LF & HT & -- load eax with flags
28421 "movl %%eax, %0", -- store flags in variable
28422 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28423 Put_Line ("Flags register:" & Flags'Img);
28428 In order to have a nicely aligned assembly listing, we have separated
28429 multiple assembler statements in the Asm template string with linefeed
28430 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
28431 The resulting section of the assembly output file is:
28439 movl %eax, -40(%ebp)
28444 It would have been legal to write the Asm invocation as:
28449 Asm ("pushfl popl %%eax movl %%eax, %0")
28453 but in the generated assembler file, this would come out as:
28459 pushfl popl %eax movl %eax, -40(%ebp)
28464 which is not so convenient for the human reader.
28466 We use Ada comments
28467 at the end of each line to explain what the assembler instructions
28468 actually do. This is a useful convention.
28470 When writing Inline Assembler instructions, you need to precede each register
28471 and variable name with a percent sign. Since the assembler already requires
28472 a percent sign at the beginning of a register name, you need two consecutive
28473 percent signs for such names in the Asm template string, thus @code{%%eax}.
28474 In the generated assembly code, one of the percent signs will be stripped off.
28476 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
28477 variables: operands you later define using @code{Input} or @code{Output}
28478 parameters to @code{Asm}.
28479 An output variable is illustrated in
28480 the third statement in the Asm template string:
28489 The intent is to store the contents of the eax register in a variable that can
28490 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
28491 necessarily work, since the compiler might optimize by using a register
28492 to hold Flags, and the expansion of the @code{movl} instruction would not be
28493 aware of this optimization. The solution is not to store the result directly
28494 but rather to advise the compiler to choose the correct operand form;
28495 that is the purpose of the @code{%0} output variable.
28497 Information about the output variable is supplied in the @code{Outputs}
28498 parameter to @code{Asm}:
28503 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28507 The output is defined by the @code{Asm_Output} attribute of the target type;
28508 the general format is
28513 Type'Asm_Output (constraint_string, variable_name)
28517 The constraint string directs the compiler how
28518 to store/access the associated variable. In the example
28523 Unsigned_32'Asm_Output ("=m", Flags);
28527 the @code{"m"} (memory) constraint tells the compiler that the variable
28528 @code{Flags} should be stored in a memory variable, thus preventing
28529 the optimizer from keeping it in a register. In contrast,
28534 Unsigned_32'Asm_Output ("=r", Flags);
28538 uses the @code{"r"} (register) constraint, telling the compiler to
28539 store the variable in a register.
28541 If the constraint is preceded by the equal character ‘=’, it tells
28542 the compiler that the variable will be used to store data into it.
28544 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
28545 allowing the optimizer to choose whatever it deems best.
28547 There are a fairly large number of constraints, but the ones that are
28548 most useful (for the Intel x86 processor) are the following:
28553 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
28568 global (i.e., can be stored anywhere)
28640 use one of eax, ebx, ecx or edx
28648 use one of eax, ebx, ecx, edx, esi or edi
28654 The full set of constraints is described in the gcc and @code{as}
28655 documentation; note that it is possible to combine certain constraints
28656 in one constraint string.
28658 You specify the association of an output variable with an assembler operand
28659 through the @code{%@var{n}} notation, where `n' is a non-negative
28665 Asm ("pushfl" & LF & HT & -- push flags on stack
28666 "popl %%eax" & LF & HT & -- load eax with flags
28667 "movl %%eax, %0", -- store flags in variable
28668 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28672 @code{%0} will be replaced in the expanded code by the appropriate operand,
28674 the compiler decided for the @code{Flags} variable.
28676 In general, you may have any number of output variables:
28682 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
28685 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
28686 of @code{Asm_Output} attributes
28694 Asm ("movl %%eax, %0" & LF & HT &
28695 "movl %%ebx, %1" & LF & HT &
28697 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
28698 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
28699 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
28703 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28704 in the Ada program.
28706 As a variation on the @code{Get_Flags} example, we can use the constraints
28707 string to direct the compiler to store the eax register into the @code{Flags}
28708 variable, instead of including the store instruction explicitly in the
28709 @code{Asm} template string:
28714 with Interfaces; use Interfaces;
28715 with Ada.Text_IO; use Ada.Text_IO;
28716 with System.Machine_Code; use System.Machine_Code;
28717 procedure Get_Flags_2 is
28718 Flags : Unsigned_32;
28721 Asm ("pushfl" & LF & HT & -- push flags on stack
28722 "popl %%eax", -- save flags in eax
28723 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28724 Put_Line ("Flags register:" & Flags'Img);
28729 The @code{"a"} constraint tells the compiler that the @code{Flags}
28730 variable will come from the eax register. Here is the resulting code:
28739 movl %eax,-40(%ebp)
28743 The compiler generated the store of eax into Flags after
28744 expanding the assembler code.
28746 Actually, there was no need to pop the flags into the eax register;
28747 more simply, we could just pop the flags directly into the program variable:
28752 with Interfaces; use Interfaces;
28753 with Ada.Text_IO; use Ada.Text_IO;
28754 with System.Machine_Code; use System.Machine_Code;
28755 procedure Get_Flags_3 is
28756 Flags : Unsigned_32;
28759 Asm ("pushfl" & LF & HT & -- push flags on stack
28760 "pop %0", -- save flags in Flags
28761 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28762 Put_Line ("Flags register:" & Flags'Img);
28767 @node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
28768 @anchor{gnat_ugn/inline_assembler id5}@anchor{23e}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{23f}
28769 @section Input Variables in Inline Assembler
28772 The example in this section illustrates how to specify the source operands
28773 for assembly language statements.
28774 The program simply increments its input value by 1:
28779 with Interfaces; use Interfaces;
28780 with Ada.Text_IO; use Ada.Text_IO;
28781 with System.Machine_Code; use System.Machine_Code;
28782 procedure Increment is
28784 function Incr (Value : Unsigned_32) return Unsigned_32 is
28785 Result : Unsigned_32;
28788 Outputs => Unsigned_32'Asm_Output ("=a", Result),
28789 Inputs => Unsigned_32'Asm_Input ("a", Value));
28793 Value : Unsigned_32;
28797 Put_Line ("Value before is" & Value'Img);
28798 Value := Incr (Value);
28799 Put_Line ("Value after is" & Value'Img);
28804 The @code{Outputs} parameter to @code{Asm} specifies
28805 that the result will be in the eax register and that it is to be stored
28806 in the @code{Result} variable.
28808 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28809 but with an @code{Asm_Input} attribute.
28810 The @code{"="} constraint, indicating an output value, is not present.
28812 You can have multiple input variables, in the same way that you can have more
28813 than one output variable.
28815 The parameter count (%0, %1) etc, still starts at the first output statement,
28816 and continues with the input statements.
28818 Just as the @code{Outputs} parameter causes the register to be stored into the
28819 target variable after execution of the assembler statements, so does the
28820 @code{Inputs} parameter cause its variable to be loaded into the register
28821 before execution of the assembler statements.
28823 Thus the effect of the @code{Asm} invocation is:
28829 load the 32-bit value of @code{Value} into eax
28832 execute the @code{incl %eax} instruction
28835 store the contents of eax into the @code{Result} variable
28838 The resulting assembler file (with @code{-O2} optimization) contains:
28843 _increment__incr.1:
28856 @node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
28857 @anchor{gnat_ugn/inline_assembler id6}@anchor{240}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{241}
28858 @section Inlining Inline Assembler Code
28861 For a short subprogram such as the @code{Incr} function in the previous
28862 section, the overhead of the call and return (creating / deleting the stack
28863 frame) can be significant, compared to the amount of code in the subprogram
28864 body. A solution is to apply Ada’s @code{Inline} pragma to the subprogram,
28865 which directs the compiler to expand invocations of the subprogram at the
28866 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28867 Here is the resulting program:
28872 with Interfaces; use Interfaces;
28873 with Ada.Text_IO; use Ada.Text_IO;
28874 with System.Machine_Code; use System.Machine_Code;
28875 procedure Increment_2 is
28877 function Incr (Value : Unsigned_32) return Unsigned_32 is
28878 Result : Unsigned_32;
28881 Outputs => Unsigned_32'Asm_Output ("=a", Result),
28882 Inputs => Unsigned_32'Asm_Input ("a", Value));
28885 pragma Inline (Increment);
28887 Value : Unsigned_32;
28891 Put_Line ("Value before is" & Value'Img);
28892 Value := Increment (Value);
28893 Put_Line ("Value after is" & Value'Img);
28898 Compile the program with both optimization (@code{-O2}) and inlining
28899 (@code{-gnatn}) enabled.
28901 The @code{Incr} function is still compiled as usual, but at the
28902 point in @code{Increment} where our function used to be called:
28908 call _increment__incr.1
28912 the code for the function body directly appears:
28925 thus saving the overhead of stack frame setup and an out-of-line call.
28927 @node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
28928 @anchor{gnat_ugn/inline_assembler id7}@anchor{242}@anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{243}
28929 @section Other @code{Asm} Functionality
28932 This section describes two important parameters to the @code{Asm}
28933 procedure: @code{Clobber}, which identifies register usage;
28934 and @code{Volatile}, which inhibits unwanted optimizations.
28937 * The Clobber Parameter::
28938 * The Volatile Parameter::
28942 @node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
28943 @anchor{gnat_ugn/inline_assembler id8}@anchor{244}@anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{245}
28944 @subsection The @code{Clobber} Parameter
28947 One of the dangers of intermixing assembly language and a compiled language
28948 such as Ada is that the compiler needs to be aware of which registers are
28949 being used by the assembly code. In some cases, such as the earlier examples,
28950 the constraint string is sufficient to indicate register usage (e.g.,
28952 the eax register). But more generally, the compiler needs an explicit
28953 identification of the registers that are used by the Inline Assembly
28956 Using a register that the compiler doesn’t know about
28957 could be a side effect of an instruction (like @code{mull}
28958 storing its result in both eax and edx).
28959 It can also arise from explicit register usage in your
28960 assembly code; for example:
28965 Asm ("movl %0, %%ebx" & LF & HT &
28967 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28968 Inputs => Unsigned_32'Asm_Input ("g", Var_In));
28972 where the compiler (since it does not analyze the @code{Asm} template string)
28973 does not know you are using the ebx register.
28975 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
28976 to identify the registers that will be used by your assembly code:
28981 Asm ("movl %0, %%ebx" & LF & HT &
28983 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28984 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28989 The Clobber parameter is a static string expression specifying the
28990 register(s) you are using. Note that register names are `not' prefixed
28991 by a percent sign. Also, if more than one register is used then their names
28992 are separated by commas; e.g., @code{"eax, ebx"}
28994 The @code{Clobber} parameter has several additional uses:
29000 Use ‘register’ name @code{cc} to indicate that flags might have changed
29003 Use ‘register’ name @code{memory} if you changed a memory location
29006 @node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
29007 @anchor{gnat_ugn/inline_assembler id9}@anchor{246}@anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{247}
29008 @subsection The @code{Volatile} Parameter
29011 @geindex Volatile parameter
29013 Compiler optimizations in the presence of Inline Assembler may sometimes have
29014 unwanted effects. For example, when an @code{Asm} invocation with an input
29015 variable is inside a loop, the compiler might move the loading of the input
29016 variable outside the loop, regarding it as a one-time initialization.
29018 If this effect is not desired, you can disable such optimizations by setting
29019 the @code{Volatile} parameter to @code{True}; for example:
29024 Asm ("movl %0, %%ebx" & LF & HT &
29026 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29027 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
29033 By default, @code{Volatile} is set to @code{False} unless there is no
29034 @code{Outputs} parameter.
29036 Although setting @code{Volatile} to @code{True} prevents unwanted
29037 optimizations, it will also disable other optimizations that might be
29038 important for efficiency. In general, you should set @code{Volatile}
29039 to @code{True} only if the compiler’s optimizations have created
29042 @node GNU Free Documentation License,Index,Inline Assembler,Top
29043 @anchor{share/gnu_free_documentation_license doc}@anchor{248}@anchor{share/gnu_free_documentation_license gnu-fdl}@anchor{1}@anchor{share/gnu_free_documentation_license gnu-free-documentation-license}@anchor{249}
29044 @chapter GNU Free Documentation License
29047 Version 1.3, 3 November 2008
29049 Copyright 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc
29050 @indicateurl{https://fsf.org/}
29052 Everyone is permitted to copy and distribute verbatim copies of this
29053 license document, but changing it is not allowed.
29057 The purpose of this License is to make a manual, textbook, or other
29058 functional and useful document “free” in the sense of freedom: to
29059 assure everyone the effective freedom to copy and redistribute it,
29060 with or without modifying it, either commercially or noncommercially.
29061 Secondarily, this License preserves for the author and publisher a way
29062 to get credit for their work, while not being considered responsible
29063 for modifications made by others.
29065 This License is a kind of “copyleft”, which means that derivative
29066 works of the document must themselves be free in the same sense. It
29067 complements the GNU General Public License, which is a copyleft
29068 license designed for free software.
29070 We have designed this License in order to use it for manuals for free
29071 software, because free software needs free documentation: a free
29072 program should come with manuals providing the same freedoms that the
29073 software does. But this License is not limited to software manuals;
29074 it can be used for any textual work, regardless of subject matter or
29075 whether it is published as a printed book. We recommend this License
29076 principally for works whose purpose is instruction or reference.
29078 `1. APPLICABILITY AND DEFINITIONS'
29080 This License applies to any manual or other work, in any medium, that
29081 contains a notice placed by the copyright holder saying it can be
29082 distributed under the terms of this License. Such a notice grants a
29083 world-wide, royalty-free license, unlimited in duration, to use that
29084 work under the conditions stated herein. The `Document', below,
29085 refers to any such manual or work. Any member of the public is a
29086 licensee, and is addressed as “`you'”. You accept the license if you
29087 copy, modify or distribute the work in a way requiring permission
29088 under copyright law.
29090 A “`Modified Version'” of the Document means any work containing the
29091 Document or a portion of it, either copied verbatim, or with
29092 modifications and/or translated into another language.
29094 A “`Secondary Section'” is a named appendix or a front-matter section of
29095 the Document that deals exclusively with the relationship of the
29096 publishers or authors of the Document to the Document’s overall subject
29097 (or to related matters) and contains nothing that could fall directly
29098 within that overall subject. (Thus, if the Document is in part a
29099 textbook of mathematics, a Secondary Section may not explain any
29100 mathematics.) The relationship could be a matter of historical
29101 connection with the subject or with related matters, or of legal,
29102 commercial, philosophical, ethical or political position regarding
29105 The “`Invariant Sections'” are certain Secondary Sections whose titles
29106 are designated, as being those of Invariant Sections, in the notice
29107 that says that the Document is released under this License. If a
29108 section does not fit the above definition of Secondary then it is not
29109 allowed to be designated as Invariant. The Document may contain zero
29110 Invariant Sections. If the Document does not identify any Invariant
29111 Sections then there are none.
29113 The “`Cover Texts'” are certain short passages of text that are listed,
29114 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
29115 the Document is released under this License. A Front-Cover Text may
29116 be at most 5 words, and a Back-Cover Text may be at most 25 words.
29118 A “`Transparent'” copy of the Document means a machine-readable copy,
29119 represented in a format whose specification is available to the
29120 general public, that is suitable for revising the document
29121 straightforwardly with generic text editors or (for images composed of
29122 pixels) generic paint programs or (for drawings) some widely available
29123 drawing editor, and that is suitable for input to text formatters or
29124 for automatic translation to a variety of formats suitable for input
29125 to text formatters. A copy made in an otherwise Transparent file
29126 format whose markup, or absence of markup, has been arranged to thwart
29127 or discourage subsequent modification by readers is not Transparent.
29128 An image format is not Transparent if used for any substantial amount
29129 of text. A copy that is not “Transparent” is called `Opaque'.
29131 Examples of suitable formats for Transparent copies include plain
29132 ASCII without markup, Texinfo input format, LaTeX input format, SGML
29133 or XML using a publicly available DTD, and standard-conforming simple
29134 HTML, PostScript or PDF designed for human modification. Examples of
29135 transparent image formats include PNG, XCF and JPG. Opaque formats
29136 include proprietary formats that can be read and edited only by
29137 proprietary word processors, SGML or XML for which the DTD and/or
29138 processing tools are not generally available, and the
29139 machine-generated HTML, PostScript or PDF produced by some word
29140 processors for output purposes only.
29142 The “`Title Page'” means, for a printed book, the title page itself,
29143 plus such following pages as are needed to hold, legibly, the material
29144 this License requires to appear in the title page. For works in
29145 formats which do not have any title page as such, “Title Page” means
29146 the text near the most prominent appearance of the work’s title,
29147 preceding the beginning of the body of the text.
29149 The “`publisher'” means any person or entity that distributes
29150 copies of the Document to the public.
29152 A section “`Entitled XYZ'” means a named subunit of the Document whose
29153 title either is precisely XYZ or contains XYZ in parentheses following
29154 text that translates XYZ in another language. (Here XYZ stands for a
29155 specific section name mentioned below, such as “`Acknowledgements'”,
29156 “`Dedications'”, “`Endorsements'”, or “`History'”.)
29157 To “`Preserve the Title'”
29158 of such a section when you modify the Document means that it remains a
29159 section “Entitled XYZ” according to this definition.
29161 The Document may include Warranty Disclaimers next to the notice which
29162 states that this License applies to the Document. These Warranty
29163 Disclaimers are considered to be included by reference in this
29164 License, but only as regards disclaiming warranties: any other
29165 implication that these Warranty Disclaimers may have is void and has
29166 no effect on the meaning of this License.
29168 `2. VERBATIM COPYING'
29170 You may copy and distribute the Document in any medium, either
29171 commercially or noncommercially, provided that this License, the
29172 copyright notices, and the license notice saying this License applies
29173 to the Document are reproduced in all copies, and that you add no other
29174 conditions whatsoever to those of this License. You may not use
29175 technical measures to obstruct or control the reading or further
29176 copying of the copies you make or distribute. However, you may accept
29177 compensation in exchange for copies. If you distribute a large enough
29178 number of copies you must also follow the conditions in section 3.
29180 You may also lend copies, under the same conditions stated above, and
29181 you may publicly display copies.
29183 `3. COPYING IN QUANTITY'
29185 If you publish printed copies (or copies in media that commonly have
29186 printed covers) of the Document, numbering more than 100, and the
29187 Document’s license notice requires Cover Texts, you must enclose the
29188 copies in covers that carry, clearly and legibly, all these Cover
29189 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
29190 the back cover. Both covers must also clearly and legibly identify
29191 you as the publisher of these copies. The front cover must present
29192 the full title with all words of the title equally prominent and
29193 visible. You may add other material on the covers in addition.
29194 Copying with changes limited to the covers, as long as they preserve
29195 the title of the Document and satisfy these conditions, can be treated
29196 as verbatim copying in other respects.
29198 If the required texts for either cover are too voluminous to fit
29199 legibly, you should put the first ones listed (as many as fit
29200 reasonably) on the actual cover, and continue the rest onto adjacent
29203 If you publish or distribute Opaque copies of the Document numbering
29204 more than 100, you must either include a machine-readable Transparent
29205 copy along with each Opaque copy, or state in or with each Opaque copy
29206 a computer-network location from which the general network-using
29207 public has access to download using public-standard network protocols
29208 a complete Transparent copy of the Document, free of added material.
29209 If you use the latter option, you must take reasonably prudent steps,
29210 when you begin distribution of Opaque copies in quantity, to ensure
29211 that this Transparent copy will remain thus accessible at the stated
29212 location until at least one year after the last time you distribute an
29213 Opaque copy (directly or through your agents or retailers) of that
29214 edition to the public.
29216 It is requested, but not required, that you contact the authors of the
29217 Document well before redistributing any large number of copies, to give
29218 them a chance to provide you with an updated version of the Document.
29222 You may copy and distribute a Modified Version of the Document under
29223 the conditions of sections 2 and 3 above, provided that you release
29224 the Modified Version under precisely this License, with the Modified
29225 Version filling the role of the Document, thus licensing distribution
29226 and modification of the Modified Version to whoever possesses a copy
29227 of it. In addition, you must do these things in the Modified Version:
29233 Use in the Title Page (and on the covers, if any) a title distinct
29234 from that of the Document, and from those of previous versions
29235 (which should, if there were any, be listed in the History section
29236 of the Document). You may use the same title as a previous version
29237 if the original publisher of that version gives permission.
29240 List on the Title Page, as authors, one or more persons or entities
29241 responsible for authorship of the modifications in the Modified
29242 Version, together with at least five of the principal authors of the
29243 Document (all of its principal authors, if it has fewer than five),
29244 unless they release you from this requirement.
29247 State on the Title page the name of the publisher of the
29248 Modified Version, as the publisher.
29251 Preserve all the copyright notices of the Document.
29254 Add an appropriate copyright notice for your modifications
29255 adjacent to the other copyright notices.
29258 Include, immediately after the copyright notices, a license notice
29259 giving the public permission to use the Modified Version under the
29260 terms of this License, in the form shown in the Addendum below.
29263 Preserve in that license notice the full lists of Invariant Sections
29264 and required Cover Texts given in the Document’s license notice.
29267 Include an unaltered copy of this License.
29270 Preserve the section Entitled “History”, Preserve its Title, and add
29271 to it an item stating at least the title, year, new authors, and
29272 publisher of the Modified Version as given on the Title Page. If
29273 there is no section Entitled “History” in the Document, create one
29274 stating the title, year, authors, and publisher of the Document as
29275 given on its Title Page, then add an item describing the Modified
29276 Version as stated in the previous sentence.
29279 Preserve the network location, if any, given in the Document for
29280 public access to a Transparent copy of the Document, and likewise
29281 the network locations given in the Document for previous versions
29282 it was based on. These may be placed in the “History” section.
29283 You may omit a network location for a work that was published at
29284 least four years before the Document itself, or if the original
29285 publisher of the version it refers to gives permission.
29288 For any section Entitled “Acknowledgements” or “Dedications”,
29289 Preserve the Title of the section, and preserve in the section all
29290 the substance and tone of each of the contributor acknowledgements
29291 and/or dedications given therein.
29294 Preserve all the Invariant Sections of the Document,
29295 unaltered in their text and in their titles. Section numbers
29296 or the equivalent are not considered part of the section titles.
29299 Delete any section Entitled “Endorsements”. Such a section
29300 may not be included in the Modified Version.
29303 Do not retitle any existing section to be Entitled “Endorsements”
29304 or to conflict in title with any Invariant Section.
29307 Preserve any Warranty Disclaimers.
29310 If the Modified Version includes new front-matter sections or
29311 appendices that qualify as Secondary Sections and contain no material
29312 copied from the Document, you may at your option designate some or all
29313 of these sections as invariant. To do this, add their titles to the
29314 list of Invariant Sections in the Modified Version’s license notice.
29315 These titles must be distinct from any other section titles.
29317 You may add a section Entitled “Endorsements”, provided it contains
29318 nothing but endorsements of your Modified Version by various
29319 parties—for example, statements of peer review or that the text has
29320 been approved by an organization as the authoritative definition of a
29323 You may add a passage of up to five words as a Front-Cover Text, and a
29324 passage of up to 25 words as a Back-Cover Text, to the end of the list
29325 of Cover Texts in the Modified Version. Only one passage of
29326 Front-Cover Text and one of Back-Cover Text may be added by (or
29327 through arrangements made by) any one entity. If the Document already
29328 includes a cover text for the same cover, previously added by you or
29329 by arrangement made by the same entity you are acting on behalf of,
29330 you may not add another; but you may replace the old one, on explicit
29331 permission from the previous publisher that added the old one.
29333 The author(s) and publisher(s) of the Document do not by this License
29334 give permission to use their names for publicity for or to assert or
29335 imply endorsement of any Modified Version.
29337 `5. COMBINING DOCUMENTS'
29339 You may combine the Document with other documents released under this
29340 License, under the terms defined in section 4 above for modified
29341 versions, provided that you include in the combination all of the
29342 Invariant Sections of all of the original documents, unmodified, and
29343 list them all as Invariant Sections of your combined work in its
29344 license notice, and that you preserve all their Warranty Disclaimers.
29346 The combined work need only contain one copy of this License, and
29347 multiple identical Invariant Sections may be replaced with a single
29348 copy. If there are multiple Invariant Sections with the same name but
29349 different contents, make the title of each such section unique by
29350 adding at the end of it, in parentheses, the name of the original
29351 author or publisher of that section if known, or else a unique number.
29352 Make the same adjustment to the section titles in the list of
29353 Invariant Sections in the license notice of the combined work.
29355 In the combination, you must combine any sections Entitled “History”
29356 in the various original documents, forming one section Entitled
29357 “History”; likewise combine any sections Entitled “Acknowledgements”,
29358 and any sections Entitled “Dedications”. You must delete all sections
29359 Entitled “Endorsements”.
29361 `6. COLLECTIONS OF DOCUMENTS'
29363 You may make a collection consisting of the Document and other documents
29364 released under this License, and replace the individual copies of this
29365 License in the various documents with a single copy that is included in
29366 the collection, provided that you follow the rules of this License for
29367 verbatim copying of each of the documents in all other respects.
29369 You may extract a single document from such a collection, and distribute
29370 it individually under this License, provided you insert a copy of this
29371 License into the extracted document, and follow this License in all
29372 other respects regarding verbatim copying of that document.
29374 `7. AGGREGATION WITH INDEPENDENT WORKS'
29376 A compilation of the Document or its derivatives with other separate
29377 and independent documents or works, in or on a volume of a storage or
29378 distribution medium, is called an “aggregate” if the copyright
29379 resulting from the compilation is not used to limit the legal rights
29380 of the compilation’s users beyond what the individual works permit.
29381 When the Document is included in an aggregate, this License does not
29382 apply to the other works in the aggregate which are not themselves
29383 derivative works of the Document.
29385 If the Cover Text requirement of section 3 is applicable to these
29386 copies of the Document, then if the Document is less than one half of
29387 the entire aggregate, the Document’s Cover Texts may be placed on
29388 covers that bracket the Document within the aggregate, or the
29389 electronic equivalent of covers if the Document is in electronic form.
29390 Otherwise they must appear on printed covers that bracket the whole
29395 Translation is considered a kind of modification, so you may
29396 distribute translations of the Document under the terms of section 4.
29397 Replacing Invariant Sections with translations requires special
29398 permission from their copyright holders, but you may include
29399 translations of some or all Invariant Sections in addition to the
29400 original versions of these Invariant Sections. You may include a
29401 translation of this License, and all the license notices in the
29402 Document, and any Warranty Disclaimers, provided that you also include
29403 the original English version of this License and the original versions
29404 of those notices and disclaimers. In case of a disagreement between
29405 the translation and the original version of this License or a notice
29406 or disclaimer, the original version will prevail.
29408 If a section in the Document is Entitled “Acknowledgements”,
29409 “Dedications”, or “History”, the requirement (section 4) to Preserve
29410 its Title (section 1) will typically require changing the actual
29415 You may not copy, modify, sublicense, or distribute the Document
29416 except as expressly provided under this License. Any attempt
29417 otherwise to copy, modify, sublicense, or distribute it is void, and
29418 will automatically terminate your rights under this License.
29420 However, if you cease all violation of this License, then your license
29421 from a particular copyright holder is reinstated (a) provisionally,
29422 unless and until the copyright holder explicitly and finally
29423 terminates your license, and (b) permanently, if the copyright holder
29424 fails to notify you of the violation by some reasonable means prior to
29425 60 days after the cessation.
29427 Moreover, your license from a particular copyright holder is
29428 reinstated permanently if the copyright holder notifies you of the
29429 violation by some reasonable means, this is the first time you have
29430 received notice of violation of this License (for any work) from that
29431 copyright holder, and you cure the violation prior to 30 days after
29432 your receipt of the notice.
29434 Termination of your rights under this section does not terminate the
29435 licenses of parties who have received copies or rights from you under
29436 this License. If your rights have been terminated and not permanently
29437 reinstated, receipt of a copy of some or all of the same material does
29438 not give you any rights to use it.
29440 `10. FUTURE REVISIONS OF THIS LICENSE'
29442 The Free Software Foundation may publish new, revised versions
29443 of the GNU Free Documentation License from time to time. Such new
29444 versions will be similar in spirit to the present version, but may
29445 differ in detail to address new problems or concerns. See
29446 @indicateurl{https://www.gnu.org/copyleft/}.
29448 Each version of the License is given a distinguishing version number.
29449 If the Document specifies that a particular numbered version of this
29450 License “or any later version” applies to it, you have the option of
29451 following the terms and conditions either of that specified version or
29452 of any later version that has been published (not as a draft) by the
29453 Free Software Foundation. If the Document does not specify a version
29454 number of this License, you may choose any version ever published (not
29455 as a draft) by the Free Software Foundation. If the Document
29456 specifies that a proxy can decide which future versions of this
29457 License can be used, that proxy’s public statement of acceptance of a
29458 version permanently authorizes you to choose that version for the
29463 “Massive Multiauthor Collaboration Site” (or “MMC Site”) means any
29464 World Wide Web server that publishes copyrightable works and also
29465 provides prominent facilities for anybody to edit those works. A
29466 public wiki that anybody can edit is an example of such a server. A
29467 “Massive Multiauthor Collaboration” (or “MMC”) contained in the
29468 site means any set of copyrightable works thus published on the MMC
29471 “CC-BY-SA” means the Creative Commons Attribution-Share Alike 3.0
29472 license published by Creative Commons Corporation, a not-for-profit
29473 corporation with a principal place of business in San Francisco,
29474 California, as well as future copyleft versions of that license
29475 published by that same organization.
29477 “Incorporate” means to publish or republish a Document, in whole or
29478 in part, as part of another Document.
29480 An MMC is “eligible for relicensing” if it is licensed under this
29481 License, and if all works that were first published under this License
29482 somewhere other than this MMC, and subsequently incorporated in whole
29483 or in part into the MMC, (1) had no cover texts or invariant sections,
29484 and (2) were thus incorporated prior to November 1, 2008.
29486 The operator of an MMC Site may republish an MMC contained in the site
29487 under CC-BY-SA on the same site at any time before August 1, 2009,
29488 provided the MMC is eligible for relicensing.
29490 `ADDENDUM: How to use this License for your documents'
29492 To use this License in a document you have written, include a copy of
29493 the License in the document and put the following copyright and
29494 license notices just after the title page:
29498 Copyright © YEAR YOUR NAME.
29499 Permission is granted to copy, distribute and/or modify this document
29500 under the terms of the GNU Free Documentation License, Version 1.3
29501 or any later version published by the Free Software Foundation;
29502 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
29503 A copy of the license is included in the section entitled “GNU
29504 Free Documentation License”.
29507 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
29508 replace the “with … Texts.” line with this:
29512 with the Invariant Sections being LIST THEIR TITLES, with the
29513 Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
29516 If you have Invariant Sections without Cover Texts, or some other
29517 combination of the three, merge those two alternatives to suit the
29520 If your document contains nontrivial examples of program code, we
29521 recommend releasing these examples in parallel under your choice of
29522 free software license, such as the GNU General Public License,
29523 to permit their use in free software.
29525 @node Index,,GNU Free Documentation License,Top
29532 @anchor{gnat_ugn/gnat_utility_programs switches-related-to-project-files}@w{ }