ada: Further cleanup in finalization machinery
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blob694a83411a2ce9f460106aee3ae7e24f7d548349
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename gnat_ugn.info
4 @documentencoding UTF-8
5 @ifinfo
6 @*Generated by Sphinx 4.3.2.@*
7 @end ifinfo
8 @settitle GNAT User's Guide for Native Platforms
9 @defindex ge
10 @paragraphindent 0
11 @exampleindent 4
12 @finalout
13 @dircategory GNU Ada Tools 
14 @direntry
15 * gnat_ugn: (gnat_ugn.info). gnat_ugn
16 @end direntry
18 @definfoenclose strong,`,'
19 @definfoenclose emph,`,'
20 @c %**end of header
22 @copying
23 @quotation
24 GNAT User's Guide for Native Platforms , Dec 14, 2023
26 AdaCore
28 Copyright @copyright{} 2008-2023, Free Software Foundation
29 @end quotation
31 @end copying
33 @titlepage
34 @title GNAT User's Guide for Native Platforms
35 @insertcopying
36 @end titlepage
37 @contents
39 @c %** start of user preamble
41 @c %** end of user preamble
43 @ifnottex
44 @node Top
45 @top GNAT User's Guide for Native Platforms
46 @insertcopying
47 @end ifnottex
49 @c %**start of body
50 @anchor{gnat_ugn doc}@anchor{0}
51 @emph{GNAT, The GNU Ada Development Environment}
54 @include gcc-common.texi
55 GCC version @value{version-GCC}@*
56 AdaCore
58 Permission is granted to copy, distribute and/or modify this document
59 under the terms of the GNU Free Documentation License, Version 1.3 or
60 any later version published by the Free Software Foundation; with no
61 Invariant Sections, with the Front-Cover Texts being
62 “GNAT User’s Guide for Native Platforms”,
63 and with no Back-Cover Texts.  A copy of the license is
64 included in the section entitled @ref{1,,GNU Free Documentation License}.
66 @menu
67 * About This Guide:: 
68 * Getting Started with GNAT:: 
69 * The GNAT Compilation Model:: 
70 * Building Executable Programs with GNAT:: 
71 * GNAT Utility Programs:: 
72 * GNAT and Program Execution:: 
73 * Platform-Specific Information:: 
74 * Example of Binder Output File:: 
75 * Elaboration Order Handling in GNAT:: 
76 * Inline Assembler:: 
77 * GNU Free Documentation License:: 
78 * Index:: 
80 @detailmenu
81  --- The Detailed Node Listing ---
83 About This Guide
85 * What This Guide Contains:: 
86 * What You Should Know before Reading This Guide:: 
87 * Related Information:: 
88 * Conventions:: 
90 Getting Started with GNAT
92 * System Requirements:: 
93 * Running GNAT:: 
94 * Running a Simple Ada Program:: 
95 * Running a Program with Multiple Units:: 
97 The GNAT Compilation Model
99 * Source Representation:: 
100 * Foreign Language Representation:: 
101 * File Naming Topics and Utilities:: 
102 * Configuration Pragmas:: 
103 * Generating Object Files:: 
104 * Source Dependencies:: 
105 * The Ada Library Information Files:: 
106 * Binding an Ada Program:: 
107 * GNAT and Libraries:: 
108 * Conditional Compilation:: 
109 * Mixed Language Programming:: 
110 * GNAT and Other Compilation Models:: 
111 * Using GNAT Files with External Tools:: 
113 Foreign Language Representation
115 * Latin-1:: 
116 * Other 8-Bit Codes:: 
117 * Wide_Character Encodings:: 
118 * Wide_Wide_Character Encodings:: 
120 File Naming Topics and Utilities
122 * File Naming Rules:: 
123 * Using Other File Names:: 
124 * Alternative File Naming Schemes:: 
125 * Handling Arbitrary File Naming Conventions with gnatname:: 
126 * File Name Krunching with gnatkr:: 
127 * Renaming Files with gnatchop:: 
129 Handling Arbitrary File Naming Conventions with gnatname
131 * Arbitrary File Naming Conventions:: 
132 * Running gnatname:: 
133 * Switches for gnatname:: 
134 * Examples of gnatname Usage:: 
136 File Name Krunching with gnatkr
138 * About gnatkr:: 
139 * Using gnatkr:: 
140 * Krunching Method:: 
141 * Examples of gnatkr Usage:: 
143 Renaming Files with gnatchop
145 * Handling Files with Multiple Units:: 
146 * Operating gnatchop in Compilation Mode:: 
147 * Command Line for gnatchop:: 
148 * Switches for gnatchop:: 
149 * Examples of gnatchop Usage:: 
151 Configuration Pragmas
153 * Handling of Configuration Pragmas:: 
154 * The Configuration Pragmas Files:: 
156 GNAT and Libraries
158 * Introduction to Libraries in GNAT:: 
159 * General Ada Libraries:: 
160 * Stand-alone Ada Libraries:: 
161 * Rebuilding the GNAT Run-Time Library:: 
163 General Ada Libraries
165 * Building a library:: 
166 * Installing a library:: 
167 * Using a library:: 
169 Stand-alone Ada Libraries
171 * Introduction to Stand-alone Libraries:: 
172 * Building a Stand-alone Library:: 
173 * Creating a Stand-alone Library to be used in a non-Ada context:: 
174 * Restrictions in Stand-alone Libraries:: 
176 Conditional Compilation
178 * Modeling Conditional Compilation in Ada:: 
179 * Preprocessing with gnatprep:: 
180 * Integrated Preprocessing:: 
182 Modeling Conditional Compilation in Ada
184 * Use of Boolean Constants:: 
185 * Debugging - A Special Case:: 
186 * Conditionalizing Declarations:: 
187 * Use of Alternative Implementations:: 
188 * Preprocessing:: 
190 Preprocessing with gnatprep
192 * Preprocessing Symbols:: 
193 * Using gnatprep:: 
194 * Switches for gnatprep:: 
195 * Form of Definitions File:: 
196 * Form of Input Text for gnatprep:: 
198 Mixed Language Programming
200 * Interfacing to C:: 
201 * Calling Conventions:: 
202 * Building Mixed Ada and C++ Programs:: 
203 * Partition-Wide Settings:: 
204 * Generating Ada Bindings for C and C++ headers:: 
205 * Generating C Headers for Ada Specifications:: 
207 Building Mixed Ada and C++ Programs
209 * Interfacing to C++:: 
210 * Linking a Mixed C++ & Ada Program:: 
211 * A Simple Example:: 
212 * Interfacing with C++ constructors:: 
213 * Interfacing with C++ at the Class Level:: 
215 Generating Ada Bindings for C and C++ headers
217 * Running the Binding Generator:: 
218 * Generating Bindings for C++ Headers:: 
219 * Switches:: 
221 Generating C Headers for Ada Specifications
223 * Running the C Header Generator:: 
225 GNAT and Other Compilation Models
227 * Comparison between GNAT and C/C++ Compilation Models:: 
228 * Comparison between GNAT and Conventional Ada Library Models:: 
230 Using GNAT Files with External Tools
232 * Using Other Utility Programs with GNAT:: 
233 * The External Symbol Naming Scheme of GNAT:: 
235 Building Executable Programs with GNAT
237 * Building with gnatmake:: 
238 * Compiling with gcc:: 
239 * Compiler Switches:: 
240 * Linker Switches:: 
241 * Binding with gnatbind:: 
242 * Linking with gnatlink:: 
243 * Using the GNU make Utility:: 
245 Building with gnatmake
247 * Running gnatmake:: 
248 * Switches for gnatmake:: 
249 * Mode Switches for gnatmake:: 
250 * Notes on the Command Line:: 
251 * How gnatmake Works:: 
252 * Examples of gnatmake Usage:: 
254 Compiling with gcc
256 * Compiling Programs:: 
257 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
258 * Order of Compilation Issues:: 
259 * Examples:: 
261 Compiler Switches
263 * Alphabetical List of All Switches:: 
264 * Output and Error Message Control:: 
265 * Warning Message Control:: 
266 * Debugging and Assertion Control:: 
267 * Validity Checking:: 
268 * Style Checking:: 
269 * Run-Time Checks:: 
270 * Using gcc for Syntax Checking:: 
271 * Using gcc for Semantic Checking:: 
272 * Compiling Different Versions of Ada:: 
273 * Character Set Control:: 
274 * File Naming Control:: 
275 * Subprogram Inlining Control:: 
276 * Auxiliary Output Control:: 
277 * Debugging Control:: 
278 * Exception Handling Control:: 
279 * Units to Sources Mapping Files:: 
280 * Code Generation Control:: 
282 Binding with gnatbind
284 * Running gnatbind:: 
285 * Switches for gnatbind:: 
286 * Command-Line Access:: 
287 * Search Paths for gnatbind:: 
288 * Examples of gnatbind Usage:: 
290 Switches for gnatbind
292 * Consistency-Checking Modes:: 
293 * Binder Error Message Control:: 
294 * Elaboration Control:: 
295 * Output Control:: 
296 * Dynamic Allocation Control:: 
297 * Binding with Non-Ada Main Programs:: 
298 * Binding Programs with No Main Subprogram:: 
300 Linking with gnatlink
302 * Running gnatlink:: 
303 * Switches for gnatlink:: 
305 Using the GNU make Utility
307 * Using gnatmake in a Makefile:: 
308 * Automatically Creating a List of Directories:: 
309 * Generating the Command Line Switches:: 
310 * Overcoming Command Line Length Limits:: 
312 GNAT Utility Programs
314 * The File Cleanup Utility gnatclean:: 
315 * The GNAT Library Browser gnatls:: 
317 The File Cleanup Utility gnatclean
319 * Running gnatclean:: 
320 * Switches for gnatclean:: 
322 The GNAT Library Browser gnatls
324 * Running gnatls:: 
325 * Switches for gnatls:: 
326 * Example of gnatls Usage:: 
328 GNAT and Program Execution
330 * Running and Debugging Ada Programs:: 
331 * Profiling:: 
332 * Improving Performance:: 
333 * Overflow Check Handling in GNAT:: 
334 * Performing Dimensionality Analysis in GNAT:: 
335 * Stack Related Facilities:: 
336 * Memory Management Issues:: 
338 Running and Debugging Ada Programs
340 * The GNAT Debugger GDB:: 
341 * Running GDB:: 
342 * Introduction to GDB Commands:: 
343 * Using Ada Expressions:: 
344 * Calling User-Defined Subprograms:: 
345 * Using the next Command in a Function:: 
346 * Stopping When Ada Exceptions Are Raised:: 
347 * Ada Tasks:: 
348 * Debugging Generic Units:: 
349 * Remote Debugging with gdbserver:: 
350 * GNAT Abnormal Termination or Failure to Terminate:: 
351 * Naming Conventions for GNAT Source Files:: 
352 * Getting Internal Debugging Information:: 
353 * Stack Traceback:: 
354 * Pretty-Printers for the GNAT runtime:: 
356 Stack Traceback
358 * Non-Symbolic Traceback:: 
359 * Symbolic Traceback:: 
361 Profiling
363 * Profiling an Ada Program with gprof:: 
365 Profiling an Ada Program with gprof
367 * Compilation for profiling:: 
368 * Program execution:: 
369 * Running gprof:: 
370 * Interpretation of profiling results:: 
372 Improving Performance
374 * Performance Considerations:: 
375 * Text_IO Suggestions:: 
376 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
378 Performance Considerations
380 * Controlling Run-Time Checks:: 
381 * Use of Restrictions:: 
382 * Optimization Levels:: 
383 * Debugging Optimized Code:: 
384 * Inlining of Subprograms:: 
385 * Floating Point Operations:: 
386 * Vectorization of loops:: 
387 * Other Optimization Switches:: 
388 * Optimization and Strict Aliasing:: 
389 * Aliased Variables and Optimization:: 
390 * Atomic Variables and Optimization:: 
391 * Passive Task Optimization:: 
393 Reducing Size of Executables with Unused Subprogram/Data Elimination
395 * About unused subprogram/data elimination:: 
396 * Compilation options:: 
397 * Example of unused subprogram/data elimination:: 
399 Overflow Check Handling in GNAT
401 * Background:: 
402 * Management of Overflows in GNAT:: 
403 * Specifying the Desired Mode:: 
404 * Default Settings:: 
405 * Implementation Notes:: 
407 Stack Related Facilities
409 * Stack Overflow Checking:: 
410 * Static Stack Usage Analysis:: 
411 * Dynamic Stack Usage Analysis:: 
413 Memory Management Issues
415 * Some Useful Memory Pools:: 
416 * The GNAT Debug Pool Facility:: 
418 Platform-Specific Information
420 * Run-Time Libraries:: 
421 * Specifying a Run-Time Library:: 
422 * GNU/Linux Topics:: 
423 * Microsoft Windows Topics:: 
424 * Mac OS Topics:: 
426 Run-Time Libraries
428 * Summary of Run-Time Configurations:: 
430 Specifying a Run-Time Library
432 * Choosing the Scheduling Policy:: 
434 GNU/Linux Topics
436 * Required Packages on GNU/Linux:: 
437 * Position Independent Executable (PIE) Enabled by Default on Linux: Position Independent Executable PIE Enabled by Default on Linux. 
438 * A GNU/Linux Debug Quirk:: 
440 Microsoft Windows Topics
442 * Using GNAT on Windows:: 
443 * Using a network installation of GNAT:: 
444 * CONSOLE and WINDOWS subsystems:: 
445 * Temporary Files:: 
446 * Disabling Command Line Argument Expansion:: 
447 * Windows Socket Timeouts:: 
448 * Mixed-Language Programming on Windows:: 
449 * Windows Specific Add-Ons:: 
451 Mixed-Language Programming on Windows
453 * Windows Calling Conventions:: 
454 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
455 * Using DLLs with GNAT:: 
456 * Building DLLs with GNAT Project files:: 
457 * Building DLLs with GNAT:: 
458 * Building DLLs with gnatdll:: 
459 * Ada DLLs and Finalization:: 
460 * Creating a Spec for Ada DLLs:: 
461 * GNAT and Windows Resources:: 
462 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
463 * Debugging a DLL:: 
464 * Setting Stack Size from gnatlink:: 
465 * Setting Heap Size from gnatlink:: 
467 Windows Calling Conventions
469 * C Calling Convention:: 
470 * Stdcall Calling Convention:: 
471 * Win32 Calling Convention:: 
472 * DLL Calling Convention:: 
474 Using DLLs with GNAT
476 * Creating an Ada Spec for the DLL Services:: 
477 * Creating an Import Library:: 
479 Building DLLs with gnatdll
481 * Limitations When Using Ada DLLs from Ada:: 
482 * Exporting Ada Entities:: 
483 * Ada DLLs and Elaboration:: 
485 Creating a Spec for Ada DLLs
487 * Creating the Definition File:: 
488 * Using gnatdll:: 
490 GNAT and Windows Resources
492 * Building Resources:: 
493 * Compiling Resources:: 
494 * Using Resources:: 
496 Debugging a DLL
498 * Program and DLL Both Built with GCC/GNAT:: 
499 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
501 Windows Specific Add-Ons
503 * Win32Ada:: 
504 * wPOSIX:: 
506 Mac OS Topics
508 * Codesigning the Debugger:: 
510 Elaboration Order Handling in GNAT
512 * Elaboration Code:: 
513 * Elaboration Order:: 
514 * Checking the Elaboration Order:: 
515 * Controlling the Elaboration Order in Ada:: 
516 * Controlling the Elaboration Order in GNAT:: 
517 * Mixing Elaboration Models:: 
518 * ABE Diagnostics:: 
519 * SPARK Diagnostics:: 
520 * Elaboration Circularities:: 
521 * Resolving Elaboration Circularities:: 
522 * Elaboration-related Compiler Switches:: 
523 * Summary of Procedures for Elaboration Control:: 
524 * Inspecting the Chosen Elaboration Order:: 
526 Inline Assembler
528 * Basic Assembler Syntax:: 
529 * A Simple Example of Inline Assembler:: 
530 * Output Variables in Inline Assembler:: 
531 * Input Variables in Inline Assembler:: 
532 * Inlining Inline Assembler Code:: 
533 * Other Asm Functionality:: 
535 Other Asm Functionality
537 * The Clobber Parameter:: 
538 * The Volatile Parameter:: 
540 @end detailmenu
541 @end menu
543 @node About This Guide,Getting Started with GNAT,Top,Top
544 @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}
545 @chapter About This Guide
549 This guide describes the use of GNAT,
550 a compiler and software development
551 toolset for the full Ada programming language.
552 It documents the features of the compiler and tools, and explains
553 how to use them to build Ada applications.
555 GNAT implements Ada 95, Ada 2005, Ada 2012, and Ada 202x, and it may also be
556 invoked in Ada 83 compatibility mode.
557 By default, GNAT assumes Ada 2012, but you can override with a
558 compiler switch (@ref{6,,Compiling Different Versions of Ada})
559 to explicitly specify the language version.
560 Throughout this manual, references to ‘Ada’ without a year suffix
561 apply to all Ada versions of the language, starting with Ada 95.
563 @menu
564 * What This Guide Contains:: 
565 * What You Should Know before Reading This Guide:: 
566 * Related Information:: 
567 * Conventions:: 
569 @end menu
571 @node What This Guide Contains,What You Should Know before Reading This Guide,,About This Guide
572 @anchor{gnat_ugn/about_this_guide what-this-guide-contains}@anchor{7}
573 @section What This Guide Contains
576 This guide contains the following chapters:
579 @itemize *
581 @item 
582 @ref{8,,Getting Started with GNAT} describes how to get started compiling
583 and running Ada programs with the GNAT Ada programming environment.
585 @item 
586 @ref{9,,The GNAT Compilation Model} describes the compilation model used
587 by GNAT.
589 @item 
590 @ref{a,,Building Executable Programs with GNAT} describes how to use the
591 main GNAT tools to build executable programs, and it also gives examples of
592 using the GNU make utility with GNAT.
594 @item 
595 @ref{b,,GNAT Utility Programs} explains the various utility programs that
596 are included in the GNAT environment.
598 @item 
599 @ref{c,,GNAT and Program Execution} covers a number of topics related to
600 running, debugging, and tuning the performance of programs developed
601 with GNAT.
602 @end itemize
604 Appendices cover several additional topics:
607 @itemize *
609 @item 
610 @ref{d,,Platform-Specific Information} describes the different run-time
611 library implementations and also presents information on how to use
612 GNAT on several specific platforms.
614 @item 
615 @ref{e,,Example of Binder Output File} shows the source code for the binder
616 output file for a sample program.
618 @item 
619 @ref{f,,Elaboration Order Handling in GNAT} describes how GNAT helps
620 you deal with elaboration order issues.
622 @item 
623 @ref{10,,Inline Assembler} shows how to use the inline assembly facility
624 in an Ada program.
625 @end itemize
627 @node What You Should Know before Reading This Guide,Related Information,What This Guide Contains,About This Guide
628 @anchor{gnat_ugn/about_this_guide what-you-should-know-before-reading-this-guide}@anchor{11}
629 @section What You Should Know before Reading This Guide
632 @geindex Ada 95 Language Reference Manual
634 @geindex Ada 2005 Language Reference Manual
636 This guide assumes a basic familiarity with the Ada 95 language, as
637 described in the International Standard ANSI/ISO/IEC-8652:1995, January
638 1995.
639 Reference manuals for Ada 95, Ada 2005, and Ada 2012 are included in
640 the GNAT documentation package.
642 @node Related Information,Conventions,What You Should Know before Reading This Guide,About This Guide
643 @anchor{gnat_ugn/about_this_guide related-information}@anchor{12}
644 @section Related Information
647 For further information about Ada and related tools, please refer to the
648 following documents:
651 @itemize *
653 @item 
654 @cite{Ada 95 Reference Manual}, @cite{Ada 2005 Reference Manual}, and
655 @cite{Ada 2012 Reference Manual}, which contain reference
656 material for the several revisions of the Ada language standard.
658 @item 
659 @cite{GNAT Reference_Manual}, which contains all reference material for the GNAT
660 implementation of Ada.
662 @item 
663 @cite{Using GNAT Studio}, which describes the GNAT Studio
664 Integrated Development Environment.
666 @item 
667 @cite{GNAT Studio Tutorial}, which introduces the
668 main GNAT Studio features through examples.
670 @item 
671 @cite{Debugging with GDB},
672 for all details on the use of the GNU source-level debugger.
674 @item 
675 @cite{GNU Emacs Manual},
676 for full information on the extensible editor and programming
677 environment Emacs.
678 @end itemize
680 @node Conventions,,Related Information,About This Guide
681 @anchor{gnat_ugn/about_this_guide conventions}@anchor{13}
682 @section Conventions
685 @geindex Conventions
686 @geindex typographical
688 @geindex Typographical conventions
690 Following are examples of the typographical and graphic conventions used
691 in this guide:
694 @itemize *
696 @item 
697 @code{Functions}, @code{utility program names}, @code{standard names},
698 and @code{classes}.
700 @item 
701 @code{Option flags}
703 @item 
704 @code{File names}
706 @item 
707 @code{Variables}
709 @item 
710 @emph{Emphasis}
712 @item 
713 [optional information or parameters]
715 @item 
716 Examples are described by text
718 @example
719 and then shown this way.
720 @end example
722 @item 
723 Commands that are entered by the user are shown as preceded by a prompt string
724 comprising the @code{$} character followed by a space.
726 @item 
727 Full file names are shown with the ‘/’ character
728 as the directory separator; e.g., @code{parent-dir/subdir/myfile.adb}.
729 If you are using GNAT on a Windows platform, please note that
730 the ‘\’ character should be used instead.
731 @end itemize
733 @node Getting Started with GNAT,The GNAT Compilation Model,About This Guide,Top
734 @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}
735 @chapter Getting Started with GNAT
738 This chapter describes how to use GNAT’s command line interface to build
739 executable Ada programs.
740 On most platforms a visually oriented Integrated Development Environment
741 is also available: GNAT Studio.
742 GNAT Studio offers a graphical “look and feel”, support for development in
743 other programming languages, comprehensive browsing features, and
744 many other capabilities.
745 For information on GNAT Studio please refer to the
746 @cite{GNAT Studio documentation}.
748 @menu
749 * System Requirements:: 
750 * Running GNAT:: 
751 * Running a Simple Ada Program:: 
752 * Running a Program with Multiple Units:: 
754 @end menu
756 @node System Requirements,Running GNAT,,Getting Started with GNAT
757 @anchor{gnat_ugn/getting_started_with_gnat id2}@anchor{16}@anchor{gnat_ugn/getting_started_with_gnat system-requirements}@anchor{17}
758 @section System Requirements
761 Even though any machine can run the GNAT toolset and GNAT Studio IDE, in order
762 to get the best experience, we recommend using a machine with as many cores
763 as possible since all individual compilations can run in parallel.
764 A comfortable setup for a compiler server is a machine with 24 physical cores
765 or more, with at least 48 GB of memory (2 GB per core).
767 For a desktop machine, a minimum of 4 cores is recommended (8 preferred),
768 with at least 2GB per core (so 8 to 16GB).
770 In addition, for running and navigating sources in GNAT Studio smoothly, we
771 recommend at least 1.5 GB plus 3 GB of RAM per 1 million source line of code.
772 In other words, we recommend at least 3 GB for for 500K lines of code and
773 7.5 GB for 2 million lines of code.
775 Note that using local and fast drives will also make a difference in terms of
776 build and link time. Network drives such as NFS, SMB, or worse, configuration
777 management filesystems (such as ClearCase dynamic views) should be avoided as
778 much as possible and will produce very degraded performance (typically 2 to 3
779 times slower than on local fast drives). If such slow drives cannot be avoided
780 for accessing the source code, then you should at least configure your project
781 file so that the result of the compilation is stored on a drive local to the
782 machine performing the run. This can be achieved by setting the @code{Object_Dir}
783 project file attribute.
785 @node Running GNAT,Running a Simple Ada Program,System Requirements,Getting Started with GNAT
786 @anchor{gnat_ugn/getting_started_with_gnat id3}@anchor{18}@anchor{gnat_ugn/getting_started_with_gnat running-gnat}@anchor{19}
787 @section Running GNAT
790 Three steps are needed to create an executable file from an Ada source
791 file:
794 @itemize *
796 @item 
797 The source file(s) must be compiled.
799 @item 
800 The file(s) must be bound using the GNAT binder.
802 @item 
803 All appropriate object files must be linked to produce an executable.
804 @end itemize
806 All three steps are most commonly handled by using the @code{gnatmake}
807 utility program that, given the name of the main program, automatically
808 performs the necessary compilation, binding and linking steps.
810 @node Running a Simple Ada Program,Running a Program with Multiple Units,Running GNAT,Getting Started with GNAT
811 @anchor{gnat_ugn/getting_started_with_gnat id4}@anchor{1a}@anchor{gnat_ugn/getting_started_with_gnat running-a-simple-ada-program}@anchor{1b}
812 @section Running a Simple Ada Program
815 Any text editor may be used to prepare an Ada program.
816 (If Emacs is used, the optional Ada mode may be helpful in laying out the
817 program.)
818 The program text is a normal text file. We will assume in our initial
819 example that you have used your editor to prepare the following
820 standard format text file:
822 @example
823 with Ada.Text_IO; use Ada.Text_IO;
824 procedure Hello is
825 begin
826    Put_Line ("Hello WORLD!");
827 end Hello;
828 @end example
830 This file should be named @code{hello.adb}.
831 With the normal default file naming conventions, GNAT requires
832 that each file
833 contain a single compilation unit whose file name is the
834 unit name,
835 with periods replaced by hyphens; the
836 extension is @code{ads} for a
837 spec and @code{adb} for a body.
838 You can override this default file naming convention by use of the
839 special pragma @code{Source_File_Name} (for further information please
840 see @ref{1c,,Using Other File Names}).
841 Alternatively, if you want to rename your files according to this default
842 convention, which is probably more convenient if you will be using GNAT
843 for all your compilations, then the @code{gnatchop} utility
844 can be used to generate correctly-named source files
845 (see @ref{1d,,Renaming Files with gnatchop}).
847 You can compile the program using the following command (@code{$} is used
848 as the command prompt in the examples in this document):
850 @example
851 $ gcc -c hello.adb
852 @end example
854 @code{gcc} is the command used to run the compiler. This compiler is
855 capable of compiling programs in several languages, including Ada and
856 C. It assumes that you have given it an Ada program if the file extension is
857 either @code{.ads} or @code{.adb}, and it will then call
858 the GNAT compiler to compile the specified file.
860 The @code{-c} switch is required. It tells @code{gcc} to only do a
861 compilation. (For C programs, @code{gcc} can also do linking, but this
862 capability is not used directly for Ada programs, so the @code{-c}
863 switch must always be present.)
865 This compile command generates a file
866 @code{hello.o}, which is the object
867 file corresponding to your Ada program. It also generates
868 an ‘Ada Library Information’ file @code{hello.ali},
869 which contains additional information used to check
870 that an Ada program is consistent.
872 To build an executable file, use either @code{gnatmake} or gprbuild with
873 the name of the main file: these tools are builders that will take care of
874 all the necessary build steps in the correct order.
875 In particular, these builders automatically recompile any sources that have
876 been modified since they were last compiled, or sources that depend
877 on such modified sources, so that ‘version skew’ is avoided.
879 @geindex Version skew (avoided by `@w{`}gnatmake`@w{`})
881 @example
882 $ gnatmake hello.adb
883 @end example
885 The result is an executable program called @code{hello}, which can be
886 run by entering:
888 @example
889 $ hello
890 @end example
892 assuming that the current directory is on the search path
893 for executable programs.
895 and, if all has gone well, you will see:
897 @example
898 Hello WORLD!
899 @end example
901 appear in response to this command.
903 @node Running a Program with Multiple Units,,Running a Simple Ada Program,Getting Started with GNAT
904 @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}
905 @section Running a Program with Multiple Units
908 Consider a slightly more complicated example that has three files: a
909 main program, and the spec and body of a package:
911 @example
912 package Greetings is
913    procedure Hello;
914    procedure Goodbye;
915 end Greetings;
917 with Ada.Text_IO; use Ada.Text_IO;
918 package body Greetings is
919    procedure Hello is
920    begin
921       Put_Line ("Hello WORLD!");
922    end Hello;
924    procedure Goodbye is
925    begin
926       Put_Line ("Goodbye WORLD!");
927    end Goodbye;
928 end Greetings;
930 with Greetings;
931 procedure Gmain is
932 begin
933    Greetings.Hello;
934    Greetings.Goodbye;
935 end Gmain;
936 @end example
938 Following the one-unit-per-file rule, place this program in the
939 following three separate files:
942 @table @asis
944 @item @emph{greetings.ads}
946 spec of package @code{Greetings}
948 @item @emph{greetings.adb}
950 body of package @code{Greetings}
952 @item @emph{gmain.adb}
954 body of main program
955 @end table
957 Note that there is no required order of compilation when using GNAT.
958 In particular it is perfectly fine to compile the main program first.
959 Also, it is not necessary to compile package specs in the case where
960 there is an accompanying body; you only need to compile the body. If you want
961 to submit these files to the compiler for semantic checking and not code
962 generation, then use the @code{-gnatc} switch:
964 @example
965 $ gcc -c greetings.ads -gnatc
966 @end example
968 Although the compilation can be done in separate steps, in practice it is
969 almost always more convenient to use the @code{gnatmake} or @code{gprbuild} tools:
971 @example
972 $ gnatmake gmain.adb
973 @end example
975 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
977 @node The GNAT Compilation Model,Building Executable Programs with GNAT,Getting Started with GNAT,Top
978 @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}
979 @chapter The GNAT Compilation Model
982 @geindex GNAT compilation model
984 @geindex Compilation model
986 This chapter describes the compilation model used by GNAT. Although
987 similar to that used by other languages such as C and C++, this model
988 is substantially different from the traditional Ada compilation models,
989 which are based on a centralized program library. The chapter covers
990 the following material:
993 @itemize *
995 @item 
996 Topics related to source file makeup and naming
999 @itemize *
1001 @item 
1002 @ref{22,,Source Representation}
1004 @item 
1005 @ref{23,,Foreign Language Representation}
1007 @item 
1008 @ref{24,,File Naming Topics and Utilities}
1009 @end itemize
1011 @item 
1012 @ref{25,,Configuration Pragmas}
1014 @item 
1015 @ref{26,,Generating Object Files}
1017 @item 
1018 @ref{27,,Source Dependencies}
1020 @item 
1021 @ref{28,,The Ada Library Information Files}
1023 @item 
1024 @ref{29,,Binding an Ada Program}
1026 @item 
1027 @ref{2a,,GNAT and Libraries}
1029 @item 
1030 @ref{2b,,Conditional Compilation}
1032 @item 
1033 @ref{2c,,Mixed Language Programming}
1035 @item 
1036 @ref{2d,,GNAT and Other Compilation Models}
1038 @item 
1039 @ref{2e,,Using GNAT Files with External Tools}
1040 @end itemize
1042 @menu
1043 * Source Representation:: 
1044 * Foreign Language Representation:: 
1045 * File Naming Topics and Utilities:: 
1046 * Configuration Pragmas:: 
1047 * Generating Object Files:: 
1048 * Source Dependencies:: 
1049 * The Ada Library Information Files:: 
1050 * Binding an Ada Program:: 
1051 * GNAT and Libraries:: 
1052 * Conditional Compilation:: 
1053 * Mixed Language Programming:: 
1054 * GNAT and Other Compilation Models:: 
1055 * Using GNAT Files with External Tools:: 
1057 @end menu
1059 @node Source Representation,Foreign Language Representation,,The GNAT Compilation Model
1060 @anchor{gnat_ugn/the_gnat_compilation_model id2}@anchor{2f}@anchor{gnat_ugn/the_gnat_compilation_model source-representation}@anchor{22}
1061 @section Source Representation
1064 @geindex Latin-1
1066 @geindex VT
1067 @geindex HT
1068 @geindex CR
1069 @geindex LF
1070 @geindex FF
1072 Ada source programs are represented in standard text files, using
1073 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1074 7-bit ASCII set, plus additional characters used for
1075 representing foreign languages (see @ref{23,,Foreign Language Representation}
1076 for support of non-USA character sets). The format effector characters
1077 are represented using their standard ASCII encodings, as follows:
1079 @quotation
1082 @multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxx} 
1083 @item
1085 Character
1087 @tab
1089 Effect
1091 @tab
1093 Code
1095 @item
1097 @code{VT}
1099 @tab
1101 Vertical tab
1103 @tab
1105 @code{16#0B#}
1107 @item
1109 @code{HT}
1111 @tab
1113 Horizontal tab
1115 @tab
1117 @code{16#09#}
1119 @item
1121 @code{CR}
1123 @tab
1125 Carriage return
1127 @tab
1129 @code{16#0D#}
1131 @item
1133 @code{LF}
1135 @tab
1137 Line feed
1139 @tab
1141 @code{16#0A#}
1143 @item
1145 @code{FF}
1147 @tab
1149 Form feed
1151 @tab
1153 @code{16#0C#}
1155 @end multitable
1157 @end quotation
1159 Source files are in standard text file format. In addition, GNAT will
1160 recognize a wide variety of stream formats, in which the end of
1161 physical lines is marked by any of the following sequences:
1162 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1163 in accommodating files that are imported from other operating systems.
1165 @geindex End of source file; Source file@comma{} end
1167 @geindex SUB (control character)
1169 The end of a source file is normally represented by the physical end of
1170 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1171 recognized as signalling the end of the source file. Again, this is
1172 provided for compatibility with other operating systems where this
1173 code is used to represent the end of file.
1175 @geindex spec (definition)
1176 @geindex compilation (definition)
1178 Each file contains a single Ada compilation unit, including any pragmas
1179 associated with the unit. For example, this means you must place a
1180 package declaration (a package @emph{spec}) and the corresponding body in
1181 separate files. An Ada @emph{compilation} (which is a sequence of
1182 compilation units) is represented using a sequence of files. Similarly,
1183 you will place each subunit or child unit in a separate file.
1185 @node Foreign Language Representation,File Naming Topics and Utilities,Source Representation,The GNAT Compilation Model
1186 @anchor{gnat_ugn/the_gnat_compilation_model foreign-language-representation}@anchor{23}@anchor{gnat_ugn/the_gnat_compilation_model id3}@anchor{30}
1187 @section Foreign Language Representation
1190 GNAT supports the standard character sets defined in Ada as well as
1191 several other non-standard character sets for use in localized versions
1192 of the compiler (@ref{31,,Character Set Control}).
1194 @menu
1195 * Latin-1:: 
1196 * Other 8-Bit Codes:: 
1197 * Wide_Character Encodings:: 
1198 * Wide_Wide_Character Encodings:: 
1200 @end menu
1202 @node Latin-1,Other 8-Bit Codes,,Foreign Language Representation
1203 @anchor{gnat_ugn/the_gnat_compilation_model id4}@anchor{32}@anchor{gnat_ugn/the_gnat_compilation_model latin-1}@anchor{33}
1204 @subsection Latin-1
1207 @geindex Latin-1
1209 The basic character set is Latin-1. This character set is defined by ISO
1210 standard 8859, part 1. The lower half (character codes @code{16#00#}
1211 … @code{16#7F#)} is identical to standard ASCII coding, but the upper
1212 half is used to represent additional characters. These include extended letters
1213 used by European languages, such as French accents, the vowels with umlauts
1214 used in German, and the extra letter A-ring used in Swedish.
1216 @geindex Ada.Characters.Latin_1
1218 For a complete list of Latin-1 codes and their encodings, see the source
1219 file of library unit @code{Ada.Characters.Latin_1} in file
1220 @code{a-chlat1.ads}.
1221 You may use any of these extended characters freely in character or
1222 string literals. In addition, the extended characters that represent
1223 letters can be used in identifiers.
1225 @node Other 8-Bit Codes,Wide_Character Encodings,Latin-1,Foreign Language Representation
1226 @anchor{gnat_ugn/the_gnat_compilation_model id5}@anchor{34}@anchor{gnat_ugn/the_gnat_compilation_model other-8-bit-codes}@anchor{35}
1227 @subsection Other 8-Bit Codes
1230 GNAT also supports several other 8-bit coding schemes:
1232 @geindex Latin-2
1234 @geindex ISO 8859-2
1237 @table @asis
1239 @item @emph{ISO 8859-2 (Latin-2)}
1241 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1242 equivalence.
1243 @end table
1245 @geindex Latin-3
1247 @geindex ISO 8859-3
1250 @table @asis
1252 @item @emph{ISO 8859-3 (Latin-3)}
1254 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1255 equivalence.
1256 @end table
1258 @geindex Latin-4
1260 @geindex ISO 8859-4
1263 @table @asis
1265 @item @emph{ISO 8859-4 (Latin-4)}
1267 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1268 equivalence.
1269 @end table
1271 @geindex ISO 8859-5
1273 @geindex Cyrillic
1276 @table @asis
1278 @item @emph{ISO 8859-5 (Cyrillic)}
1280 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1281 lowercase equivalence.
1282 @end table
1284 @geindex ISO 8859-15
1286 @geindex Latin-9
1289 @table @asis
1291 @item @emph{ISO 8859-15 (Latin-9)}
1293 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1294 lowercase equivalence.
1295 @end table
1297 @geindex code page 437 (IBM PC)
1300 @table @asis
1302 @item @emph{IBM PC (code page 437)}
1304 This code page is the normal default for PCs in the U.S. It corresponds
1305 to the original IBM PC character set. This set has some, but not all, of
1306 the extended Latin-1 letters, but these letters do not have the same
1307 encoding as Latin-1. In this mode, these letters are allowed in
1308 identifiers with uppercase and lowercase equivalence.
1309 @end table
1311 @geindex code page 850 (IBM PC)
1314 @table @asis
1316 @item @emph{IBM PC (code page 850)}
1318 This code page is a modification of 437 extended to include all the
1319 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1320 mode, all these letters are allowed in identifiers with uppercase and
1321 lowercase equivalence.
1323 @item @emph{Full Upper 8-bit}
1325 Any character in the range 80-FF allowed in identifiers, and all are
1326 considered distinct. In other words, there are no uppercase and lowercase
1327 equivalences in this range. This is useful in conjunction with
1328 certain encoding schemes used for some foreign character sets (e.g.,
1329 the typical method of representing Chinese characters on the PC).
1331 @item @emph{No Upper-Half}
1333 No upper-half characters in the range 80-FF are allowed in identifiers.
1334 This gives Ada 83 compatibility for identifier names.
1335 @end table
1337 For precise data on the encodings permitted, and the uppercase and lowercase
1338 equivalences that are recognized, see the file @code{csets.adb} in
1339 the GNAT compiler sources. You will need to obtain a full source release
1340 of GNAT to obtain this file.
1342 @node Wide_Character Encodings,Wide_Wide_Character Encodings,Other 8-Bit Codes,Foreign Language Representation
1343 @anchor{gnat_ugn/the_gnat_compilation_model id6}@anchor{36}@anchor{gnat_ugn/the_gnat_compilation_model wide-character-encodings}@anchor{37}
1344 @subsection Wide_Character Encodings
1347 GNAT allows wide character codes to appear in character and string
1348 literals, and also optionally in identifiers, by means of the following
1349 possible encoding schemes:
1352 @table @asis
1354 @item @emph{Hex Coding}
1356 In this encoding, a wide character is represented by the following five
1357 character sequence:
1359 @example
1360 ESC a b c d
1361 @end example
1363 where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1364 characters (using uppercase letters) of the wide character code. For
1365 example, ESC A345 is used to represent the wide character with code
1366 @code{16#A345#}.
1367 This scheme is compatible with use of the full Wide_Character set.
1368 @end table
1370 @geindex Upper-Half Coding
1373 @table @asis
1375 @item @emph{Upper-Half Coding}
1377 The wide character with encoding @code{16#abcd#} where the upper bit is on
1378 (in other words, ‘a’ is in the range 8-F) is represented as two bytes,
1379 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1380 character, but is not required to be in the upper half. This method can
1381 be also used for shift-JIS or EUC, where the internal coding matches the
1382 external coding.
1383 @end table
1385 @geindex Shift JIS Coding
1388 @table @asis
1390 @item @emph{Shift JIS Coding}
1392 A wide character is represented by a two-character sequence,
1393 @code{16#ab#} and
1394 @code{16#cd#}, with the restrictions described for upper-half encoding as
1395 described above. The internal character code is the corresponding JIS
1396 character according to the standard algorithm for Shift-JIS
1397 conversion. Only characters defined in the JIS code set table can be
1398 used with this encoding method.
1399 @end table
1401 @geindex EUC Coding
1404 @table @asis
1406 @item @emph{EUC Coding}
1408 A wide character is represented by a two-character sequence
1409 @code{16#ab#} and
1410 @code{16#cd#}, with both characters being in the upper half. The internal
1411 character code is the corresponding JIS character according to the EUC
1412 encoding algorithm. Only characters defined in the JIS code set table
1413 can be used with this encoding method.
1415 @item @emph{UTF-8 Coding}
1417 A wide character is represented using
1418 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1419 10646-1/Am.2. Depending on the character value, the representation
1420 is a one, two, or three byte sequence:
1422 @example
1423 16#0000#-16#007f#: 2#0xxxxxxx#
1424 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1425 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1426 @end example
1428 where the @code{xxx} bits correspond to the left-padded bits of the
1429 16-bit character value. Note that all lower half ASCII characters
1430 are represented as ASCII bytes and all upper half characters and
1431 other wide characters are represented as sequences of upper-half
1432 (The full UTF-8 scheme allows for encoding 31-bit characters as
1433 6-byte sequences, and in the following section on wide wide
1434 characters, the use of these sequences is documented).
1436 @item @emph{Brackets Coding}
1438 In this encoding, a wide character is represented by the following eight
1439 character sequence:
1441 @example
1442 [ " a b c d " ]
1443 @end example
1445 where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1446 characters (using uppercase letters) of the wide character code. For
1447 example, [‘A345’] is used to represent the wide character with code
1448 @code{16#A345#}. It is also possible (though not required) to use the
1449 Brackets coding for upper half characters. For example, the code
1450 @code{16#A3#} can be represented as @code{['A3']}.
1452 This scheme is compatible with use of the full Wide_Character set,
1453 and is also the method used for wide character encoding in some standard
1454 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1455 @end table
1457 @cartouche
1458 @quotation Note 
1459 Some of these coding schemes do not permit the full use of the
1460 Ada character set. For example, neither Shift JIS nor EUC allow the
1461 use of the upper half of the Latin-1 set.
1462 @end quotation
1463 @end cartouche
1465 @node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1466 @anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{38}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{39}
1467 @subsection Wide_Wide_Character Encodings
1470 GNAT allows wide wide character codes to appear in character and string
1471 literals, and also optionally in identifiers, by means of the following
1472 possible encoding schemes:
1475 @table @asis
1477 @item @emph{UTF-8 Coding}
1479 A wide character is represented using
1480 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1481 10646-1/Am.2. Depending on the character value, the representation
1482 of character codes with values greater than 16#FFFF# is a
1483 is a four, five, or six byte sequence:
1485 @example
1486 16#01_0000#-16#10_FFFF#:     11110xxx 10xxxxxx 10xxxxxx
1487                              10xxxxxx
1488 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1489                              10xxxxxx 10xxxxxx
1490 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1491                              10xxxxxx 10xxxxxx 10xxxxxx
1492 @end example
1494 where the @code{xxx} bits correspond to the left-padded bits of the
1495 32-bit character value.
1497 @item @emph{Brackets Coding}
1499 In this encoding, a wide wide character is represented by the following ten or
1500 twelve byte character sequence:
1502 @example
1503 [ " a b c d e f " ]
1504 [ " a b c d e f g h " ]
1505 @end example
1507 where @code{a-h} are the six or eight hexadecimal
1508 characters (using uppercase letters) of the wide wide character code. For
1509 example, [“1F4567”] is used to represent the wide wide character with code
1510 @code{16#001F_4567#}.
1512 This scheme is compatible with use of the full Wide_Wide_Character set,
1513 and is also the method used for wide wide character encoding in some standard
1514 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1515 @end table
1517 @node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1518 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{24}@anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{3a}
1519 @section File Naming Topics and Utilities
1522 GNAT has a default file naming scheme and also provides the user with
1523 a high degree of control over how the names and extensions of the
1524 source files correspond to the Ada compilation units that they contain.
1526 @menu
1527 * File Naming Rules:: 
1528 * Using Other File Names:: 
1529 * Alternative File Naming Schemes:: 
1530 * Handling Arbitrary File Naming Conventions with gnatname:: 
1531 * File Name Krunching with gnatkr:: 
1532 * Renaming Files with gnatchop:: 
1534 @end menu
1536 @node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1537 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{3b}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{3c}
1538 @subsection File Naming Rules
1541 The default file name is determined by the name of the unit that the
1542 file contains. The name is formed by taking the full expanded name of
1543 the unit and replacing the separating dots with hyphens and using
1544 lowercase for all letters.
1546 An exception arises if the file name generated by the above rules starts
1547 with one of the characters
1548 @code{a}, @code{g}, @code{i}, or @code{s}, and the second character is a
1549 minus. In this case, the character tilde is used in place
1550 of the minus. The reason for this special rule is to avoid clashes with
1551 the standard names for child units of the packages System, Ada,
1552 Interfaces, and GNAT, which use the prefixes
1553 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
1554 respectively.
1556 The file extension is @code{.ads} for a spec and
1557 @code{.adb} for a body. The following table shows some
1558 examples of these rules.
1560 @quotation
1563 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
1564 @item
1566 Source File
1568 @tab
1570 Ada Compilation Unit
1572 @item
1574 @code{main.ads}
1576 @tab
1578 Main (spec)
1580 @item
1582 @code{main.adb}
1584 @tab
1586 Main (body)
1588 @item
1590 @code{arith_functions.ads}
1592 @tab
1594 Arith_Functions (package spec)
1596 @item
1598 @code{arith_functions.adb}
1600 @tab
1602 Arith_Functions (package body)
1604 @item
1606 @code{func-spec.ads}
1608 @tab
1610 Func.Spec (child package spec)
1612 @item
1614 @code{func-spec.adb}
1616 @tab
1618 Func.Spec (child package body)
1620 @item
1622 @code{main-sub.adb}
1624 @tab
1626 Sub (subunit of Main)
1628 @item
1630 @code{a~bad.adb}
1632 @tab
1634 A.Bad (child package body)
1636 @end multitable
1638 @end quotation
1640 Following these rules can result in excessively long
1641 file names if corresponding
1642 unit names are long (for example, if child units or subunits are
1643 heavily nested). An option is available to shorten such long file names
1644 (called file name ‘krunching’). This may be particularly useful when
1645 programs being developed with GNAT are to be used on operating systems
1646 with limited file name lengths. @ref{3d,,Using gnatkr}.
1648 Of course, no file shortening algorithm can guarantee uniqueness over
1649 all possible unit names; if file name krunching is used, it is your
1650 responsibility to ensure no name clashes occur. Alternatively you
1651 can specify the exact file names that you want used, as described
1652 in the next section. Finally, if your Ada programs are migrating from a
1653 compiler with a different naming convention, you can use the gnatchop
1654 utility to produce source files that follow the GNAT naming conventions.
1655 (For details see @ref{1d,,Renaming Files with gnatchop}.)
1657 Note: in the case of Windows or Mac OS operating systems, case is not
1658 significant. So for example on Windows if the canonical name is
1659 @code{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1660 However, case is significant for other operating systems, so for example,
1661 if you want to use other than canonically cased file names on a Unix system,
1662 you need to follow the procedures described in the next section.
1664 @node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1665 @anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{3e}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{1c}
1666 @subsection Using Other File Names
1669 @geindex File names
1671 In the previous section, we have described the default rules used by
1672 GNAT to determine the file name in which a given unit resides. It is
1673 often convenient to follow these default rules, and if you follow them,
1674 the compiler knows without being explicitly told where to find all
1675 the files it needs.
1677 @geindex Source_File_Name pragma
1679 However, in some cases, particularly when a program is imported from
1680 another Ada compiler environment, it may be more convenient for the
1681 programmer to specify which file names contain which units. GNAT allows
1682 arbitrary file names to be used by means of the Source_File_Name pragma.
1683 The form of this pragma is as shown in the following examples:
1685 @example
1686 pragma Source_File_Name (My_Utilities.Stacks,
1687   Spec_File_Name => "myutilst_a.ada");
1688 pragma Source_File_name (My_Utilities.Stacks,
1689   Body_File_Name => "myutilst.ada");
1690 @end example
1692 As shown in this example, the first argument for the pragma is the unit
1693 name (in this example a child unit). The second argument has the form
1694 of a named association. The identifier
1695 indicates whether the file name is for a spec or a body;
1696 the file name itself is given by a string literal.
1698 The source file name pragma is a configuration pragma, which means that
1699 normally it will be placed in the @code{gnat.adc}
1700 file used to hold configuration
1701 pragmas that apply to a complete compilation environment.
1702 For more details on how the @code{gnat.adc} file is created and used
1703 see @ref{3f,,Handling of Configuration Pragmas}.
1705 @geindex gnat.adc
1707 GNAT allows completely arbitrary file names to be specified using the
1708 source file name pragma. However, if the file name specified has an
1709 extension other than @code{.ads} or @code{.adb} it is necessary to use
1710 a special syntax when compiling the file. The name in this case must be
1711 preceded by the special sequence @code{-x} followed by a space and the name
1712 of the language, here @code{ada}, as in:
1714 @example
1715 $ gcc -c -x ada peculiar_file_name.sim
1716 @end example
1718 @code{gnatmake} handles non-standard file names in the usual manner (the
1719 non-standard file name for the main program is simply used as the
1720 argument to gnatmake). Note that if the extension is also non-standard,
1721 then it must be included in the @code{gnatmake} command, it may not
1722 be omitted.
1724 @node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
1725 @anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{41}
1726 @subsection Alternative File Naming Schemes
1729 @geindex File naming schemes
1730 @geindex alternative
1732 @geindex File names
1734 The previous section described the use of the @code{Source_File_Name}
1735 pragma to allow arbitrary names to be assigned to individual source files.
1736 However, this approach requires one pragma for each file, and especially in
1737 large systems can result in very long @code{gnat.adc} files, and also create
1738 a maintenance problem.
1740 @geindex Source_File_Name pragma
1742 GNAT also provides a facility for specifying systematic file naming schemes
1743 other than the standard default naming scheme previously described. An
1744 alternative scheme for naming is specified by the use of
1745 @code{Source_File_Name} pragmas having the following format:
1747 @example
1748 pragma Source_File_Name (
1749    Spec_File_Name  => FILE_NAME_PATTERN
1750  [ , Casing          => CASING_SPEC]
1751  [ , Dot_Replacement => STRING_LITERAL ] );
1753 pragma Source_File_Name (
1754    Body_File_Name  => FILE_NAME_PATTERN
1755  [ , Casing          => CASING_SPEC ]
1756  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1758 pragma Source_File_Name (
1759    Subunit_File_Name  => FILE_NAME_PATTERN
1760  [ , Casing          => CASING_SPEC ]
1761  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1763 FILE_NAME_PATTERN ::= STRING_LITERAL
1764 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1765 @end example
1767 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1768 It contains a single asterisk character, and the unit name is substituted
1769 systematically for this asterisk. The optional parameter
1770 @code{Casing} indicates
1771 whether the unit name is to be all upper-case letters, all lower-case letters,
1772 or mixed-case. If no
1773 @code{Casing} parameter is used, then the default is all
1774 lower-case.
1776 The optional @code{Dot_Replacement} string is used to replace any periods
1777 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1778 argument is used then separating dots appear unchanged in the resulting
1779 file name.
1780 Although the above syntax indicates that the
1781 @code{Casing} argument must appear
1782 before the @code{Dot_Replacement} argument, but it
1783 is also permissible to write these arguments in the opposite order.
1785 As indicated, it is possible to specify different naming schemes for
1786 bodies, specs, and subunits. Quite often the rule for subunits is the
1787 same as the rule for bodies, in which case, there is no need to give
1788 a separate @code{Subunit_File_Name} rule, and in this case the
1789 @code{Body_File_name} rule is used for subunits as well.
1791 The separate rule for subunits can also be used to implement the rather
1792 unusual case of a compilation environment (e.g., a single directory) which
1793 contains a subunit and a child unit with the same unit name. Although
1794 both units cannot appear in the same partition, the Ada Reference Manual
1795 allows (but does not require) the possibility of the two units coexisting
1796 in the same environment.
1798 The file name translation works in the following steps:
1801 @itemize *
1803 @item 
1804 If there is a specific @code{Source_File_Name} pragma for the given unit,
1805 then this is always used, and any general pattern rules are ignored.
1807 @item 
1808 If there is a pattern type @code{Source_File_Name} pragma that applies to
1809 the unit, then the resulting file name will be used if the file exists. If
1810 more than one pattern matches, the latest one will be tried first, and the
1811 first attempt resulting in a reference to a file that exists will be used.
1813 @item 
1814 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1815 for which the corresponding file exists, then the standard GNAT default
1816 naming rules are used.
1817 @end itemize
1819 As an example of the use of this mechanism, consider a commonly used scheme
1820 in which file names are all lower case, with separating periods copied
1821 unchanged to the resulting file name, and specs end with @code{.1.ada}, and
1822 bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
1823 two pragmas appear:
1825 @example
1826 pragma Source_File_Name
1827   (Spec_File_Name => ".1.ada");
1828 pragma Source_File_Name
1829   (Body_File_Name => ".2.ada");
1830 @end example
1832 The default GNAT scheme is actually implemented by providing the following
1833 default pragmas internally:
1835 @example
1836 pragma Source_File_Name
1837   (Spec_File_Name => ".ads", Dot_Replacement => "-");
1838 pragma Source_File_Name
1839   (Body_File_Name => ".adb", Dot_Replacement => "-");
1840 @end example
1842 Our final example implements a scheme typically used with one of the
1843 Ada 83 compilers, where the separator character for subunits was ‘__’
1844 (two underscores), specs were identified by adding @code{_.ADA}, bodies
1845 by adding @code{.ADA}, and subunits by
1846 adding @code{.SEP}. All file names were
1847 upper case. Child units were not present of course since this was an
1848 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1849 the same double underscore separator for child units.
1851 @example
1852 pragma Source_File_Name
1853   (Spec_File_Name => "_.ADA",
1854    Dot_Replacement => "__",
1855    Casing = Uppercase);
1856 pragma Source_File_Name
1857   (Body_File_Name => ".ADA",
1858    Dot_Replacement => "__",
1859    Casing = Uppercase);
1860 pragma Source_File_Name
1861   (Subunit_File_Name => ".SEP",
1862    Dot_Replacement => "__",
1863    Casing = Uppercase);
1864 @end example
1866 @geindex gnatname
1868 @node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
1869 @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}
1870 @subsection Handling Arbitrary File Naming Conventions with @code{gnatname}
1873 @geindex File Naming Conventions
1875 @menu
1876 * Arbitrary File Naming Conventions:: 
1877 * Running gnatname:: 
1878 * Switches for gnatname:: 
1879 * Examples of gnatname Usage:: 
1881 @end menu
1883 @node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
1884 @anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{44}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{45}
1885 @subsubsection Arbitrary File Naming Conventions
1888 The GNAT compiler must be able to know the source file name of a compilation
1889 unit.  When using the standard GNAT default file naming conventions
1890 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
1891 does not need additional information.
1893 When the source file names do not follow the standard GNAT default file naming
1894 conventions, the GNAT compiler must be given additional information through
1895 a configuration pragmas file (@ref{25,,Configuration Pragmas})
1896 or a project file.
1897 When the non-standard file naming conventions are well-defined,
1898 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
1899 (@ref{40,,Alternative File Naming Schemes}) may be sufficient. However,
1900 if the file naming conventions are irregular or arbitrary, a number
1901 of pragma @code{Source_File_Name} for individual compilation units
1902 must be defined.
1903 To help maintain the correspondence between compilation unit names and
1904 source file names within the compiler,
1905 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
1906 set of files.
1908 @node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
1909 @anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{46}@anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{47}
1910 @subsubsection Running @code{gnatname}
1913 The usual form of the @code{gnatname} command is:
1915 @example
1916 $ gnatname [ switches ]  naming_pattern  [ naming_patterns ]
1917     [--and [ switches ]  naming_pattern  [ naming_patterns ]]
1918 @end example
1920 All of the arguments are optional. If invoked without any argument,
1921 @code{gnatname} will display its usage.
1923 When used with at least one naming pattern, @code{gnatname} will attempt to
1924 find all the compilation units in files that follow at least one of the
1925 naming patterns. To find these compilation units,
1926 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
1927 regular files.
1929 One or several Naming Patterns may be given as arguments to @code{gnatname}.
1930 Each Naming Pattern is enclosed between double quotes (or single
1931 quotes on Windows).
1932 A Naming Pattern is a regular expression similar to the wildcard patterns
1933 used in file names by the Unix shells or the DOS prompt.
1935 @code{gnatname} may be called with several sections of directories/patterns.
1936 Sections are separated by the switch @code{--and}. In each section, there must be
1937 at least one pattern. If no directory is specified in a section, the current
1938 directory (or the project directory if @code{-P} is used) is implied.
1939 The options other that the directory switches and the patterns apply globally
1940 even if they are in different sections.
1942 Examples of Naming Patterns are:
1944 @example
1945 "*.[12].ada"
1946 "*.ad[sb]*"
1947 "body_*"    "spec_*"
1948 @end example
1950 For a more complete description of the syntax of Naming Patterns,
1951 see the second kind of regular expressions described in @code{g-regexp.ads}
1952 (the ‘Glob’ regular expressions).
1954 When invoked without the switch @code{-P}, @code{gnatname} will create a
1955 configuration pragmas file @code{gnat.adc} in the current working directory,
1956 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
1957 unit.
1959 @node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
1960 @anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{48}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{49}
1961 @subsubsection Switches for @code{gnatname}
1964 Switches for @code{gnatname} must precede any specified Naming Pattern.
1966 You may specify any of the following switches to @code{gnatname}:
1968 @geindex --version (gnatname)
1971 @table @asis
1973 @item @code{--version}
1975 Display Copyright and version, then exit disregarding all other options.
1976 @end table
1978 @geindex --help (gnatname)
1981 @table @asis
1983 @item @code{--help}
1985 If @code{--version} was not used, display usage, then exit disregarding
1986 all other options.
1988 @item @code{--subdirs=@emph{dir}}
1990 Real object, library or exec directories are subdirectories <dir> of the
1991 specified ones.
1993 @item @code{--no-backup}
1995 Do not create a backup copy of an existing project file.
1997 @item @code{--and}
1999 Start another section of directories/patterns.
2000 @end table
2002 @geindex -c (gnatname)
2005 @table @asis
2007 @item @code{-c@emph{filename}}
2009 Create a configuration pragmas file @code{filename} (instead of the default
2010 @code{gnat.adc}).
2011 There may be zero, one or more space between @code{-c} and
2012 @code{filename}.
2013 @code{filename} may include directory information. @code{filename} must be
2014 writable. There may be only one switch @code{-c}.
2015 When a switch @code{-c} is
2016 specified, no switch @code{-P} may be specified (see below).
2017 @end table
2019 @geindex -d (gnatname)
2022 @table @asis
2024 @item @code{-d@emph{dir}}
2026 Look for source files in directory @code{dir}. There may be zero, one or more
2027 spaces between @code{-d} and @code{dir}.
2028 @code{dir} may end with @code{/**}, that is it may be of the form
2029 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
2030 subdirectories, recursively, have to be searched for sources.
2031 When a switch @code{-d}
2032 is specified, the current working directory will not be searched for source
2033 files, unless it is explicitly specified with a @code{-d}
2034 or @code{-D} switch.
2035 Several switches @code{-d} may be specified.
2036 If @code{dir} is a relative path, it is relative to the directory of
2037 the configuration pragmas file specified with switch
2038 @code{-c},
2039 or to the directory of the project file specified with switch
2040 @code{-P} or,
2041 if neither switch @code{-c}
2042 nor switch @code{-P} are specified, it is relative to the
2043 current working directory. The directory
2044 specified with switch @code{-d} must exist and be readable.
2045 @end table
2047 @geindex -D (gnatname)
2050 @table @asis
2052 @item @code{-D@emph{filename}}
2054 Look for source files in all directories listed in text file @code{filename}.
2055 There may be zero, one or more spaces between @code{-D}
2056 and @code{filename}.
2057 @code{filename} must be an existing, readable text file.
2058 Each nonempty line in @code{filename} must be a directory.
2059 Specifying switch @code{-D} is equivalent to specifying as many
2060 switches @code{-d} as there are nonempty lines in
2061 @code{file}.
2063 @item @code{-eL}
2065 Follow symbolic links when processing project files.
2067 @geindex -f (gnatname)
2069 @item @code{-f@emph{pattern}}
2071 Foreign patterns. Using this switch, it is possible to add sources of languages
2072 other than Ada to the list of sources of a project file.
2073 It is only useful if a -P switch is used.
2074 For example,
2076 @example
2077 gnatname -Pprj -f"*.c" "*.ada"
2078 @end example
2080 will look for Ada units in all files with the @code{.ada} extension,
2081 and will add to the list of file for project @code{prj.gpr} the C files
2082 with extension @code{.c}.
2084 @geindex -h (gnatname)
2086 @item @code{-h}
2088 Output usage (help) information. The output is written to @code{stdout}.
2090 @geindex -P (gnatname)
2092 @item @code{-P@emph{proj}}
2094 Create or update project file @code{proj}. There may be zero, one or more space
2095 between @code{-P} and @code{proj}. @code{proj} may include directory
2096 information. @code{proj} must be writable.
2097 There may be only one switch @code{-P}.
2098 When a switch @code{-P} is specified,
2099 no switch @code{-c} may be specified.
2100 On all platforms, except on VMS, when @code{gnatname} is invoked for an
2101 existing project file <proj>.gpr, a backup copy of the project file is created
2102 in the project directory with file name <proj>.gpr.saved_x. ‘x’ is the first
2103 non negative number that makes this backup copy a new file.
2105 @geindex -v (gnatname)
2107 @item @code{-v}
2109 Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2110 This includes name of the file written, the name of the directories to search
2111 and, for each file in those directories whose name matches at least one of
2112 the Naming Patterns, an indication of whether the file contains a unit,
2113 and if so the name of the unit.
2114 @end table
2116 @geindex -v -v (gnatname)
2119 @table @asis
2121 @item @code{-v -v}
2123 Very Verbose mode. In addition to the output produced in verbose mode,
2124 for each file in the searched directories whose name matches none of
2125 the Naming Patterns, an indication is given that there is no match.
2127 @geindex -x (gnatname)
2129 @item @code{-x@emph{pattern}}
2131 Excluded patterns. Using this switch, it is possible to exclude some files
2132 that would match the name patterns. For example,
2134 @example
2135 gnatname -x "*_nt.ada" "*.ada"
2136 @end example
2138 will look for Ada units in all files with the @code{.ada} extension,
2139 except those whose names end with @code{_nt.ada}.
2140 @end table
2142 @node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2143 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{4a}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{4b}
2144 @subsubsection Examples of @code{gnatname} Usage
2147 @example
2148 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2149 @end example
2151 In this example, the directory @code{/home/me} must already exist
2152 and be writable. In addition, the directory
2153 @code{/home/me/sources} (specified by
2154 @code{-d sources}) must exist and be readable.
2156 Note the optional spaces after @code{-c} and @code{-d}.
2158 @example
2159 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
2160 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2161 @end example
2163 Note that several switches @code{-d} may be used,
2164 even in conjunction with one or several switches
2165 @code{-D}. Several Naming Patterns and one excluded pattern
2166 are used in this example.
2168 @node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2169 @anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{4c}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{4d}
2170 @subsection File Name Krunching with @code{gnatkr}
2173 @geindex gnatkr
2175 This section discusses the method used by the compiler to shorten
2176 the default file names chosen for Ada units so that they do not
2177 exceed the maximum length permitted. It also describes the
2178 @code{gnatkr} utility that can be used to determine the result of
2179 applying this shortening.
2181 @menu
2182 * About gnatkr:: 
2183 * Using gnatkr:: 
2184 * Krunching Method:: 
2185 * Examples of gnatkr Usage:: 
2187 @end menu
2189 @node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2190 @anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{4e}@anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{4f}
2191 @subsubsection About @code{gnatkr}
2194 The default file naming rule in GNAT
2195 is that the file name must be derived from
2196 the unit name. The exact default rule is as follows:
2199 @itemize *
2201 @item 
2202 Take the unit name and replace all dots by hyphens.
2204 @item 
2205 If such a replacement occurs in the
2206 second character position of a name, and the first character is
2207 @code{a}, @code{g}, @code{s}, or @code{i},
2208 then replace the dot by the character
2209 @code{~} (tilde)
2210 instead of a minus.
2212 The reason for this exception is to avoid clashes
2213 with the standard names for children of System, Ada, Interfaces,
2214 and GNAT, which use the prefixes
2215 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
2216 respectively.
2217 @end itemize
2219 The @code{-gnatk@emph{nn}}
2220 switch of the compiler activates a ‘krunching’
2221 circuit that limits file names to nn characters (where nn is a decimal
2222 integer).
2224 The @code{gnatkr} utility can be used to determine the krunched name for
2225 a given file, when krunched to a specified maximum length.
2227 @node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2228 @anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{50}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{3d}
2229 @subsubsection Using @code{gnatkr}
2232 The @code{gnatkr} command has the form:
2234 @example
2235 $ gnatkr name [ length ]
2236 @end example
2238 @code{name} is the uncrunched file name, derived from the name of the unit
2239 in the standard manner described in the previous section (i.e., in particular
2240 all dots are replaced by hyphens). The file name may or may not have an
2241 extension (defined as a suffix of the form period followed by arbitrary
2242 characters other than period). If an extension is present then it will
2243 be preserved in the output. For example, when krunching @code{hellofile.ads}
2244 to eight characters, the result will be hellofil.ads.
2246 Note: for compatibility with previous versions of @code{gnatkr} dots may
2247 appear in the name instead of hyphens, but the last dot will always be
2248 taken as the start of an extension. So if @code{gnatkr} is given an argument
2249 such as @code{Hello.World.adb} it will be treated exactly as if the first
2250 period had been a hyphen, and for example krunching to eight characters
2251 gives the result @code{hellworl.adb}.
2253 Note that the result is always all lower case.
2254 Characters of the other case are folded as required.
2256 @code{length} represents the length of the krunched name. The default
2257 when no argument is given is 8 characters. A length of zero stands for
2258 unlimited, in other words do not chop except for system files where the
2259 implied crunching length is always eight characters.
2261 The output is the krunched name. The output has an extension only if the
2262 original argument was a file name with an extension.
2264 @node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2265 @anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{52}
2266 @subsubsection Krunching Method
2269 The initial file name is determined by the name of the unit that the file
2270 contains. The name is formed by taking the full expanded name of the
2271 unit and replacing the separating dots with hyphens and
2272 using lowercase
2273 for all letters, except that a hyphen in the second character position is
2274 replaced by a tilde if the first character is
2275 @code{a}, @code{i}, @code{g}, or @code{s}.
2276 The extension is @code{.ads} for a
2277 spec and @code{.adb} for a body.
2278 Krunching does not affect the extension, but the file name is shortened to
2279 the specified length by following these rules:
2282 @itemize *
2284 @item 
2285 The name is divided into segments separated by hyphens, tildes or
2286 underscores and all hyphens, tildes, and underscores are
2287 eliminated. If this leaves the name short enough, we are done.
2289 @item 
2290 If the name is too long, the longest segment is located (left-most
2291 if there are two of equal length), and shortened by dropping
2292 its last character. This is repeated until the name is short enough.
2294 As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2295 to fit the name into 8 characters as required by some operating systems:
2297 @example
2298 our-strings-wide_fixed 22
2299 our strings wide fixed 19
2300 our string  wide fixed 18
2301 our strin   wide fixed 17
2302 our stri    wide fixed 16
2303 our stri    wide fixe  15
2304 our str     wide fixe  14
2305 our str     wid  fixe  13
2306 our str     wid  fix   12
2307 ou  str     wid  fix   11
2308 ou  st      wid  fix   10
2309 ou  st      wi   fix   9
2310 ou  st      wi   fi    8
2311 Final file name: oustwifi.adb
2312 @end example
2314 @item 
2315 The file names for all predefined units are always krunched to eight
2316 characters. The krunching of these predefined units uses the following
2317 special prefix replacements:
2320 @multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} 
2321 @item
2323 Prefix
2325 @tab
2327 Replacement
2329 @item
2331 @code{ada-}
2333 @tab
2335 @code{a-}
2337 @item
2339 @code{gnat-}
2341 @tab
2343 @code{g-}
2345 @item
2347 @code{interfac es-}
2349 @tab
2351 @code{i-}
2353 @item
2355 @code{system-}
2357 @tab
2359 @code{s-}
2361 @end multitable
2364 These system files have a hyphen in the second character position. That
2365 is why normal user files replace such a character with a
2366 tilde, to avoid confusion with system file names.
2368 As an example of this special rule, consider
2369 @code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2371 @example
2372 ada-strings-wide_fixed 22
2373 a-  strings wide fixed 18
2374 a-  string  wide fixed 17
2375 a-  strin   wide fixed 16
2376 a-  stri    wide fixed 15
2377 a-  stri    wide fixe  14
2378 a-  str     wide fixe  13
2379 a-  str     wid  fixe  12
2380 a-  str     wid  fix   11
2381 a-  st      wid  fix   10
2382 a-  st      wi   fix   9
2383 a-  st      wi   fi    8
2384 Final file name: a-stwifi.adb
2385 @end example
2386 @end itemize
2388 Of course no file shortening algorithm can guarantee uniqueness over all
2389 possible unit names, and if file name krunching is used then it is your
2390 responsibility to ensure that no name clashes occur. The utility
2391 program @code{gnatkr} is supplied for conveniently determining the
2392 krunched name of a file.
2394 @node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2395 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{53}@anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{54}
2396 @subsubsection Examples of @code{gnatkr} Usage
2399 @example
2400 $ gnatkr very_long_unit_name.ads      --> velounna.ads
2401 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
2402 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2403 $ gnatkr grandparent-parent-child     --> grparchi
2404 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2405 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2406 @end example
2408 @node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2409 @anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{55}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{1d}
2410 @subsection Renaming Files with @code{gnatchop}
2413 @geindex gnatchop
2415 This section discusses how to handle files with multiple units by using
2416 the @code{gnatchop} utility. This utility is also useful in renaming
2417 files to meet the standard GNAT default file naming conventions.
2419 @menu
2420 * Handling Files with Multiple Units:: 
2421 * Operating gnatchop in Compilation Mode:: 
2422 * Command Line for gnatchop:: 
2423 * Switches for gnatchop:: 
2424 * Examples of gnatchop Usage:: 
2426 @end menu
2428 @node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2429 @anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{56}@anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{57}
2430 @subsubsection Handling Files with Multiple Units
2433 The basic compilation model of GNAT requires that a file submitted to the
2434 compiler have only one unit and there be a strict correspondence
2435 between the file name and the unit name.
2437 If you want to keep your files with multiple units,
2438 perhaps to maintain compatibility with some other Ada compilation system,
2439 you can use @code{gnatname} to generate or update your project files.
2440 Generated or modified project files can be processed by GNAT.
2442 See @ref{42,,Handling Arbitrary File Naming Conventions with gnatname}
2443 for more details on how to use @cite{gnatname}.
2445 Alternatively, if you want to permanently restructure a set of ‘foreign’
2446 files so that they match the GNAT rules, and do the remaining development
2447 using the GNAT structure, you can simply use @code{gnatchop} once, generate the
2448 new set of files and work with them from that point on.
2450 Note that if your file containing multiple units starts with a byte order
2451 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2452 will each start with a copy of this BOM, meaning that they can be compiled
2453 automatically in UTF-8 mode without needing to specify an explicit encoding.
2455 @node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2456 @anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{58}@anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{59}
2457 @subsubsection Operating gnatchop in Compilation Mode
2460 The basic function of @code{gnatchop} is to take a file with multiple units
2461 and split it into separate files. The boundary between files is reasonably
2462 clear, except for the issue of comments and pragmas. In default mode, the
2463 rule is that any pragmas between units belong to the previous unit, except
2464 that configuration pragmas always belong to the following unit. Any comments
2465 belong to the following unit. These rules
2466 almost always result in the right choice of
2467 the split point without needing to mark it explicitly and most users will
2468 find this default to be what they want. In this default mode it is incorrect to
2469 submit a file containing only configuration pragmas, or one that ends in
2470 configuration pragmas, to @code{gnatchop}.
2472 However, using a special option to activate ‘compilation mode’,
2473 @code{gnatchop}
2474 can perform another function, which is to provide exactly the semantics
2475 required by the RM for handling of configuration pragmas in a compilation.
2476 In the absence of configuration pragmas (at the main file level), this
2477 option has no effect, but it causes such configuration pragmas to be handled
2478 in a quite different manner.
2480 First, in compilation mode, if @code{gnatchop} is given a file that consists of
2481 only configuration pragmas, then this file is appended to the
2482 @code{gnat.adc} file in the current directory. This behavior provides
2483 the required behavior described in the RM for the actions to be taken
2484 on submitting such a file to the compiler, namely that these pragmas
2485 should apply to all subsequent compilations in the same compilation
2486 environment. Using GNAT, the current directory, possibly containing a
2487 @code{gnat.adc} file is the representation
2488 of a compilation environment. For more information on the
2489 @code{gnat.adc} file, see @ref{3f,,Handling of Configuration Pragmas}.
2491 Second, in compilation mode, if @code{gnatchop}
2492 is given a file that starts with
2493 configuration pragmas, and contains one or more units, then these
2494 configuration pragmas are prepended to each of the chopped files. This
2495 behavior provides the required behavior described in the RM for the
2496 actions to be taken on compiling such a file, namely that the pragmas
2497 apply to all units in the compilation, but not to subsequently compiled
2498 units.
2500 Finally, if configuration pragmas appear between units, they are appended
2501 to the previous unit. This results in the previous unit being illegal,
2502 since the compiler does not accept configuration pragmas that follow
2503 a unit. This provides the required RM behavior that forbids configuration
2504 pragmas other than those preceding the first compilation unit of a
2505 compilation.
2507 For most purposes, @code{gnatchop} will be used in default mode. The
2508 compilation mode described above is used only if you need exactly
2509 accurate behavior with respect to compilations, and you have files
2510 that contain multiple units and configuration pragmas. In this
2511 circumstance the use of @code{gnatchop} with the compilation mode
2512 switch provides the required behavior, and is for example the mode
2513 in which GNAT processes the ACVC tests.
2515 @node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2516 @anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{5a}@anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{5b}
2517 @subsubsection Command Line for @code{gnatchop}
2520 The @code{gnatchop} command has the form:
2522 @example
2523 $ gnatchop switches file_name [file_name ...]
2524       [directory]
2525 @end example
2527 The only required argument is the file name of the file to be chopped.
2528 There are no restrictions on the form of this file name. The file itself
2529 contains one or more Ada units, in normal GNAT format, concatenated
2530 together. As shown, more than one file may be presented to be chopped.
2532 When run in default mode, @code{gnatchop} generates one output file in
2533 the current directory for each unit in each of the files.
2535 @code{directory}, if specified, gives the name of the directory to which
2536 the output files will be written. If it is not specified, all files are
2537 written to the current directory.
2539 For example, given a
2540 file called @code{hellofiles} containing
2542 @example
2543 procedure Hello;
2545 with Ada.Text_IO; use Ada.Text_IO;
2546 procedure Hello is
2547 begin
2548    Put_Line ("Hello");
2549 end Hello;
2550 @end example
2552 the command
2554 @example
2555 $ gnatchop hellofiles
2556 @end example
2558 generates two files in the current directory, one called
2559 @code{hello.ads} containing the single line that is the procedure spec,
2560 and the other called @code{hello.adb} containing the remaining text. The
2561 original file is not affected. The generated files can be compiled in
2562 the normal manner.
2564 When gnatchop is invoked on a file that is empty or that contains only empty
2565 lines and/or comments, gnatchop will not fail, but will not produce any
2566 new sources.
2568 For example, given a
2569 file called @code{toto.txt} containing
2571 @example
2572 --  Just a comment
2573 @end example
2575 the command
2577 @example
2578 $ gnatchop toto.txt
2579 @end example
2581 will not produce any new file and will result in the following warnings:
2583 @example
2584 toto.txt:1:01: warning: empty file, contains no compilation units
2585 no compilation units found
2586 no source files written
2587 @end example
2589 @node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2590 @anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{5c}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{5d}
2591 @subsubsection Switches for @code{gnatchop}
2594 @code{gnatchop} recognizes the following switches:
2596 @geindex --version (gnatchop)
2599 @table @asis
2601 @item @code{--version}
2603 Display Copyright and version, then exit disregarding all other options.
2604 @end table
2606 @geindex --help (gnatchop)
2609 @table @asis
2611 @item @code{--help}
2613 If @code{--version} was not used, display usage, then exit disregarding
2614 all other options.
2615 @end table
2617 @geindex -c (gnatchop)
2620 @table @asis
2622 @item @code{-c}
2624 Causes @code{gnatchop} to operate in compilation mode, in which
2625 configuration pragmas are handled according to strict RM rules. See
2626 previous section for a full description of this mode.
2628 @item @code{-gnat@emph{xxx}}
2630 This passes the given @code{-gnat@emph{xxx}} switch to @code{gnat} which is
2631 used to parse the given file. Not all @emph{xxx} options make sense,
2632 but for example, the use of @code{-gnati2} allows @code{gnatchop} to
2633 process a source file that uses Latin-2 coding for identifiers.
2635 @item @code{-h}
2637 Causes @code{gnatchop} to generate a brief help summary to the standard
2638 output file showing usage information.
2639 @end table
2641 @geindex -k (gnatchop)
2644 @table @asis
2646 @item @code{-k@emph{mm}}
2648 Limit generated file names to the specified number @code{mm}
2649 of characters.
2650 This is useful if the
2651 resulting set of files is required to be interoperable with systems
2652 which limit the length of file names.
2653 No space is allowed between the @code{-k} and the numeric value. The numeric
2654 value may be omitted in which case a default of @code{-k8},
2655 suitable for use
2656 with DOS-like file systems, is used. If no @code{-k} switch
2657 is present then
2658 there is no limit on the length of file names.
2659 @end table
2661 @geindex -p (gnatchop)
2664 @table @asis
2666 @item @code{-p}
2668 Causes the file modification time stamp of the input file to be
2669 preserved and used for the time stamp of the output file(s). This may be
2670 useful for preserving coherency of time stamps in an environment where
2671 @code{gnatchop} is used as part of a standard build process.
2672 @end table
2674 @geindex -q (gnatchop)
2677 @table @asis
2679 @item @code{-q}
2681 Causes output of informational messages indicating the set of generated
2682 files to be suppressed. Warnings and error messages are unaffected.
2683 @end table
2685 @geindex -r (gnatchop)
2687 @geindex Source_Reference pragmas
2690 @table @asis
2692 @item @code{-r}
2694 Generate @code{Source_Reference} pragmas. Use this switch if the output
2695 files are regarded as temporary and development is to be done in terms
2696 of the original unchopped file. This switch causes
2697 @code{Source_Reference} pragmas to be inserted into each of the
2698 generated files to refers back to the original file name and line number.
2699 The result is that all error messages refer back to the original
2700 unchopped file.
2701 In addition, the debugging information placed into the object file (when
2702 the @code{-g} switch of @code{gcc} or @code{gnatmake} is
2703 specified)
2704 also refers back to this original file so that tools like profilers and
2705 debuggers will give information in terms of the original unchopped file.
2707 If the original file to be chopped itself contains
2708 a @code{Source_Reference}
2709 pragma referencing a third file, then gnatchop respects
2710 this pragma, and the generated @code{Source_Reference} pragmas
2711 in the chopped file refer to the original file, with appropriate
2712 line numbers. This is particularly useful when @code{gnatchop}
2713 is used in conjunction with @code{gnatprep} to compile files that
2714 contain preprocessing statements and multiple units.
2715 @end table
2717 @geindex -v (gnatchop)
2720 @table @asis
2722 @item @code{-v}
2724 Causes @code{gnatchop} to operate in verbose mode. The version
2725 number and copyright notice are output, as well as exact copies of
2726 the gnat1 commands spawned to obtain the chop control information.
2727 @end table
2729 @geindex -w (gnatchop)
2732 @table @asis
2734 @item @code{-w}
2736 Overwrite existing file names. Normally @code{gnatchop} regards it as a
2737 fatal error if there is already a file with the same name as a
2738 file it would otherwise output, in other words if the files to be
2739 chopped contain duplicated units. This switch bypasses this
2740 check, and causes all but the last instance of such duplicated
2741 units to be skipped.
2742 @end table
2744 @geindex --GCC= (gnatchop)
2747 @table @asis
2749 @item @code{--GCC=@emph{xxxx}}
2751 Specify the path of the GNAT parser to be used. When this switch is used,
2752 no attempt is made to add the prefix to the GNAT parser executable.
2753 @end table
2755 @node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
2756 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{5e}@anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{5f}
2757 @subsubsection Examples of @code{gnatchop} Usage
2760 @example
2761 $ gnatchop -w hello_s.ada prerelease/files
2762 @end example
2764 Chops the source file @code{hello_s.ada}. The output files will be
2765 placed in the directory @code{prerelease/files},
2766 overwriting any
2767 files with matching names in that directory (no files in the current
2768 directory are modified).
2770 @example
2771 $ gnatchop archive
2772 @end example
2774 Chops the source file @code{archive}
2775 into the current directory. One
2776 useful application of @code{gnatchop} is in sending sets of sources
2777 around, for example in email messages. The required sources are simply
2778 concatenated (for example, using a Unix @code{cat}
2779 command), and then
2780 @code{gnatchop} is used at the other end to reconstitute the original
2781 file names.
2783 @example
2784 $ gnatchop file1 file2 file3 direc
2785 @end example
2787 Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
2788 the resulting files in the directory @code{direc}. Note that if any units
2789 occur more than once anywhere within this set of files, an error message
2790 is generated, and no files are written. To override this check, use the
2791 @code{-w} switch,
2792 in which case the last occurrence in the last file will
2793 be the one that is output, and earlier duplicate occurrences for a given
2794 unit will be skipped.
2796 @node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
2797 @anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{25}@anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{60}
2798 @section Configuration Pragmas
2801 @geindex Configuration pragmas
2803 @geindex Pragmas
2804 @geindex configuration
2806 Configuration pragmas include those pragmas described as
2807 such in the Ada Reference Manual, as well as
2808 implementation-dependent pragmas that are configuration pragmas.
2809 See the @code{Implementation_Defined_Pragmas} chapter in the
2810 @cite{GNAT_Reference_Manual} for details on these
2811 additional GNAT-specific configuration pragmas.
2812 Most notably, the pragma @code{Source_File_Name}, which allows
2813 specifying non-default names for source files, is a configuration
2814 pragma. The following is a complete list of configuration pragmas
2815 recognized by GNAT:
2817 @example
2818 Ada_83
2819 Ada_95
2820 Ada_05
2821 Ada_2005
2822 Ada_12
2823 Ada_2012
2824 Ada_2022
2825 Aggregate_Individually_Assign
2826 Allow_Integer_Address
2827 Annotate
2828 Assertion_Policy
2829 Assume_No_Invalid_Values
2830 C_Pass_By_Copy
2831 Check_Float_Overflow
2832 Check_Name
2833 Check_Policy
2834 Component_Alignment
2835 Convention_Identifier
2836 Debug_Policy
2837 Default_Scalar_Storage_Order
2838 Default_Storage_Pool
2839 Detect_Blocking
2840 Disable_Atomic_Synchronization
2841 Discard_Names
2842 Elaboration_Checks
2843 Eliminate
2844 Enable_Atomic_Synchronization
2845 Extend_System
2846 Extensions_Allowed
2847 External_Name_Casing
2848 Fast_Math
2849 Favor_Top_Level
2850 Ignore_Pragma
2851 Implicit_Packing
2852 Initialize_Scalars
2853 Interrupt_State
2854 License
2855 Locking_Policy
2856 No_Component_Reordering
2857 No_Heap_Finalization
2858 No_Strict_Aliasing
2859 Normalize_Scalars
2860 Optimize_Alignment
2861 Overflow_Mode
2862 Overriding_Renamings
2863 Partition_Elaboration_Policy
2864 Persistent_BSS
2865 Prefix_Exception_Messages
2866 Priority_Specific_Dispatching
2867 Profile
2868 Profile_Warnings
2869 Queuing_Policy
2870 Rename_Pragma
2871 Restrictions
2872 Restriction_Warnings
2873 Reviewable
2874 Short_Circuit_And_Or
2875 Source_File_Name
2876 Source_File_Name_Project
2877 SPARK_Mode
2878 Style_Checks
2879 Suppress
2880 Suppress_Exception_Locations
2881 Task_Dispatching_Policy
2882 Unevaluated_Use_Of_Old
2883 Unsuppress
2884 Use_VADS_Size
2885 User_Aspect_Definition
2886 Validity_Checks
2887 Warning_As_Error
2888 Warnings
2889 Wide_Character_Encoding
2890 @end example
2892 @menu
2893 * Handling of Configuration Pragmas:: 
2894 * The Configuration Pragmas Files:: 
2896 @end menu
2898 @node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
2899 @anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{3f}@anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{61}
2900 @subsection Handling of Configuration Pragmas
2903 Configuration pragmas may either appear at the start of a compilation
2904 unit, or they can appear in a configuration pragma file to apply to
2905 all compilations performed in a given compilation environment.
2907 GNAT also provides the @code{gnatchop} utility to provide an automatic
2908 way to handle configuration pragmas following the semantics for
2909 compilations (that is, files with multiple units), described in the RM.
2910 See @ref{59,,Operating gnatchop in Compilation Mode} for details.
2911 However, for most purposes, it will be more convenient to edit the
2912 @code{gnat.adc} file that contains configuration pragmas directly,
2913 as described in the following section.
2915 In the case of @code{Restrictions} pragmas appearing as configuration
2916 pragmas in individual compilation units, the exact handling depends on
2917 the type of restriction.
2919 Restrictions that require partition-wide consistency (like
2920 @code{No_Tasking}) are
2921 recognized wherever they appear
2922 and can be freely inherited, e.g. from a @emph{with}ed unit to the @emph{with}ing
2923 unit. This makes sense since the binder will in any case insist on seeing
2924 consistent use, so any unit not conforming to any restrictions that are
2925 anywhere in the partition will be rejected, and you might as well find
2926 that out at compile time rather than at bind time.
2928 For restrictions that do not require partition-wide consistency, e.g.
2929 SPARK or No_Implementation_Attributes, in general the restriction applies
2930 only to the unit in which the pragma appears, and not to any other units.
2932 The exception is No_Elaboration_Code which always applies to the entire
2933 object file from a compilation, i.e. to the body, spec, and all subunits.
2934 This restriction can be specified in a configuration pragma file, or it
2935 can be on the body and/or the spec (in either case it applies to all the
2936 relevant units). It can appear on a subunit only if it has previously
2937 appeared in the body of spec.
2939 @node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
2940 @anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{62}@anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{63}
2941 @subsection The Configuration Pragmas Files
2944 @geindex gnat.adc
2946 In GNAT a compilation environment is defined by the current
2947 directory at the time that a compile command is given. This current
2948 directory is searched for a file whose name is @code{gnat.adc}. If
2949 this file is present, it is expected to contain one or more
2950 configuration pragmas that will be applied to the current compilation.
2951 However, if the switch @code{-gnatA} is used, @code{gnat.adc} is not
2952 considered. When taken into account, @code{gnat.adc} is added to the
2953 dependencies, so that if @code{gnat.adc} is modified later, an invocation of
2954 @code{gnatmake} will recompile the source.
2956 Configuration pragmas may be entered into the @code{gnat.adc} file
2957 either by running @code{gnatchop} on a source file that consists only of
2958 configuration pragmas, or more conveniently by direct editing of the
2959 @code{gnat.adc} file, which is a standard format source file.
2961 Besides @code{gnat.adc}, additional files containing configuration
2962 pragmas may be applied to the current compilation using the switch
2963 @code{-gnatec=@emph{path}} where @code{path} must designate an existing file that
2964 contains only configuration pragmas. These configuration pragmas are
2965 in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
2966 is present and switch @code{-gnatA} is not used).
2968 It is allowable to specify several switches @code{-gnatec=}, all of which
2969 will be taken into account.
2971 Files containing configuration pragmas specified with switches
2972 @code{-gnatec=} are added to the dependencies, unless they are
2973 temporary files. A file is considered temporary if its name ends in
2974 @code{.tmp} or @code{.TMP}. Certain tools follow this naming
2975 convention because they pass information to @code{gcc} via
2976 temporary files that are immediately deleted; it doesn’t make sense to
2977 depend on a file that no longer exists. Such tools include
2978 @code{gprbuild}, @code{gnatmake}, and @code{gnatcheck}.
2980 By default, configuration pragma files are stored by their absolute paths in
2981 ALI files. You can use the @code{-gnateb} switch in order to store them by
2982 their basename instead.
2984 If you are using project file, a separate mechanism is provided using
2985 project attributes.
2987 @c --Comment
2988 @c See :ref:`Specifying_Configuration_Pragmas` for more details.
2990 @node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
2991 @anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{26}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{64}
2992 @section Generating Object Files
2995 An Ada program consists of a set of source files, and the first step in
2996 compiling the program is to generate the corresponding object files.
2997 These are generated by compiling a subset of these source files.
2998 The files you need to compile are the following:
3001 @itemize *
3003 @item 
3004 If a package spec has no body, compile the package spec to produce the
3005 object file for the package.
3007 @item 
3008 If a package has both a spec and a body, compile the body to produce the
3009 object file for the package. The source file for the package spec need
3010 not be compiled in this case because there is only one object file, which
3011 contains the code for both the spec and body of the package.
3013 @item 
3014 For a subprogram, compile the subprogram body to produce the object file
3015 for the subprogram. The spec, if one is present, is as usual in a
3016 separate file, and need not be compiled.
3017 @end itemize
3019 @geindex Subunits
3022 @itemize *
3024 @item 
3025 In the case of subunits, only compile the parent unit. A single object
3026 file is generated for the entire subunit tree, which includes all the
3027 subunits.
3029 @item 
3030 Compile child units independently of their parent units
3031 (though, of course, the spec of all the ancestor unit must be present in order
3032 to compile a child unit).
3034 @geindex Generics
3036 @item 
3037 Compile generic units in the same manner as any other units. The object
3038 files in this case are small dummy files that contain at most the
3039 flag used for elaboration checking. This is because GNAT always handles generic
3040 instantiation by means of macro expansion. However, it is still necessary to
3041 compile generic units, for dependency checking and elaboration purposes.
3042 @end itemize
3044 The preceding rules describe the set of files that must be compiled to
3045 generate the object files for a program. Each object file has the same
3046 name as the corresponding source file, except that the extension is
3047 @code{.o} as usual.
3049 You may wish to compile other files for the purpose of checking their
3050 syntactic and semantic correctness. For example, in the case where a
3051 package has a separate spec and body, you would not normally compile the
3052 spec. However, it is convenient in practice to compile the spec to make
3053 sure it is error-free before compiling clients of this spec, because such
3054 compilations will fail if there is an error in the spec.
3056 GNAT provides an option for compiling such files purely for the
3057 purposes of checking correctness; such compilations are not required as
3058 part of the process of building a program. To compile a file in this
3059 checking mode, use the @code{-gnatc} switch.
3061 @node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3062 @anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{27}
3063 @section Source Dependencies
3066 A given object file clearly depends on the source file which is compiled
3067 to produce it. Here we are using “depends” in the sense of a typical
3068 @code{make} utility; in other words, an object file depends on a source
3069 file if changes to the source file require the object file to be
3070 recompiled.
3071 In addition to this basic dependency, a given object may depend on
3072 additional source files as follows:
3075 @itemize *
3077 @item 
3078 If a file being compiled @emph{with}s a unit @code{X}, the object file
3079 depends on the file containing the spec of unit @code{X}. This includes
3080 files that are @emph{with}ed implicitly either because they are parents
3081 of @emph{with}ed child units or they are run-time units required by the
3082 language constructs used in a particular unit.
3084 @item 
3085 If a file being compiled instantiates a library level generic unit, the
3086 object file depends on both the spec and body files for this generic
3087 unit.
3089 @item 
3090 If a file being compiled instantiates a generic unit defined within a
3091 package, the object file depends on the body file for the package as
3092 well as the spec file.
3093 @end itemize
3095 @geindex Inline
3097 @geindex -gnatn switch
3100 @itemize *
3102 @item 
3103 If a file being compiled contains a call to a subprogram for which
3104 pragma @code{Inline} applies and inlining is activated with the
3105 @code{-gnatn} switch, the object file depends on the file containing the
3106 body of this subprogram as well as on the file containing the spec. Note
3107 that for inlining to actually occur as a result of the use of this switch,
3108 it is necessary to compile in optimizing mode.
3110 @geindex -gnatN switch
3112 The use of @code{-gnatN} activates  inlining optimization
3113 that is performed by the front end of the compiler. This inlining does
3114 not require that the code generation be optimized. Like @code{-gnatn},
3115 the use of this switch generates additional dependencies.
3117 When using a gcc-based back end, then the use of
3118 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
3119 Historically front end inlining was more extensive than the gcc back end
3120 inlining, but that is no longer the case.
3122 @item 
3123 If an object file @code{O} depends on the proper body of a subunit through
3124 inlining or instantiation, it depends on the parent unit of the subunit.
3125 This means that any modification of the parent unit or one of its subunits
3126 affects the compilation of @code{O}.
3128 @item 
3129 The object file for a parent unit depends on all its subunit body files.
3131 @item 
3132 The previous two rules meant that for purposes of computing dependencies and
3133 recompilation, a body and all its subunits are treated as an indivisible whole.
3135 These rules are applied transitively: if unit @code{A} @emph{with}s
3136 unit @code{B}, whose elaboration calls an inlined procedure in package
3137 @code{C}, the object file for unit @code{A} will depend on the body of
3138 @code{C}, in file @code{c.adb}.
3140 The set of dependent files described by these rules includes all the
3141 files on which the unit is semantically dependent, as dictated by the
3142 Ada language standard. However, it is a superset of what the
3143 standard describes, because it includes generic, inline, and subunit
3144 dependencies.
3146 An object file must be recreated by recompiling the corresponding source
3147 file if any of the source files on which it depends are modified. For
3148 example, if the @code{make} utility is used to control compilation,
3149 the rule for an Ada object file must mention all the source files on
3150 which the object file depends, according to the above definition.
3151 The determination of the necessary
3152 recompilations is done automatically when one uses @code{gnatmake}.
3153 @end itemize
3155 @node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3156 @anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{66}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{28}
3157 @section The Ada Library Information Files
3160 @geindex Ada Library Information files
3162 @geindex ALI files
3164 Each compilation actually generates two output files. The first of these
3165 is the normal object file that has a @code{.o} extension. The second is a
3166 text file containing full dependency information. It has the same
3167 name as the source file, but an @code{.ali} extension.
3168 This file is known as the Ada Library Information (@code{ALI}) file.
3169 The following information is contained in the @code{ALI} file.
3172 @itemize *
3174 @item 
3175 Version information (indicates which version of GNAT was used to compile
3176 the unit(s) in question)
3178 @item 
3179 Main program information (including priority and time slice settings,
3180 as well as the wide character encoding used during compilation).
3182 @item 
3183 List of arguments used in the @code{gcc} command for the compilation
3185 @item 
3186 Attributes of the unit, including configuration pragmas used, an indication
3187 of whether the compilation was successful, exception model used etc.
3189 @item 
3190 A list of relevant restrictions applying to the unit (used for consistency)
3191 checking.
3193 @item 
3194 Categorization information (e.g., use of pragma @code{Pure}).
3196 @item 
3197 Information on all @emph{with}ed units, including presence of
3198 @code{Elaborate} or @code{Elaborate_All} pragmas.
3200 @item 
3201 Information from any @code{Linker_Options} pragmas used in the unit
3203 @item 
3204 Information on the use of @code{Body_Version} or @code{Version}
3205 attributes in the unit.
3207 @item 
3208 Dependency information. This is a list of files, together with
3209 time stamp and checksum information. These are files on which
3210 the unit depends in the sense that recompilation is required
3211 if any of these units are modified.
3213 @item 
3214 Cross-reference data. Contains information on all entities referenced
3215 in the unit. Used by some tools to provide cross-reference information.
3216 @end itemize
3218 For a full detailed description of the format of the @code{ALI} file,
3219 see the source of the body of unit @code{Lib.Writ}, contained in file
3220 @code{lib-writ.adb} in the GNAT compiler sources.
3222 @node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3223 @anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{29}@anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{67}
3224 @section Binding an Ada Program
3227 When using languages such as C and C++, once the source files have been
3228 compiled the only remaining step in building an executable program
3229 is linking the object modules together. This means that it is possible to
3230 link an inconsistent version of a program, in which two units have
3231 included different versions of the same header.
3233 The rules of Ada do not permit such an inconsistent program to be built.
3234 For example, if two clients have different versions of the same package,
3235 it is illegal to build a program containing these two clients.
3236 These rules are enforced by the GNAT binder, which also determines an
3237 elaboration order consistent with the Ada rules.
3239 The GNAT binder is run after all the object files for a program have
3240 been created. It is given the name of the main program unit, and from
3241 this it determines the set of units required by the program, by reading the
3242 corresponding ALI files. It generates error messages if the program is
3243 inconsistent or if no valid order of elaboration exists.
3245 If no errors are detected, the binder produces a main program, in Ada by
3246 default, that contains calls to the elaboration procedures of those
3247 compilation unit that require them, followed by
3248 a call to the main program. This Ada program is compiled to generate the
3249 object file for the main program. The name of
3250 the Ada file is @code{b~xxx.adb} (with the corresponding spec
3251 @code{b~xxx.ads}) where @code{xxx} is the name of the
3252 main program unit.
3254 Finally, the linker is used to build the resulting executable program,
3255 using the object from the main program from the bind step as well as the
3256 object files for the Ada units of the program.
3258 @node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3259 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{2a}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{68}
3260 @section GNAT and Libraries
3263 @geindex Library building and using
3265 This section describes how to build and use libraries with GNAT, and also shows
3266 how to recompile the GNAT run-time library. You should be familiar with the
3267 Project Manager facility (see the @emph{GNAT_Project_Manager} chapter of the
3268 @emph{GPRbuild User’s Guide}) before reading this chapter.
3270 @menu
3271 * Introduction to Libraries in GNAT:: 
3272 * General Ada Libraries:: 
3273 * Stand-alone Ada Libraries:: 
3274 * Rebuilding the GNAT Run-Time Library:: 
3276 @end menu
3278 @node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3279 @anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{69}@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{6a}
3280 @subsection Introduction to Libraries in GNAT
3283 A library is, conceptually, a collection of objects which does not have its
3284 own main thread of execution, but rather provides certain services to the
3285 applications that use it. A library can be either statically linked with the
3286 application, in which case its code is directly included in the application,
3287 or, on platforms that support it, be dynamically linked, in which case
3288 its code is shared by all applications making use of this library.
3290 GNAT supports both types of libraries.
3291 In the static case, the compiled code can be provided in different ways. The
3292 simplest approach is to provide directly the set of objects resulting from
3293 compilation of the library source files. Alternatively, you can group the
3294 objects into an archive using whatever commands are provided by the operating
3295 system. For the latter case, the objects are grouped into a shared library.
3297 In the GNAT environment, a library has three types of components:
3300 @itemize *
3302 @item 
3303 Source files,
3305 @item 
3306 @code{ALI} files (see @ref{28,,The Ada Library Information Files}), and
3308 @item 
3309 Object files, an archive or a shared library.
3310 @end itemize
3312 A GNAT library may expose all its source files, which is useful for
3313 documentation purposes. Alternatively, it may expose only the units needed by
3314 an external user to make use of the library. That is to say, the specs
3315 reflecting the library services along with all the units needed to compile
3316 those specs, which can include generic bodies or any body implementing an
3317 inlined routine. In the case of @emph{stand-alone libraries} those exposed
3318 units are called @emph{interface units} (@ref{6b,,Stand-alone Ada Libraries}).
3320 All compilation units comprising an application, including those in a library,
3321 need to be elaborated in an order partially defined by Ada’s semantics. GNAT
3322 computes the elaboration order from the @code{ALI} files and this is why they
3323 constitute a mandatory part of GNAT libraries.
3324 @emph{Stand-alone libraries} are the exception to this rule because a specific
3325 library elaboration routine is produced independently of the application(s)
3326 using the library.
3328 @node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3329 @anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{6d}
3330 @subsection General Ada Libraries
3333 @menu
3334 * Building a library:: 
3335 * Installing a library:: 
3336 * Using a library:: 
3338 @end menu
3340 @node Building a library,Installing a library,,General Ada Libraries
3341 @anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{6e}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{6f}
3342 @subsubsection Building a library
3345 The easiest way to build a library is to use the Project Manager,
3346 which supports a special type of project called a @emph{Library Project}
3347 (see the @emph{Library Projects} section in the @emph{GNAT Project Manager}
3348 chapter of the @emph{GPRbuild User’s Guide}).
3350 A project is considered a library project, when two project-level attributes
3351 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
3352 control different aspects of library configuration, additional optional
3353 project-level attributes can be specified:
3356 @itemize *
3358 @item 
3360 @table @asis
3362 @item @code{Library_Kind}
3364 This attribute controls whether the library is to be static or dynamic
3365 @end table
3367 @item 
3369 @table @asis
3371 @item @code{Library_Version}
3373 This attribute specifies the library version; this value is used
3374 during dynamic linking of shared libraries to determine if the currently
3375 installed versions of the binaries are compatible.
3376 @end table
3378 @item 
3379 @code{Library_Options}
3381 @item 
3383 @table @asis
3385 @item @code{Library_GCC}
3387 These attributes specify additional low-level options to be used during
3388 library generation, and redefine the actual application used to generate
3389 library.
3390 @end table
3391 @end itemize
3393 The GNAT Project Manager takes full care of the library maintenance task,
3394 including recompilation of the source files for which objects do not exist
3395 or are not up to date, assembly of the library archive, and installation of
3396 the library (i.e., copying associated source, object and @code{ALI} files
3397 to the specified location).
3399 Here is a simple library project file:
3401 @example
3402 project My_Lib is
3403   for Source_Dirs use ("src1", "src2");
3404   for Object_Dir use "obj";
3405   for Library_Name use "mylib";
3406   for Library_Dir use "lib";
3407   for Library_Kind use "dynamic";
3408 end My_lib;
3409 @end example
3411 and the compilation command to build and install the library:
3413 @example
3414 $ gnatmake -Pmy_lib
3415 @end example
3417 It is not entirely trivial to perform manually all the steps required to
3418 produce a library. We recommend that you use the GNAT Project Manager
3419 for this task. In special cases where this is not desired, the necessary
3420 steps are discussed below.
3422 There are various possibilities for compiling the units that make up the
3423 library: for example with a Makefile (@ref{70,,Using the GNU make Utility}) or
3424 with a conventional script. For simple libraries, it is also possible to create
3425 a dummy main program which depends upon all the packages that comprise the
3426 interface of the library. This dummy main program can then be given to
3427 @code{gnatmake}, which will ensure that all necessary objects are built.
3429 After this task is accomplished, you should follow the standard procedure
3430 of the underlying operating system to produce the static or shared library.
3432 Here is an example of such a dummy program:
3434 @example
3435 with My_Lib.Service1;
3436 with My_Lib.Service2;
3437 with My_Lib.Service3;
3438 procedure My_Lib_Dummy is
3439 begin
3440    null;
3441 end;
3442 @end example
3444 Here are the generic commands that will build an archive or a shared library.
3446 @example
3447 # compiling the library
3448 $ gnatmake -c my_lib_dummy.adb
3450 # we don't need the dummy object itself
3451 $ rm my_lib_dummy.o my_lib_dummy.ali
3453 # create an archive with the remaining objects
3454 $ ar rc libmy_lib.a *.o
3455 # some systems may require "ranlib" to be run as well
3457 # or create a shared library
3458 $ gcc -shared -o libmy_lib.so *.o
3459 # some systems may require the code to have been compiled with -fPIC
3461 # remove the object files that are now in the library
3462 $ rm *.o
3464 # Make the ALI files read-only so that gnatmake will not try to
3465 # regenerate the objects that are in the library
3466 $ chmod -w *.ali
3467 @end example
3469 Please note that the library must have a name of the form @code{lib@emph{xxx}.a}
3470 or @code{lib@emph{xxx}.so} (or @code{lib@emph{xxx}.dll} on Windows) in order to
3471 be accessed by the directive @code{-l@emph{xxx}} at link time.
3473 @node Installing a library,Using a library,Building a library,General Ada Libraries
3474 @anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{72}
3475 @subsubsection Installing a library
3478 @geindex ADA_PROJECT_PATH
3480 @geindex GPR_PROJECT_PATH
3482 If you use project files, library installation is part of the library build
3483 process (see the @emph{Installing a Library with Project Files} section of the
3484 @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User’s Guide}).
3486 When project files are not an option, it is also possible, but not recommended,
3487 to install the library so that the sources needed to use the library are on the
3488 Ada source path and the ALI files & libraries be on the Ada Object path (see
3489 @ref{73,,Search Paths and the Run-Time Library (RTL)}). Alternatively, the system
3490 administrator can place general-purpose libraries in the default compiler
3491 paths, by specifying the libraries’ location in the configuration files
3492 @code{ada_source_path} and @code{ada_object_path}. These configuration files
3493 must be located in the GNAT installation tree at the same place as the gcc spec
3494 file. The location of the gcc spec file can be determined as follows:
3496 @example
3497 $ gcc -v
3498 @end example
3500 The configuration files mentioned above have a simple format: each line
3501 must contain one unique directory name.
3502 Those names are added to the corresponding path
3503 in their order of appearance in the file. The names can be either absolute
3504 or relative; in the latter case, they are relative to where theses files
3505 are located.
3507 The files @code{ada_source_path} and @code{ada_object_path} might not be
3508 present in a
3509 GNAT installation, in which case, GNAT will look for its run-time library in
3510 the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3511 objects and @code{ALI} files). When the files exist, the compiler does not
3512 look in @code{adainclude} and @code{adalib}, and thus the
3513 @code{ada_source_path} file
3514 must contain the location for the GNAT run-time sources (which can simply
3515 be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3516 contain the location for the GNAT run-time objects (which can simply
3517 be @code{adalib}).
3519 You can also specify a new default path to the run-time library at compilation
3520 time with the switch @code{--RTS=rts-path}. You can thus choose / change
3521 the run-time library you want your program to be compiled with. This switch is
3522 recognized by @code{gcc}, @code{gnatmake}, @code{gnatbind}, @code{gnatls}, and all
3523 project aware tools.
3525 It is possible to install a library before or after the standard GNAT
3526 library, by reordering the lines in the configuration files. In general, a
3527 library must be installed before the GNAT library if it redefines
3528 any part of it.
3530 @node Using a library,,Installing a library,General Ada Libraries
3531 @anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{74}@anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{75}
3532 @subsubsection Using a library
3535 Once again, the project facility greatly simplifies the use of
3536 libraries. In this context, using a library is just a matter of adding a
3537 @emph{with} clause in the user project. For instance, to make use of the
3538 library @code{My_Lib} shown in examples in earlier sections, you can
3539 write:
3541 @example
3542 with "my_lib";
3543 project My_Proj is
3544   ...
3545 end My_Proj;
3546 @end example
3548 Even if you have a third-party, non-Ada library, you can still use GNAT’s
3549 Project Manager facility to provide a wrapper for it. For example, the
3550 following project, when @emph{with}ed by your main project, will link with the
3551 third-party library @code{liba.a}:
3553 @example
3554 project Liba is
3555    for Externally_Built use "true";
3556    for Source_Files use ();
3557    for Library_Dir use "lib";
3558    for Library_Name use "a";
3559    for Library_Kind use "static";
3560 end Liba;
3561 @end example
3563 This is an alternative to the use of @code{pragma Linker_Options}. It is
3564 especially interesting in the context of systems with several interdependent
3565 static libraries where finding a proper linker order is not easy and best be
3566 left to the tools having visibility over project dependence information.
3568 In order to use an Ada library manually, you need to make sure that this
3569 library is on both your source and object path
3570 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}
3571 and @ref{76,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3572 in an archive or a shared library, you need to specify the desired
3573 library at link time.
3575 For example, you can use the library @code{mylib} installed in
3576 @code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3578 @example
3579 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3580   -largs -lmy_lib
3581 @end example
3583 This can be expressed more simply:
3585 @example
3586 $ gnatmake my_appl
3587 @end example
3589 when the following conditions are met:
3592 @itemize *
3594 @item 
3595 @code{/dir/my_lib_src} has been added by the user to the environment
3596 variable 
3597 @geindex ADA_INCLUDE_PATH
3598 @geindex environment variable; ADA_INCLUDE_PATH
3599 @code{ADA_INCLUDE_PATH}, or by the administrator to the file
3600 @code{ada_source_path}
3602 @item 
3603 @code{/dir/my_lib_obj} has been added by the user to the environment
3604 variable 
3605 @geindex ADA_OBJECTS_PATH
3606 @geindex environment variable; ADA_OBJECTS_PATH
3607 @code{ADA_OBJECTS_PATH}, or by the administrator to the file
3608 @code{ada_object_path}
3610 @item 
3611 a pragma @code{Linker_Options} has been added to one of the sources.
3612 For example:
3614 @example
3615 pragma Linker_Options ("-lmy_lib");
3616 @end example
3617 @end itemize
3619 Note that you may also load a library dynamically at
3620 run time given its filename, as illustrated in the GNAT @code{plugins} example
3621 in the directory @code{share/examples/gnat/plugins} within the GNAT
3622 install area.
3624 @node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3625 @anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{6b}
3626 @subsection Stand-alone Ada Libraries
3629 @geindex Stand-alone libraries
3631 @menu
3632 * Introduction to Stand-alone Libraries:: 
3633 * Building a Stand-alone Library:: 
3634 * Creating a Stand-alone Library to be used in a non-Ada context:: 
3635 * Restrictions in Stand-alone Libraries:: 
3637 @end menu
3639 @node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3640 @anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{78}@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{79}
3641 @subsubsection Introduction to Stand-alone Libraries
3644 A Stand-alone Library (abbreviated ‘SAL’) is a library that contains the
3645 necessary code to
3646 elaborate the Ada units that are included in the library. In contrast with
3647 an ordinary library, which consists of all sources, objects and @code{ALI}
3648 files of the
3649 library, a SAL may specify a restricted subset of compilation units
3650 to serve as a library interface. In this case, the fully
3651 self-sufficient set of files will normally consist of an objects
3652 archive, the sources of interface units’ specs, and the @code{ALI}
3653 files of interface units.
3654 If an interface spec contains a generic unit or an inlined subprogram,
3655 the body’s
3656 source must also be provided; if the units that must be provided in the source
3657 form depend on other units, the source and @code{ALI} files of those must
3658 also be provided.
3660 The main purpose of a SAL is to minimize the recompilation overhead of client
3661 applications when a new version of the library is installed. Specifically,
3662 if the interface sources have not changed, client applications do not need to
3663 be recompiled. If, furthermore, a SAL is provided in the shared form and its
3664 version, controlled by @code{Library_Version} attribute, is not changed,
3665 then the clients do not need to be relinked.
3667 SALs also allow the library providers to minimize the amount of library source
3668 text exposed to the clients.  Such ‘information hiding’ might be useful or
3669 necessary for various reasons.
3671 Stand-alone libraries are also well suited to be used in an executable whose
3672 main routine is not written in Ada.
3674 @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
3675 @anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{7a}@anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{7b}
3676 @subsubsection Building a Stand-alone Library
3679 GNAT’s Project facility provides a simple way of building and installing
3680 stand-alone libraries; see the @emph{Stand-alone Library Projects} section
3681 in the @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User’s Guide}.
3682 To be a Stand-alone Library Project, in addition to the two attributes
3683 that make a project a Library Project (@code{Library_Name} and
3684 @code{Library_Dir}; see the @emph{Library Projects} section in the
3685 @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User’s Guide}),
3686 the attribute @code{Library_Interface} must be defined.  For example:
3688 @example
3689 for Library_Dir use "lib_dir";
3690 for Library_Name use "dummy";
3691 for Library_Interface use ("int1", "int1.child");
3692 @end example
3694 Attribute @code{Library_Interface} has a non-empty string list value,
3695 each string in the list designating a unit contained in an immediate source
3696 of the project file.
3698 When a Stand-alone Library is built, first the binder is invoked to build
3699 a package whose name depends on the library name
3700 (@code{b~dummy.ads/b} in the example above).
3701 This binder-generated package includes initialization and
3702 finalization procedures whose
3703 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
3704 in the example
3705 above). The object corresponding to this package is included in the library.
3707 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
3708 calling of these procedures if a static SAL is built, or if a shared SAL
3709 is built
3710 with the project-level attribute @code{Library_Auto_Init} set to
3711 @code{"false"}.
3713 For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
3714 (those that are listed in attribute @code{Library_Interface}) are copied to
3715 the Library Directory. As a consequence, only the Interface Units may be
3716 imported from Ada units outside of the library. If other units are imported,
3717 the binding phase will fail.
3719 It is also possible to build an encapsulated library where not only
3720 the code to elaborate and finalize the library is embedded but also
3721 ensuring that the library is linked only against static
3722 libraries. So an encapsulated library only depends on system
3723 libraries, all other code, including the GNAT runtime, is embedded. To
3724 build an encapsulated library the attribute
3725 @code{Library_Standalone} must be set to @code{encapsulated}:
3727 @example
3728 for Library_Dir use "lib_dir";
3729 for Library_Name use "dummy";
3730 for Library_Kind use "dynamic";
3731 for Library_Interface use ("int1", "int1.child");
3732 for Library_Standalone use "encapsulated";
3733 @end example
3735 The default value for this attribute is @code{standard} in which case
3736 a stand-alone library is built.
3738 The attribute @code{Library_Src_Dir} may be specified for a
3739 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
3740 single string value. Its value must be the path (absolute or relative to the
3741 project directory) of an existing directory. This directory cannot be the
3742 object directory or one of the source directories, but it can be the same as
3743 the library directory. The sources of the Interface
3744 Units of the library that are needed by an Ada client of the library will be
3745 copied to the designated directory, called the Interface Copy directory.
3746 These sources include the specs of the Interface Units, but they may also
3747 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
3748 are used, or when there is a generic unit in the spec. Before the sources
3749 are copied to the Interface Copy directory, an attempt is made to delete all
3750 files in the Interface Copy directory.
3752 Building stand-alone libraries by hand is somewhat tedious, but for those
3753 occasions when it is necessary here are the steps that you need to perform:
3756 @itemize *
3758 @item 
3759 Compile all library sources.
3761 @item 
3762 Invoke the binder with the switch @code{-n} (No Ada main program),
3763 with all the @code{ALI} files of the interfaces, and
3764 with the switch @code{-L} to give specific names to the @code{init}
3765 and @code{final} procedures.  For example:
3767 @example
3768 $ gnatbind -n int1.ali int2.ali -Lsal1
3769 @end example
3771 @item 
3772 Compile the binder generated file:
3774 @example
3775 $ gcc -c b~int2.adb
3776 @end example
3778 @item 
3779 Link the dynamic library with all the necessary object files,
3780 indicating to the linker the names of the @code{init} (and possibly
3781 @code{final}) procedures for automatic initialization (and finalization).
3782 The built library should be placed in a directory different from
3783 the object directory.
3785 @item 
3786 Copy the @code{ALI} files of the interface to the library directory,
3787 add in this copy an indication that it is an interface to a SAL
3788 (i.e., add a word @code{SL} on the line in the @code{ALI} file that starts
3789 with letter ‘P’) and make the modified copy of the @code{ALI} file
3790 read-only.
3791 @end itemize
3793 Using SALs is not different from using other libraries
3794 (see @ref{75,,Using a library}).
3796 @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
3797 @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}
3798 @subsubsection Creating a Stand-alone Library to be used in a non-Ada context
3801 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
3802 a non-Ada context.
3804 The only extra step required is to ensure that library interface subprograms
3805 are compatible with the main program, by means of @code{pragma Export}
3806 or @code{pragma Convention}.
3808 Here is an example of simple library interface for use with C main program:
3810 @example
3811 package My_Package is
3813    procedure Do_Something;
3814    pragma Export (C, Do_Something, "do_something");
3816    procedure Do_Something_Else;
3817    pragma Export (C, Do_Something_Else, "do_something_else");
3819 end My_Package;
3820 @end example
3822 On the foreign language side, you must provide a ‘foreign’ view of the
3823 library interface; remember that it should contain elaboration routines in
3824 addition to interface subprograms.
3826 The example below shows the content of @code{mylib_interface.h} (note
3827 that there is no rule for the naming of this file, any name can be used)
3829 @example
3830 /* the library elaboration procedure */
3831 extern void mylibinit (void);
3833 /* the library finalization procedure */
3834 extern void mylibfinal (void);
3836 /* the interface exported by the library */
3837 extern void do_something (void);
3838 extern void do_something_else (void);
3839 @end example
3841 Libraries built as explained above can be used from any program, provided
3842 that the elaboration procedures (named @code{mylibinit} in the previous
3843 example) are called before the library services are used. Any number of
3844 libraries can be used simultaneously, as long as the elaboration
3845 procedure of each library is called.
3847 Below is an example of a C program that uses the @code{mylib} library.
3849 @example
3850 #include "mylib_interface.h"
3853 main (void)
3855    /* First, elaborate the library before using it */
3856    mylibinit ();
3858    /* Main program, using the library exported entities */
3859    do_something ();
3860    do_something_else ();
3862    /* Library finalization at the end of the program */
3863    mylibfinal ();
3864    return 0;
3866 @end example
3868 Note that invoking any library finalization procedure generated by
3869 @code{gnatbind} shuts down the Ada run-time environment.
3870 Consequently, the
3871 finalization of all Ada libraries must be performed at the end of the program.
3872 No call to these libraries or to the Ada run-time library should be made
3873 after the finalization phase.
3875 Information on limitations of binding Ada code in non-Ada contexts can be
3876 found under @ref{7e,,Binding with Non-Ada Main Programs}.
3878 Note also that special care must be taken with multi-tasks
3879 applications. The initialization and finalization routines are not
3880 protected against concurrent access. If such requirement is needed it
3881 must be ensured at the application level using a specific operating
3882 system services like a mutex or a critical-section.
3884 @node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
3885 @anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{7f}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{80}
3886 @subsubsection Restrictions in Stand-alone Libraries
3889 The pragmas listed below should be used with caution inside libraries,
3890 as they can create incompatibilities with other Ada libraries:
3893 @itemize *
3895 @item 
3896 pragma @code{Locking_Policy}
3898 @item 
3899 pragma @code{Partition_Elaboration_Policy}
3901 @item 
3902 pragma @code{Queuing_Policy}
3904 @item 
3905 pragma @code{Task_Dispatching_Policy}
3907 @item 
3908 pragma @code{Unreserve_All_Interrupts}
3909 @end itemize
3911 When using a library that contains such pragmas, the user must make sure
3912 that all libraries use the same pragmas with the same values. Otherwise,
3913 @code{Program_Error} will
3914 be raised during the elaboration of the conflicting
3915 libraries. The usage of these pragmas and its consequences for the user
3916 should therefore be well documented.
3918 Similarly, the traceback in the exception occurrence mechanism should be
3919 enabled or disabled in a consistent manner across all libraries.
3920 Otherwise, Program_Error will be raised during the elaboration of the
3921 conflicting libraries.
3923 If the @code{Version} or @code{Body_Version}
3924 attributes are used inside a library, then you need to
3925 perform a @code{gnatbind} step that specifies all @code{ALI} files in all
3926 libraries, so that version identifiers can be properly computed.
3927 In practice these attributes are rarely used, so this is unlikely
3928 to be a consideration.
3930 @node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
3931 @anchor{gnat_ugn/the_gnat_compilation_model id46}@anchor{81}@anchor{gnat_ugn/the_gnat_compilation_model rebuilding-the-gnat-run-time-library}@anchor{82}
3932 @subsection Rebuilding the GNAT Run-Time Library
3935 @geindex GNAT Run-Time Library
3936 @geindex rebuilding
3938 @geindex Building the GNAT Run-Time Library
3940 @geindex Rebuilding the GNAT Run-Time Library
3942 @geindex Run-Time Library
3943 @geindex rebuilding
3945 It may be useful to recompile the GNAT library in various debugging or
3946 experimentation contexts. A project file called
3947 @code{libada.gpr} is provided to that effect and can be found in
3948 the directory containing the GNAT library. The location of this
3949 directory depends on the way the GNAT environment has been installed and can
3950 be determined by means of the command:
3952 @example
3953 $ gnatls -v
3954 @end example
3956 The last entry in the source search path usually contains the
3957 gnat library (the @code{adainclude} directory). This project file contains its
3958 own documentation and in particular the set of instructions needed to rebuild a
3959 new library and to use it.
3961 Note that rebuilding the GNAT Run-Time is only recommended for temporary
3962 experiments or debugging, and is not supported.
3964 @geindex Conditional compilation
3966 @node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
3967 @anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{2b}@anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{83}
3968 @section Conditional Compilation
3971 This section presents some guidelines for modeling conditional compilation in Ada and describes the
3972 gnatprep preprocessor utility.
3974 @geindex Conditional compilation
3976 @menu
3977 * Modeling Conditional Compilation in Ada:: 
3978 * Preprocessing with gnatprep:: 
3979 * Integrated Preprocessing:: 
3981 @end menu
3983 @node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
3984 @anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{84}@anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{85}
3985 @subsection Modeling Conditional Compilation in Ada
3988 It is often necessary to arrange for a single source program
3989 to serve multiple purposes, where it is compiled in different
3990 ways to achieve these different goals. Some examples of the
3991 need for this feature are
3994 @itemize *
3996 @item 
3997 Adapting a program to a different hardware environment
3999 @item 
4000 Adapting a program to a different target architecture
4002 @item 
4003 Turning debugging features on and off
4005 @item 
4006 Arranging for a program to compile with different compilers
4007 @end itemize
4009 In C, or C++, the typical approach would be to use the preprocessor
4010 that is defined as part of the language. The Ada language does not
4011 contain such a feature. This is not an oversight, but rather a very
4012 deliberate design decision, based on the experience that overuse of
4013 the preprocessing features in C and C++ can result in programs that
4014 are extremely difficult to maintain. For example, if we have ten
4015 switches that can be on or off, this means that there are a thousand
4016 separate programs, any one of which might not even be syntactically
4017 correct, and even if syntactically correct, the resulting program
4018 might not work correctly. Testing all combinations can quickly become
4019 impossible.
4021 Nevertheless, the need to tailor programs certainly exists, and in
4022 this section we will discuss how this can
4023 be achieved using Ada in general, and GNAT in particular.
4025 @menu
4026 * Use of Boolean Constants:: 
4027 * Debugging - A Special Case:: 
4028 * Conditionalizing Declarations:: 
4029 * Use of Alternative Implementations:: 
4030 * Preprocessing:: 
4032 @end menu
4034 @node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4035 @anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{86}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{87}
4036 @subsubsection Use of Boolean Constants
4039 In the case where the difference is simply which code
4040 sequence is executed, the cleanest solution is to use Boolean
4041 constants to control which code is executed.
4043 @example
4044 FP_Initialize_Required : constant Boolean := True;
4046 if FP_Initialize_Required then
4048 end if;
4049 @end example
4051 Not only will the code inside the @code{if} statement not be executed if
4052 the constant Boolean is @code{False}, but it will also be completely
4053 deleted from the program.
4054 However, the code is only deleted after the @code{if} statement
4055 has been checked for syntactic and semantic correctness.
4056 (In contrast, with preprocessors the code is deleted before the
4057 compiler ever gets to see it, so it is not checked until the switch
4058 is turned on.)
4060 @geindex Preprocessors (contrasted with conditional compilation)
4062 Typically the Boolean constants will be in a separate package,
4063 something like:
4065 @example
4066 package Config is
4067    FP_Initialize_Required : constant Boolean := True;
4068    Reset_Available        : constant Boolean := False;
4069    ...
4070 end Config;
4071 @end example
4073 The @code{Config} package exists in multiple forms for the various targets,
4074 with an appropriate script selecting the version of @code{Config} needed.
4075 Then any other unit requiring conditional compilation can do a @emph{with}
4076 of @code{Config} to make the constants visible.
4078 @node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4079 @anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{88}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{89}
4080 @subsubsection Debugging - A Special Case
4083 A common use of conditional code is to execute statements (for example
4084 dynamic checks, or output of intermediate results) under control of a
4085 debug switch, so that the debugging behavior can be turned on and off.
4086 This can be done using a Boolean constant to control whether the code
4087 is active:
4089 @example
4090 if Debugging then
4091    Put_Line ("got to the first stage!");
4092 end if;
4093 @end example
4097 @example
4098 if Debugging and then Temperature > 999.0 then
4099    raise Temperature_Crazy;
4100 end if;
4101 @end example
4103 @geindex pragma Assert
4105 Since this is a common case, there are special features to deal with
4106 this in a convenient manner. For the case of tests, Ada 2005 has added
4107 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
4108 on the @code{Assert} pragma that has always been available in GNAT, so this
4109 feature may be used with GNAT even if you are not using Ada 2005 features.
4110 The use of pragma @code{Assert} is described in the
4111 @cite{GNAT_Reference_Manual}, but as an
4112 example, the last test could be written:
4114 @example
4115 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4116 @end example
4118 or simply
4120 @example
4121 pragma Assert (Temperature <= 999.0);
4122 @end example
4124 In both cases, if assertions are active and the temperature is excessive,
4125 the exception @code{Assert_Failure} will be raised, with the given string in
4126 the first case or a string indicating the location of the pragma in the second
4127 case used as the exception message.
4129 @geindex pragma Assertion_Policy
4131 You can turn assertions on and off by using the @code{Assertion_Policy}
4132 pragma.
4134 @geindex -gnata switch
4136 This is an Ada 2005 pragma which is implemented in all modes by
4137 GNAT. Alternatively, you can use the @code{-gnata} switch
4138 to enable assertions from the command line, which applies to
4139 all versions of Ada.
4141 @geindex pragma Debug
4143 For the example above with the @code{Put_Line}, the GNAT-specific pragma
4144 @code{Debug} can be used:
4146 @example
4147 pragma Debug (Put_Line ("got to the first stage!"));
4148 @end example
4150 If debug pragmas are enabled, the argument, which must be of the form of
4151 a procedure call, is executed (in this case, @code{Put_Line} will be called).
4152 Only one call can be present, but of course a special debugging procedure
4153 containing any code you like can be included in the program and then
4154 called in a pragma @code{Debug} argument as needed.
4156 One advantage of pragma @code{Debug} over the @code{if Debugging then}
4157 construct is that pragma @code{Debug} can appear in declarative contexts,
4158 such as at the very beginning of a procedure, before local declarations have
4159 been elaborated.
4161 @geindex pragma Debug_Policy
4163 Debug pragmas are enabled using either the @code{-gnata} switch that also
4164 controls assertions, or with a separate Debug_Policy pragma.
4166 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4167 in Ada 95 and Ada 83 programs as well), and is analogous to
4168 pragma @code{Assertion_Policy} to control assertions.
4170 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
4171 and thus they can appear in @code{gnat.adc} if you are not using a
4172 project file, or in the file designated to contain configuration pragmas
4173 in a project file.
4174 They then apply to all subsequent compilations. In practice the use of
4175 the @code{-gnata} switch is often the most convenient method of controlling
4176 the status of these pragmas.
4178 Note that a pragma is not a statement, so in contexts where a statement
4179 sequence is required, you can’t just write a pragma on its own. You have
4180 to add a @code{null} statement.
4182 @example
4183 if ... then
4184    ... -- some statements
4185 else
4186    pragma Assert (Num_Cases < 10);
4187    null;
4188 end if;
4189 @end example
4191 @node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4192 @anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{8a}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{8b}
4193 @subsubsection Conditionalizing Declarations
4196 In some cases it may be necessary to conditionalize declarations to meet
4197 different requirements. For example we might want a bit string whose length
4198 is set to meet some hardware message requirement.
4200 This may be possible using declare blocks controlled
4201 by conditional constants:
4203 @example
4204 if Small_Machine then
4205    declare
4206       X : Bit_String (1 .. 10);
4207    begin
4208       ...
4209    end;
4210 else
4211    declare
4212       X : Large_Bit_String (1 .. 1000);
4213    begin
4214       ...
4215    end;
4216 end if;
4217 @end example
4219 Note that in this approach, both declarations are analyzed by the
4220 compiler so this can only be used where both declarations are legal,
4221 even though one of them will not be used.
4223 Another approach is to define integer constants, e.g., @code{Bits_Per_Word},
4224 or Boolean constants, e.g., @code{Little_Endian}, and then write declarations
4225 that are parameterized by these constants. For example
4227 @example
4228 for Rec use
4229   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4230 end record;
4231 @end example
4233 If @code{Bits_Per_Word} is set to 32, this generates either
4235 @example
4236 for Rec use
4237   Field1 at 0 range 0 .. 32;
4238 end record;
4239 @end example
4241 for the big endian case, or
4243 @example
4244 for Rec use record
4245     Field1 at 0 range 10 .. 32;
4246 end record;
4247 @end example
4249 for the little endian case. Since a powerful subset of Ada expression
4250 notation is usable for creating static constants, clever use of this
4251 feature can often solve quite difficult problems in conditionalizing
4252 compilation (note incidentally that in Ada 95, the little endian
4253 constant was introduced as @code{System.Default_Bit_Order}, so you do not
4254 need to define this one yourself).
4256 @node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4257 @anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{8c}@anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{8d}
4258 @subsubsection Use of Alternative Implementations
4261 In some cases, none of the approaches described above are adequate. This
4262 can occur for example if the set of declarations required is radically
4263 different for two different configurations.
4265 In this situation, the official Ada way of dealing with conditionalizing
4266 such code is to write separate units for the different cases. As long as
4267 this does not result in excessive duplication of code, this can be done
4268 without creating maintenance problems. The approach is to share common
4269 code as far as possible, and then isolate the code and declarations
4270 that are different. Subunits are often a convenient method for breaking
4271 out a piece of a unit that is to be conditionalized, with separate files
4272 for different versions of the subunit for different targets, where the
4273 build script selects the right one to give to the compiler.
4275 @geindex Subunits (and conditional compilation)
4277 As an example, consider a situation where a new feature in Ada 2005
4278 allows something to be done in a really nice way. But your code must be able
4279 to compile with an Ada 95 compiler. Conceptually you want to say:
4281 @example
4282 if Ada_2005 then
4283    ... neat Ada 2005 code
4284 else
4285    ... not quite as neat Ada 95 code
4286 end if;
4287 @end example
4289 where @code{Ada_2005} is a Boolean constant.
4291 But this won’t work when @code{Ada_2005} is set to @code{False},
4292 since the @code{then} clause will be illegal for an Ada 95 compiler.
4293 (Recall that although such unreachable code would eventually be deleted
4294 by the compiler, it still needs to be legal.  If it uses features
4295 introduced in Ada 2005, it will be illegal in Ada 95.)
4297 So instead we write
4299 @example
4300 procedure Insert is separate;
4301 @end example
4303 Then we have two files for the subunit @code{Insert}, with the two sets of
4304 code.
4305 If the package containing this is called @code{File_Queries}, then we might
4306 have two files
4309 @itemize *
4311 @item 
4312 @code{file_queries-insert-2005.adb}
4314 @item 
4315 @code{file_queries-insert-95.adb}
4316 @end itemize
4318 and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4320 This can also be done with project files’ naming schemes. For example:
4322 @example
4323 for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4324 @end example
4326 Note also that with project files it is desirable to use a different extension
4327 than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4328 conflict may arise through another commonly used feature: to declare as part
4329 of the project a set of directories containing all the sources obeying the
4330 default naming scheme.
4332 The use of alternative units is certainly feasible in all situations,
4333 and for example the Ada part of the GNAT run-time is conditionalized
4334 based on the target architecture using this approach. As a specific example,
4335 consider the implementation of the AST feature in VMS. There is one
4336 spec: @code{s-asthan.ads} which is the same for all architectures, and three
4337 bodies:
4340 @itemize *
4342 @item 
4344 @table @asis
4346 @item @code{s-asthan.adb}
4348 used for all non-VMS operating systems
4349 @end table
4351 @item 
4353 @table @asis
4355 @item @code{s-asthan-vms-alpha.adb}
4357 used for VMS on the Alpha
4358 @end table
4360 @item 
4362 @table @asis
4364 @item @code{s-asthan-vms-ia64.adb}
4366 used for VMS on the ia64
4367 @end table
4368 @end itemize
4370 The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4371 this operating system feature is not available, and the two remaining
4372 versions interface with the corresponding versions of VMS to provide
4373 VMS-compatible AST handling. The GNAT build script knows the architecture
4374 and operating system, and automatically selects the right version,
4375 renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4377 Another style for arranging alternative implementations is through Ada’s
4378 access-to-subprogram facility.
4379 In case some functionality is to be conditionally included,
4380 you can declare an access-to-procedure variable @code{Ref} that is initialized
4381 to designate a ‘do nothing’ procedure, and then invoke @code{Ref.all}
4382 when appropriate.
4383 In some library package, set @code{Ref} to @code{Proc'Access} for some
4384 procedure @code{Proc} that performs the relevant processing.
4385 The initialization only occurs if the library package is included in the
4386 program.
4387 The same idea can also be implemented using tagged types and dispatching
4388 calls.
4390 @node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4391 @anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{8e}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{8f}
4392 @subsubsection Preprocessing
4395 @geindex Preprocessing
4397 Although it is quite possible to conditionalize code without the use of
4398 C-style preprocessing, as described earlier in this section, it is
4399 nevertheless convenient in some cases to use the C approach. Moreover,
4400 older Ada compilers have often provided some preprocessing capability,
4401 so legacy code may depend on this approach, even though it is not
4402 standard.
4404 To accommodate such use, GNAT provides a preprocessor (modeled to a large
4405 extent on the various preprocessors that have been used
4406 with legacy code on other compilers, to enable easier transition).
4408 @geindex gnatprep
4410 The preprocessor may be used in two separate modes. It can be used quite
4411 separately from the compiler, to generate a separate output source file
4412 that is then fed to the compiler as a separate step. This is the
4413 @code{gnatprep} utility, whose use is fully described in
4414 @ref{90,,Preprocessing with gnatprep}.
4416 The preprocessing language allows such constructs as
4418 @example
4419 #if DEBUG or else (PRIORITY > 4) then
4420    sequence of declarations
4421 #else
4422    completely different sequence of declarations
4423 #end if;
4424 @end example
4426 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
4427 defined either on the command line or in a separate file.
4429 The other way of running the preprocessor is even closer to the C style and
4430 often more convenient. In this approach the preprocessing is integrated into
4431 the compilation process. The compiler is given the preprocessor input which
4432 includes @code{#if} lines etc, and then the compiler carries out the
4433 preprocessing internally and processes the resulting output.
4434 For more details on this approach, see @ref{91,,Integrated Preprocessing}.
4436 @node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4437 @anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{92}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{90}
4438 @subsection Preprocessing with @code{gnatprep}
4441 @geindex gnatprep
4443 @geindex Preprocessing (gnatprep)
4445 This section discusses how to use GNAT’s @code{gnatprep} utility for simple
4446 preprocessing.
4447 Although designed for use with GNAT, @code{gnatprep} does not depend on any
4448 special GNAT features.
4449 For further discussion of conditional compilation in general, see
4450 @ref{2b,,Conditional Compilation}.
4452 @menu
4453 * Preprocessing Symbols:: 
4454 * Using gnatprep:: 
4455 * Switches for gnatprep:: 
4456 * Form of Definitions File:: 
4457 * Form of Input Text for gnatprep:: 
4459 @end menu
4461 @node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4462 @anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{93}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{94}
4463 @subsubsection Preprocessing Symbols
4466 Preprocessing symbols are defined in @emph{definition files} and referenced in the
4467 sources to be preprocessed. A preprocessing symbol is an identifier, following
4468 normal Ada (case-insensitive) rules for its syntax, with the restriction that
4469 all characters need to be in the ASCII set (no accented letters).
4471 @node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4472 @anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{95}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{96}
4473 @subsubsection Using @code{gnatprep}
4476 To call @code{gnatprep} use:
4478 @example
4479 $ gnatprep [ switches ] infile outfile [ deffile ]
4480 @end example
4482 where
4485 @itemize *
4487 @item 
4489 @table @asis
4491 @item @emph{switches}
4493 is an optional sequence of switches as described in the next section.
4494 @end table
4496 @item 
4498 @table @asis
4500 @item @emph{infile}
4502 is the full name of the input file, which is an Ada source
4503 file containing preprocessor directives.
4504 @end table
4506 @item 
4508 @table @asis
4510 @item @emph{outfile}
4512 is the full name of the output file, which is an Ada source
4513 in standard Ada form. When used with GNAT, this file name will
4514 normally have an @code{ads} or @code{adb} suffix.
4515 @end table
4517 @item 
4519 @table @asis
4521 @item @code{deffile}
4523 is the full name of a text file containing definitions of
4524 preprocessing symbols to be referenced by the preprocessor. This argument is
4525 optional, and can be replaced by the use of the @code{-D} switch.
4526 @end table
4527 @end itemize
4529 @node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4530 @anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{97}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{98}
4531 @subsubsection Switches for @code{gnatprep}
4534 @geindex --version (gnatprep)
4537 @table @asis
4539 @item @code{--version}
4541 Display Copyright and version, then exit disregarding all other options.
4542 @end table
4544 @geindex --help (gnatprep)
4547 @table @asis
4549 @item @code{--help}
4551 If @code{--version} was not used, display usage and then exit disregarding
4552 all other options.
4553 @end table
4555 @geindex -b (gnatprep)
4558 @table @asis
4560 @item @code{-b}
4562 Causes both preprocessor lines and the lines deleted by
4563 preprocessing to be replaced by blank lines in the output source file,
4564 preserving line numbers in the output file.
4565 @end table
4567 @geindex -c (gnatprep)
4570 @table @asis
4572 @item @code{-c}
4574 Causes both preprocessor lines and the lines deleted
4575 by preprocessing to be retained in the output source as comments marked
4576 with the special string @code{"--! "}. This option will result in line numbers
4577 being preserved in the output file.
4578 @end table
4580 @geindex -C (gnatprep)
4583 @table @asis
4585 @item @code{-C}
4587 Causes comments to be scanned. Normally comments are ignored by gnatprep.
4588 If this option is specified, then comments are scanned and any $symbol
4589 substitutions performed as in program text. This is particularly useful
4590 when structured comments are used (e.g., for programs written in a
4591 pre-2014 version of the SPARK Ada subset). Note that this switch is not
4592 available when  doing integrated preprocessing (it would be useless in
4593 this context since comments are ignored by the compiler in any case).
4594 @end table
4596 @geindex -D (gnatprep)
4599 @table @asis
4601 @item @code{-D@emph{symbol}[=@emph{value}]}
4603 Defines a new preprocessing symbol with the specified value. If no value is given
4604 on the command line, then symbol is considered to be @code{True}. This switch
4605 can be used in place of a definition file.
4606 @end table
4608 @geindex -r (gnatprep)
4611 @table @asis
4613 @item @code{-r}
4615 Causes a @code{Source_Reference} pragma to be generated that
4616 references the original input file, so that error messages will use
4617 the file name of this original file. The use of this switch implies
4618 that preprocessor lines are not to be removed from the file, so its
4619 use will force @code{-b} mode if @code{-c}
4620 has not been specified explicitly.
4622 Note that if the file to be preprocessed contains multiple units, then
4623 it will be necessary to @code{gnatchop} the output file from
4624 @code{gnatprep}. If a @code{Source_Reference} pragma is present
4625 in the preprocessed file, it will be respected by
4626 @code{gnatchop -r}
4627 so that the final chopped files will correctly refer to the original
4628 input source file for @code{gnatprep}.
4629 @end table
4631 @geindex -s (gnatprep)
4634 @table @asis
4636 @item @code{-s}
4638 Causes a sorted list of symbol names and values to be
4639 listed on the standard output file.
4640 @end table
4642 @geindex -T (gnatprep)
4645 @table @asis
4647 @item @code{-T}
4649 Use LF as line terminators when writing files. By default the line terminator
4650 of the host (LF under unix, CR/LF under Windows) is used.
4651 @end table
4653 @geindex -u (gnatprep)
4656 @table @asis
4658 @item @code{-u}
4660 Causes undefined symbols to be treated as having the value FALSE in the context
4661 of a preprocessor test. In the absence of this option, an undefined symbol in
4662 a @code{#if} or @code{#elsif} test will be treated as an error.
4663 @end table
4665 @geindex -v (gnatprep)
4668 @table @asis
4670 @item @code{-v}
4672 Verbose mode: generates more output about work done.
4673 @end table
4675 Note: if neither @code{-b} nor @code{-c} is present,
4676 then preprocessor lines and
4677 deleted lines are completely removed from the output, unless -r is
4678 specified, in which case -b is assumed.
4680 @node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4681 @anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{99}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{9a}
4682 @subsubsection Form of Definitions File
4685 The definitions file contains lines of the form:
4687 @example
4688 symbol := value
4689 @end example
4691 where @code{symbol} is a preprocessing symbol, and @code{value} is one of the following:
4694 @itemize *
4696 @item 
4697 Empty, corresponding to a null substitution,
4699 @item 
4700 A string literal using normal Ada syntax, or
4702 @item 
4703 Any sequence of characters from the set @{letters, digits, period, underline@}.
4704 @end itemize
4706 Comment lines may also appear in the definitions file, starting with
4707 the usual @code{--},
4708 and comments may be added to the definitions lines.
4710 @node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4711 @anchor{gnat_ugn/the_gnat_compilation_model form-of-input-text-for-gnatprep}@anchor{9b}@anchor{gnat_ugn/the_gnat_compilation_model id59}@anchor{9c}
4712 @subsubsection Form of Input Text for @code{gnatprep}
4715 The input text may contain preprocessor conditional inclusion lines,
4716 as well as general symbol substitution sequences.
4718 The preprocessor conditional inclusion commands have the form:
4720 @example
4721 #if <expression> [then]
4722    lines
4723 #elsif <expression> [then]
4724    lines
4725 #elsif <expression> [then]
4726    lines
4728 #else
4729    lines
4730 #end if;
4731 @end example
4733 In this example, <expression> is defined by the following grammar:
4735 @example
4736 <expression> ::=  <symbol>
4737 <expression> ::=  <symbol> = "<value>"
4738 <expression> ::=  <symbol> = <symbol>
4739 <expression> ::=  <symbol> = <integer>
4740 <expression> ::=  <symbol> > <integer>
4741 <expression> ::=  <symbol> >= <integer>
4742 <expression> ::=  <symbol> < <integer>
4743 <expression> ::=  <symbol> <= <integer>
4744 <expression> ::=  <symbol> 'Defined
4745 <expression> ::=  not <expression>
4746 <expression> ::=  <expression> and <expression>
4747 <expression> ::=  <expression> or <expression>
4748 <expression> ::=  <expression> and then <expression>
4749 <expression> ::=  <expression> or else <expression>
4750 <expression> ::=  ( <expression> )
4751 @end example
4753 Note the following restriction: it is not allowed to have “and” or “or”
4754 following “not” in the same expression without parentheses. For example, this
4755 is not allowed:
4757 @example
4758 not X or Y
4759 @end example
4761 This can be expressed instead as one of the following forms:
4763 @example
4764 (not X) or Y
4765 not (X or Y)
4766 @end example
4768 For the first test (<expression> ::= <symbol>) the symbol must have
4769 either the value true or false, that is to say the right-hand of the
4770 symbol definition must be one of the (case-insensitive) literals
4771 @code{True} or @code{False}. If the value is true, then the
4772 corresponding lines are included, and if the value is false, they are
4773 excluded.
4775 When comparing a symbol to an integer, the integer is any non negative
4776 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
4777 2#11#. The symbol value must also be a non negative integer. Integer values
4778 in the range 0 .. 2**31-1 are supported.
4780 The test (<expression> ::= <symbol>’Defined) is true only if
4781 the symbol has been defined in the definition file or by a @code{-D}
4782 switch on the command line. Otherwise, the test is false.
4784 The equality tests are case insensitive, as are all the preprocessor lines.
4786 If the symbol referenced is not defined in the symbol definitions file,
4787 then the effect depends on whether or not switch @code{-u}
4788 is specified. If so, then the symbol is treated as if it had the value
4789 false and the test fails. If this switch is not specified, then
4790 it is an error to reference an undefined symbol. It is also an error to
4791 reference a symbol that is defined with a value other than @code{True}
4792 or @code{False}.
4794 The use of the @code{not} operator inverts the sense of this logical test.
4795 The @code{not} operator cannot be combined with the @code{or} or @code{and}
4796 operators, without parentheses. For example, “if not X or Y then” is not
4797 allowed, but “if (not X) or Y then” and “if not (X or Y) then” are.
4799 The @code{then} keyword is optional as shown
4801 The @code{#} must be the first non-blank character on a line, but
4802 otherwise the format is free form. Spaces or tabs may appear between
4803 the @code{#} and the keyword. The keywords and the symbols are case
4804 insensitive as in normal Ada code. Comments may be used on a
4805 preprocessor line, but other than that, no other tokens may appear on a
4806 preprocessor line. Any number of @code{elsif} clauses can be present,
4807 including none at all. The @code{else} is optional, as in Ada.
4809 The @code{#} marking the start of a preprocessor line must be the first
4810 non-blank character on the line, i.e., it must be preceded only by
4811 spaces or horizontal tabs.
4813 Symbol substitution outside of preprocessor lines is obtained by using
4814 the sequence:
4816 @example
4817 $symbol
4818 @end example
4820 anywhere within a source line, except in a comment or within a
4821 string literal. The identifier
4822 following the @code{$} must match one of the symbols defined in the symbol
4823 definition file, and the result is to substitute the value of the
4824 symbol in place of @code{$symbol} in the output file.
4826 Note that although the substitution of strings within a string literal
4827 is not possible, it is possible to have a symbol whose defined value is
4828 a string literal. So instead of setting XYZ to @code{hello} and writing:
4830 @example
4831 Header : String := "$XYZ";
4832 @end example
4834 you should set XYZ to @code{"hello"} and write:
4836 @example
4837 Header : String := $XYZ;
4838 @end example
4840 and then the substitution will occur as desired.
4842 @node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
4843 @anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{9d}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{91}
4844 @subsection Integrated Preprocessing
4847 As noted above, a file to be preprocessed consists of Ada source code
4848 in which preprocessing lines have been inserted. However,
4849 instead of using @code{gnatprep} to explicitly preprocess a file as a separate
4850 step before compilation, you can carry out the preprocessing implicitly
4851 as part of compilation. Such @emph{integrated preprocessing}, which is the common
4852 style with C, is performed when either or both of the following switches
4853 are passed to the compiler:
4855 @quotation
4858 @itemize *
4860 @item 
4861 @code{-gnatep}, which specifies the @emph{preprocessor data file}.
4862 This file dictates how the source files will be preprocessed (e.g., which
4863 symbol definition files apply to which sources).
4865 @item 
4866 @code{-gnateD}, which defines values for preprocessing symbols.
4867 @end itemize
4868 @end quotation
4870 Integrated preprocessing applies only to Ada source files, it is
4871 not available for configuration pragma files.
4873 With integrated preprocessing, the output from the preprocessor is not,
4874 by default, written to any external file. Instead it is passed
4875 internally to the compiler. To preserve the result of
4876 preprocessing in a file, either run @code{gnatprep}
4877 in standalone mode or else supply the @code{-gnateG} switch
4878 (described below) to the compiler.
4880 When using project files:
4882 @quotation
4885 @itemize *
4887 @item 
4888 the builder switch @code{-x} should be used if any Ada source is
4889 compiled with @code{gnatep=}, so that the compiler finds the
4890 @emph{preprocessor data file}.
4892 @item 
4893 the preprocessing data file and the symbol definition files should be
4894 located in the source directories of the project.
4895 @end itemize
4896 @end quotation
4898 Note that the @code{gnatmake} switch @code{-m} will almost
4899 always trigger recompilation for sources that are preprocessed,
4900 because @code{gnatmake} cannot compute the checksum of the source after
4901 preprocessing.
4903 The actual preprocessing function is described in detail in
4904 @ref{90,,Preprocessing with gnatprep}. This section explains the switches
4905 that relate to integrated preprocessing.
4907 @geindex -gnatep (gcc)
4910 @table @asis
4912 @item @code{-gnatep=@emph{preprocessor_data_file}}
4914 This switch specifies the file name (without directory
4915 information) of the preprocessor data file. Either place this file
4916 in one of the source directories, or, when using project
4917 files, reference the project file’s directory via the
4918 @code{project_name'Project_Dir} project attribute; e.g:
4920 @quotation
4922 @example
4923 project Prj is
4924    package Compiler is
4925       for Switches ("Ada") use
4926         ("-gnatep=" & Prj'Project_Dir & "prep.def");
4927    end Compiler;
4928 end Prj;
4929 @end example
4930 @end quotation
4932 A preprocessor data file is a text file that contains @emph{preprocessor
4933 control lines}.  A preprocessor control line directs the preprocessing of
4934 either a particular source file, or, analogous to @code{others} in Ada,
4935 all sources not specified elsewhere in  the preprocessor data file.
4936 A preprocessor control line
4937 can optionally identify a @emph{definition file} that assigns values to
4938 preprocessor symbols, as well as a list of switches that relate to
4939 preprocessing.
4940 Empty lines and comments (using Ada syntax) are also permitted, with no
4941 semantic effect.
4943 Here’s an example of a preprocessor data file:
4945 @quotation
4947 @example
4948 "toto.adb"  "prep.def" -u
4949 --  Preprocess toto.adb, using definition file prep.def
4950 --  Undefined symbols are treated as False
4952 * -c -DVERSION=V101
4953 --  Preprocess all other sources without using a definition file
4954 --  Suppressed lined are commented
4955 --  Symbol VERSION has the value V101
4957 "tata.adb" "prep2.def" -s
4958 --  Preprocess tata.adb, using definition file prep2.def
4959 --  List all symbols with their values
4960 @end example
4961 @end quotation
4963 A preprocessor control line has the following syntax:
4965 @quotation
4967 @example
4968 <preprocessor_control_line> ::=
4969    <preprocessor_input> [ <definition_file_name> ] @{ <switch> @}
4971 <preprocessor_input> ::= <source_file_name> | '*'
4973 <definition_file_name> ::= <string_literal>
4975 <source_file_name> := <string_literal>
4977 <switch> := (See below for list)
4978 @end example
4979 @end quotation
4981 Thus  each preprocessor control line starts with either a literal string or
4982 the character ‘*’:
4985 @itemize *
4987 @item 
4988 A literal string is the file name (without directory information) of the source
4989 file that will be input to the preprocessor.
4991 @item 
4992 The character ‘*’ is a wild-card indicator; the additional parameters on the line
4993 indicate the preprocessing for all the sources
4994 that are not specified explicitly on other lines (the order of the lines is not
4995 significant).
4996 @end itemize
4998 It is an error to have two lines with the same file name or two
4999 lines starting with the character ‘*’.
5001 After the file name or ‘*’, an optional literal string specifies the name of
5002 the definition file to be used for preprocessing
5003 (@ref{99,,Form of Definitions File}). The definition files are found by the
5004 compiler in one of the source directories. In some cases, when compiling
5005 a source in a directory other than the current directory, if the definition
5006 file is in the current directory, it may be necessary to add the current
5007 directory as a source directory through the @code{-I} switch; otherwise
5008 the compiler would not find the definition file.
5010 Finally, switches similar to those of @code{gnatprep} may optionally appear:
5013 @table @asis
5015 @item @code{-b}
5017 Causes both preprocessor lines and the lines deleted by
5018 preprocessing to be replaced by blank lines, preserving the line number.
5019 This switch is always implied; however, if specified after @code{-c}
5020 it cancels the effect of @code{-c}.
5022 @item @code{-c}
5024 Causes both preprocessor lines and the lines deleted
5025 by preprocessing to be retained as comments marked
5026 with the special string ‘@cite{–!}’.
5028 @item @code{-D@emph{symbol}=@emph{new_value}}
5030 Define or redefine @code{symbol} to have @code{new_value} as its value.
5031 The permitted form for @code{symbol} is either an Ada identifier, or any Ada reserved word
5032 aside from @code{if},
5033 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5034 The permitted form for @code{new_value} is a literal string, an Ada identifier or any Ada reserved
5035 word. A symbol declared with this switch replaces a symbol with the
5036 same name defined in a definition file.
5038 @item @code{-s}
5040 Causes a sorted list of symbol names and values to be
5041 listed on the standard output file.
5043 @item @code{-u}
5045 Causes undefined symbols to be treated as having the value @code{FALSE}
5046 in the context
5047 of a preprocessor test. In the absence of this option, an undefined symbol in
5048 a @code{#if} or @code{#elsif} test will be treated as an error.
5049 @end table
5050 @end table
5052 @geindex -gnateD (gcc)
5055 @table @asis
5057 @item @code{-gnateD@emph{symbol}[=@emph{new_value}]}
5059 Define or redefine @code{symbol} to have @code{new_value} as its value. If no value
5060 is supplied, then the value of @code{symbol} is @code{True}.
5061 The form of @code{symbol} is an identifier, following normal Ada (case-insensitive)
5062 rules for its syntax, and @code{new_value} is either an arbitrary string between double
5063 quotes or any sequence (including an empty sequence) of characters from the
5064 set (letters, digits, period, underline).
5065 Ada reserved words may be used as symbols, with the exceptions of @code{if},
5066 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5068 Examples:
5070 @quotation
5072 @example
5073 -gnateDToto=Tata
5074 -gnateDFoo
5075 -gnateDFoo=\"Foo-Bar\"
5076 @end example
5077 @end quotation
5079 A symbol declared with this switch on the command line replaces a
5080 symbol with the same name either in a definition file or specified with a
5081 switch @code{-D} in the preprocessor data file.
5083 This switch is similar to switch @code{-D} of @code{gnatprep}.
5085 @item @code{-gnateG}
5087 When integrated preprocessing is performed on source file @code{filename.extension},
5088 create or overwrite @code{filename.extension.prep} to contain
5089 the result of the preprocessing.
5090 For example if the source file is @code{foo.adb} then
5091 the output file will be @code{foo.adb.prep}.
5092 @end table
5094 @node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5095 @anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{9e}@anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{2c}
5096 @section Mixed Language Programming
5099 @geindex Mixed Language Programming
5101 This section describes how to develop a mixed-language program,
5102 with a focus on combining Ada with C or C++.
5104 @menu
5105 * Interfacing to C:: 
5106 * Calling Conventions:: 
5107 * Building Mixed Ada and C++ Programs:: 
5108 * Partition-Wide Settings:: 
5109 * Generating Ada Bindings for C and C++ headers:: 
5110 * Generating C Headers for Ada Specifications:: 
5112 @end menu
5114 @node Interfacing to C,Calling Conventions,,Mixed Language Programming
5115 @anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{9f}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{a0}
5116 @subsection Interfacing to C
5119 Interfacing Ada with a foreign language such as C involves using
5120 compiler directives to import and/or export entity definitions in each
5121 language – using @code{extern} statements in C, for instance, and the
5122 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
5123 A full treatment of these topics is provided in Appendix B, section 1
5124 of the Ada Reference Manual.
5126 There are two ways to build a program using GNAT that contains some Ada
5127 sources and some foreign language sources, depending on whether or not
5128 the main subprogram is written in Ada.  Here is a source example with
5129 the main subprogram in Ada:
5131 @example
5132 /* file1.c */
5133 #include <stdio.h>
5135 void print_num (int num)
5137   printf ("num is %d.\\n", num);
5138   return;
5140 @end example
5142 @example
5143 /* file2.c */
5145 /* num_from_Ada is declared in my_main.adb */
5146 extern int num_from_Ada;
5148 int get_num (void)
5150   return num_from_Ada;
5152 @end example
5154 @example
5155 --  my_main.adb
5156 procedure My_Main is
5158    --  Declare then export an Integer entity called num_from_Ada
5159    My_Num : Integer := 10;
5160    pragma Export (C, My_Num, "num_from_Ada");
5162    --  Declare an Ada function spec for Get_Num, then use
5163    --  C function get_num for the implementation.
5164    function Get_Num return Integer;
5165    pragma Import (C, Get_Num, "get_num");
5167    --  Declare an Ada procedure spec for Print_Num, then use
5168    --  C function print_num for the implementation.
5169    procedure Print_Num (Num : Integer);
5170    pragma Import (C, Print_Num, "print_num");
5172 begin
5173    Print_Num (Get_Num);
5174 end My_Main;
5175 @end example
5177 To build this example:
5180 @itemize *
5182 @item 
5183 First compile the foreign language files to
5184 generate object files:
5186 @example
5187 $ gcc -c file1.c
5188 $ gcc -c file2.c
5189 @end example
5191 @item 
5192 Then, compile the Ada units to produce a set of object files and ALI
5193 files:
5195 @example
5196 $ gnatmake -c my_main.adb
5197 @end example
5199 @item 
5200 Run the Ada binder on the Ada main program:
5202 @example
5203 $ gnatbind my_main.ali
5204 @end example
5206 @item 
5207 Link the Ada main program, the Ada objects and the other language
5208 objects:
5210 @example
5211 $ gnatlink my_main.ali file1.o file2.o
5212 @end example
5213 @end itemize
5215 The last three steps can be grouped in a single command:
5217 @example
5218 $ gnatmake my_main.adb -largs file1.o file2.o
5219 @end example
5221 @geindex Binder output file
5223 If the main program is in a language other than Ada, then you may have
5224 more than one entry point into the Ada subsystem. You must use a special
5225 binder option to generate callable routines that initialize and
5226 finalize the Ada units (@ref{7e,,Binding with Non-Ada Main Programs}).
5227 Calls to the initialization and finalization routines must be inserted
5228 in the main program, or some other appropriate point in the code. The
5229 call to initialize the Ada units must occur before the first Ada
5230 subprogram is called, and the call to finalize the Ada units must occur
5231 after the last Ada subprogram returns. The binder will place the
5232 initialization and finalization subprograms into the
5233 @code{b~xxx.adb} file where they can be accessed by your C
5234 sources.  To illustrate, we have the following example:
5236 @example
5237 /* main.c */
5238 extern void adainit (void);
5239 extern void adafinal (void);
5240 extern int add (int, int);
5241 extern int sub (int, int);
5243 int main (int argc, char *argv[])
5245    int a = 21, b = 7;
5247    adainit();
5249    /* Should print "21 + 7 = 28" */
5250    printf ("%d + %d = %d\\n", a, b, add (a, b));
5252    /* Should print "21 - 7 = 14" */
5253    printf ("%d - %d = %d\\n", a, b, sub (a, b));
5255    adafinal();
5257 @end example
5259 @example
5260 --  unit1.ads
5261 package Unit1 is
5262    function Add (A, B : Integer) return Integer;
5263    pragma Export (C, Add, "add");
5264 end Unit1;
5265 @end example
5267 @example
5268 --  unit1.adb
5269 package body Unit1 is
5270    function Add (A, B : Integer) return Integer is
5271    begin
5272       return A + B;
5273    end Add;
5274 end Unit1;
5275 @end example
5277 @example
5278 --  unit2.ads
5279 package Unit2 is
5280    function Sub (A, B : Integer) return Integer;
5281    pragma Export (C, Sub, "sub");
5282 end Unit2;
5283 @end example
5285 @example
5286 --  unit2.adb
5287 package body Unit2 is
5288    function Sub (A, B : Integer) return Integer is
5289    begin
5290       return A - B;
5291    end Sub;
5292 end Unit2;
5293 @end example
5295 The build procedure for this application is similar to the last
5296 example’s:
5299 @itemize *
5301 @item 
5302 First, compile the foreign language files to generate object files:
5304 @example
5305 $ gcc -c main.c
5306 @end example
5308 @item 
5309 Next, compile the Ada units to produce a set of object files and ALI
5310 files:
5312 @example
5313 $ gnatmake -c unit1.adb
5314 $ gnatmake -c unit2.adb
5315 @end example
5317 @item 
5318 Run the Ada binder on every generated ALI file.  Make sure to use the
5319 @code{-n} option to specify a foreign main program:
5321 @example
5322 $ gnatbind -n unit1.ali unit2.ali
5323 @end example
5325 @item 
5326 Link the Ada main program, the Ada objects and the foreign language
5327 objects. You need only list the last ALI file here:
5329 @example
5330 $ gnatlink unit2.ali main.o -o exec_file
5331 @end example
5333 This procedure yields a binary executable called @code{exec_file}.
5334 @end itemize
5336 Depending on the circumstances (for example when your non-Ada main object
5337 does not provide symbol @code{main}), you may also need to instruct the
5338 GNAT linker not to include the standard startup objects by passing the
5339 @code{-nostartfiles} switch to @code{gnatlink}.
5341 @node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5342 @anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{a2}
5343 @subsection Calling Conventions
5346 @geindex Foreign Languages
5348 @geindex Calling Conventions
5350 GNAT follows standard calling sequence conventions and will thus interface
5351 to any other language that also follows these conventions. The following
5352 Convention identifiers are recognized by GNAT:
5354 @geindex Interfacing to Ada
5356 @geindex Other Ada compilers
5358 @geindex Convention Ada
5361 @table @asis
5363 @item @code{Ada}
5365 This indicates that the standard Ada calling sequence will be
5366 used and all Ada data items may be passed without any limitations in the
5367 case where GNAT is used to generate both the caller and callee. It is also
5368 possible to mix GNAT generated code and code generated by another Ada
5369 compiler. In this case, the data types should be restricted to simple
5370 cases, including primitive types. Whether complex data types can be passed
5371 depends on the situation. Probably it is safe to pass simple arrays, such
5372 as arrays of integers or floats. Records may or may not work, depending
5373 on whether both compilers lay them out identically. Complex structures
5374 involving variant records, access parameters, tasks, or protected types,
5375 are unlikely to be able to be passed.
5377 Note that in the case of GNAT running
5378 on a platform that supports HP Ada 83, a higher degree of compatibility
5379 can be guaranteed, and in particular records are laid out in an identical
5380 manner in the two compilers. Note also that if output from two different
5381 compilers is mixed, the program is responsible for dealing with elaboration
5382 issues. Probably the safest approach is to write the main program in the
5383 version of Ada other than GNAT, so that it takes care of its own elaboration
5384 requirements, and then call the GNAT-generated adainit procedure to ensure
5385 elaboration of the GNAT components. Consult the documentation of the other
5386 Ada compiler for further details on elaboration.
5388 However, it is not possible to mix the tasking run time of GNAT and
5389 HP Ada 83, all the tasking operations must either be entirely within
5390 GNAT compiled sections of the program, or entirely within HP Ada 83
5391 compiled sections of the program.
5392 @end table
5394 @geindex Interfacing to Assembly
5396 @geindex Convention Assembler
5399 @table @asis
5401 @item @code{Assembler}
5403 Specifies assembler as the convention. In practice this has the
5404 same effect as convention Ada (but is not equivalent in the sense of being
5405 considered the same convention).
5406 @end table
5408 @geindex Convention Asm
5410 @geindex Asm
5413 @table @asis
5415 @item @code{Asm}
5417 Equivalent to Assembler.
5419 @geindex Interfacing to COBOL
5421 @geindex Convention COBOL
5422 @end table
5424 @geindex COBOL
5427 @table @asis
5429 @item @code{COBOL}
5431 Data will be passed according to the conventions described
5432 in section B.4 of the Ada Reference Manual.
5433 @end table
5435 @geindex C
5437 @geindex Interfacing to C
5439 @geindex Convention C
5442 @table @asis
5444 @item @code{C}
5446 Data will be passed according to the conventions described
5447 in section B.3 of the Ada Reference Manual.
5449 A note on interfacing to a C ‘varargs’ function:
5451 @quotation
5453 @geindex C varargs function
5455 @geindex Interfacing to C varargs function
5457 @geindex varargs function interfaces
5459 In C, @code{varargs} allows a function to take a variable number of
5460 arguments. There is no direct equivalent in this to Ada. One
5461 approach that can be used is to create a C wrapper for each
5462 different profile and then interface to this C wrapper. For
5463 example, to print an @code{int} value using @code{printf},
5464 create a C function @code{printfi} that takes two arguments, a
5465 pointer to a string and an int, and calls @code{printf}.
5466 Then in the Ada program, use pragma @code{Import} to
5467 interface to @code{printfi}.
5469 It may work on some platforms to directly interface to
5470 a @code{varargs} function by providing a specific Ada profile
5471 for a particular call. However, this does not work on
5472 all platforms, since there is no guarantee that the
5473 calling sequence for a two argument normal C function
5474 is the same as for calling a @code{varargs} C function with
5475 the same two arguments.
5476 @end quotation
5477 @end table
5479 @geindex Convention Default
5481 @geindex Default
5484 @table @asis
5486 @item @code{Default}
5488 Equivalent to C.
5489 @end table
5491 @geindex Convention External
5493 @geindex External
5496 @table @asis
5498 @item @code{External}
5500 Equivalent to C.
5501 @end table
5503 @geindex C++
5505 @geindex Interfacing to C++
5507 @geindex Convention C++
5510 @table @asis
5512 @item @code{C_Plus_Plus} (or @code{CPP})
5514 This stands for C++. For most purposes this is identical to C.
5515 See the separate description of the specialized GNAT pragmas relating to
5516 C++ interfacing for further details.
5517 @end table
5519 @geindex Fortran
5521 @geindex Interfacing to Fortran
5523 @geindex Convention Fortran
5526 @table @asis
5528 @item @code{Fortran}
5530 Data will be passed according to the conventions described
5531 in section B.5 of the Ada Reference Manual.
5533 @item @code{Intrinsic}
5535 This applies to an intrinsic operation, as defined in the Ada
5536 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5537 this means that the body of the subprogram is provided by the compiler itself,
5538 usually by means of an efficient code sequence, and that the user does not
5539 supply an explicit body for it. In an application program, the pragma may
5540 be applied to the following sets of names:
5543 @itemize *
5545 @item 
5546 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5547 The corresponding subprogram declaration must have
5548 two formal parameters. The
5549 first one must be a signed integer type or a modular type with a binary
5550 modulus, and the second parameter must be of type Natural.
5551 The return type must be the same as the type of the first argument. The size
5552 of this type can only be 8, 16, 32, or 64.
5554 @item 
5555 Binary arithmetic operators: ‘+’, ‘-’, ‘*’, ‘/’.
5556 The corresponding operator declaration must have parameters and result type
5557 that have the same root numeric type (for example, all three are long_float
5558 types). This simplifies the definition of operations that use type checking
5559 to perform dimensional checks:
5561 @example
5562 type Distance is new Long_Float;
5563 type Time     is new Long_Float;
5564 type Velocity is new Long_Float;
5565 function "/" (D : Distance; T : Time)
5566   return Velocity;
5567 pragma Import (Intrinsic, "/");
5568 @end example
5570 This common idiom is often programmed with a generic definition and an
5571 explicit body. The pragma makes it simpler to introduce such declarations.
5572 It incurs no overhead in compilation time or code size, because it is
5573 implemented as a single machine instruction.
5575 @item 
5576 General subprogram entities. This is used  to bind an Ada subprogram
5577 declaration to
5578 a compiler builtin by name with back-ends where such interfaces are
5579 available. A typical example is the set of @code{__builtin} functions
5580 exposed by the GCC back-end, as in the following example:
5582 @example
5583 function builtin_sqrt (F : Float) return Float;
5584 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5585 @end example
5587 Most of the GCC builtins are accessible this way, and as for other
5588 import conventions (e.g. C), it is the user’s responsibility to ensure
5589 that the Ada subprogram profile matches the underlying builtin
5590 expectations.
5591 @end itemize
5592 @end table
5594 @geindex Stdcall
5596 @geindex Convention Stdcall
5599 @table @asis
5601 @item @code{Stdcall}
5603 This is relevant only to Windows implementations of GNAT,
5604 and specifies that the @code{Stdcall} calling sequence will be used,
5605 as defined by the NT API. Nevertheless, to ease building
5606 cross-platform bindings this convention will be handled as a @code{C} calling
5607 convention on non-Windows platforms.
5608 @end table
5610 @geindex DLL
5612 @geindex Convention DLL
5615 @table @asis
5617 @item @code{DLL}
5619 This is equivalent to @code{Stdcall}.
5620 @end table
5622 @geindex Win32
5624 @geindex Convention Win32
5627 @table @asis
5629 @item @code{Win32}
5631 This is equivalent to @code{Stdcall}.
5632 @end table
5634 @geindex Stubbed
5636 @geindex Convention Stubbed
5639 @table @asis
5641 @item @code{Stubbed}
5643 This is a special convention that indicates that the compiler
5644 should provide a stub body that raises @code{Program_Error}.
5645 @end table
5647 GNAT additionally provides a useful pragma @code{Convention_Identifier}
5648 that can be used to parameterize conventions and allow additional synonyms
5649 to be specified. For example if you have legacy code in which the convention
5650 identifier Fortran77 was used for Fortran, you can use the configuration
5651 pragma:
5653 @example
5654 pragma Convention_Identifier (Fortran77, Fortran);
5655 @end example
5657 And from now on the identifier Fortran77 may be used as a convention
5658 identifier (for example in an @code{Import} pragma) with the same
5659 meaning as Fortran.
5661 @node Building Mixed Ada and C++ Programs,Partition-Wide Settings,Calling Conventions,Mixed Language Programming
5662 @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}
5663 @subsection Building Mixed Ada and C++ Programs
5666 A programmer inexperienced with mixed-language development may find that
5667 building an application containing both Ada and C++ code can be a
5668 challenge.  This section gives a few hints that should make this task easier.
5670 @menu
5671 * Interfacing to C++:: 
5672 * Linking a Mixed C++ & Ada Program:: 
5673 * A Simple Example:: 
5674 * Interfacing with C++ constructors:: 
5675 * Interfacing with C++ at the Class Level:: 
5677 @end menu
5679 @node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5680 @anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{a6}
5681 @subsubsection Interfacing to C++
5684 GNAT supports interfacing with the G++ compiler (or any C++ compiler
5685 generating code that is compatible with the G++ Application Binary
5686 Interface —see @indicateurl{http://itanium-cxx-abi.github.io/cxx-abi/abi.html}).
5688 Interfacing can be done at 3 levels: simple data, subprograms, and
5689 classes. In the first two cases, GNAT offers a specific @code{Convention C_Plus_Plus}
5690 (or @code{CPP}) that behaves exactly like @code{Convention C}.
5691 Usually, C++ mangles the names of subprograms. To generate proper mangled
5692 names automatically, see @ref{a7,,Generating Ada Bindings for C and C++ headers}).
5693 This problem can also be addressed manually in two ways:
5696 @itemize *
5698 @item 
5699 by modifying the C++ code in order to force a C convention using
5700 the @code{extern "C"} syntax.
5702 @item 
5703 by figuring out the mangled name (using e.g. @code{nm}) and using it as the
5704 Link_Name argument of the pragma import.
5705 @end itemize
5707 Interfacing at the class level can be achieved by using the GNAT specific
5708 pragmas such as @code{CPP_Constructor}.  See the @cite{GNAT_Reference_Manual} for additional information.
5710 @node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5711 @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}
5712 @subsubsection Linking a Mixed C++ & Ada Program
5715 Usually the linker of the C++ development system must be used to link
5716 mixed applications because most C++ systems will resolve elaboration
5717 issues (such as calling constructors on global class instances)
5718 transparently during the link phase. GNAT has been adapted to ease the
5719 use of a foreign linker for the last phase. Three cases can be
5720 considered:
5723 @itemize *
5725 @item 
5726 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5727 The C++ linker can simply be called by using the C++ specific driver
5728 called @code{g++}.
5730 Note that if the C++ code uses inline functions, you will need to
5731 compile your C++ code with the @code{-fkeep-inline-functions} switch in
5732 order to provide an existing function implementation that the Ada code can
5733 link with.
5735 @example
5736 $ g++ -c -fkeep-inline-functions file1.C
5737 $ g++ -c -fkeep-inline-functions file2.C
5738 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5739 @end example
5741 @item 
5742 Using GNAT and G++ from two different GCC installations: If both
5743 compilers are on the 
5744 @geindex PATH
5745 @geindex environment variable; PATH
5746 @code{PATH}, the previous method may be used. It is
5747 important to note that environment variables such as
5748 @geindex C_INCLUDE_PATH
5749 @geindex environment variable; C_INCLUDE_PATH
5750 @code{C_INCLUDE_PATH}, 
5751 @geindex GCC_EXEC_PREFIX
5752 @geindex environment variable; GCC_EXEC_PREFIX
5753 @code{GCC_EXEC_PREFIX},
5754 @geindex BINUTILS_ROOT
5755 @geindex environment variable; BINUTILS_ROOT
5756 @code{BINUTILS_ROOT}, and
5757 @geindex GCC_ROOT
5758 @geindex environment variable; GCC_ROOT
5759 @code{GCC_ROOT} will affect both compilers
5760 at the same time and may make one of the two compilers operate
5761 improperly if set during invocation of the wrong compiler.  It is also
5762 very important that the linker uses the proper @code{libgcc.a} GCC
5763 library – that is, the one from the C++ compiler installation. The
5764 implicit link command as suggested in the @code{gnatmake} command
5765 from the former example can be replaced by an explicit link command with
5766 the full-verbosity option in order to verify which library is used:
5768 @example
5769 $ gnatbind ada_unit
5770 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5771 @end example
5773 If there is a problem due to interfering environment variables, it can
5774 be worked around by using an intermediate script. The following example
5775 shows the proper script to use when GNAT has not been installed at its
5776 default location and g++ has been installed at its default location:
5778 @example
5779 $ cat ./my_script
5780 #!/bin/sh
5781 unset BINUTILS_ROOT
5782 unset GCC_ROOT
5783 c++ $*
5784 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5785 @end example
5787 @item 
5788 Using a non-GNU C++ compiler: The commands previously described can be
5789 used to insure that the C++ linker is used. Nonetheless, you need to add
5790 a few more parameters to the link command line, depending on the exception
5791 mechanism used.
5793 If the @code{setjmp} / @code{longjmp} exception mechanism is used, only the paths
5794 to the @code{libgcc} libraries are required:
5796 @example
5797 $ cat ./my_script
5798 #!/bin/sh
5799 CC $* gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a
5800 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5801 @end example
5803 where CC is the name of the non-GNU C++ compiler.
5805 If the “zero cost” exception mechanism is used, and the platform
5806 supports automatic registration of exception tables (e.g., Solaris),
5807 paths to more objects are required:
5809 @example
5810 $ cat ./my_script
5811 #!/bin/sh
5812 CC gcc -print-file-name=crtbegin.o $* \\
5813 gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a \\
5814 gcc -print-file-name=crtend.o
5815 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5816 @end example
5818 If the “zero cost exception” mechanism is used, and the platform
5819 doesn’t support automatic registration of exception tables (e.g., HP-UX
5820 or AIX), the simple approach described above will not work and
5821 a pre-linking phase using GNAT will be necessary.
5822 @end itemize
5824 Another alternative is to use the @code{gprbuild} multi-language builder
5825 which has a large knowledge base and knows how to link Ada and C++ code
5826 together automatically in most cases.
5828 @node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
5829 @anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{aa}@anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{ab}
5830 @subsubsection A Simple Example
5833 The following example, provided as part of the GNAT examples, shows how
5834 to achieve procedural interfacing between Ada and C++ in both
5835 directions. The C++ class A has two methods. The first method is exported
5836 to Ada by the means of an extern C wrapper function. The second method
5837 calls an Ada subprogram. On the Ada side, the C++ calls are modelled by
5838 a limited record with a layout comparable to the C++ class. The Ada
5839 subprogram, in turn, calls the C++ method. So, starting from the C++
5840 main program, the process passes back and forth between the two
5841 languages.
5843 Here are the compilation commands:
5845 @example
5846 $ gnatmake -c simple_cpp_interface
5847 $ g++ -c cpp_main.C
5848 $ g++ -c ex7.C
5849 $ gnatbind -n simple_cpp_interface
5850 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
5851 @end example
5853 Here are the corresponding sources:
5855 @example
5856 //cpp_main.C
5858 #include "ex7.h"
5860 extern "C" @{
5861   void adainit (void);
5862   void adafinal (void);
5863   void method1 (A *t);
5866 void method1 (A *t)
5868   t->method1 ();
5871 int main ()
5873   A obj;
5874   adainit ();
5875   obj.method2 (3030);
5876   adafinal ();
5878 @end example
5880 @example
5881 //ex7.h
5883 class Origin @{
5884  public:
5885   int o_value;
5887 class A : public Origin @{
5888  public:
5889   void method1 (void);
5890   void method2 (int v);
5891   A();
5892   int   a_value;
5894 @end example
5896 @example
5897 //ex7.C
5899 #include "ex7.h"
5900 #include <stdio.h>
5902 extern "C" @{ void ada_method2 (A *t, int v);@}
5904 void A::method1 (void)
5906   a_value = 2020;
5907   printf ("in A::method1, a_value = %d \\n",a_value);
5910 void A::method2 (int v)
5912    ada_method2 (this, v);
5913    printf ("in A::method2, a_value = %d \\n",a_value);
5916 A::A(void)
5918    a_value = 1010;
5919   printf ("in A::A, a_value = %d \\n",a_value);
5921 @end example
5923 @example
5924 -- simple_cpp_interface.ads
5925 with System;
5926 package Simple_Cpp_Interface is
5927    type A is limited
5928       record
5929          Vptr    : System.Address;
5930          O_Value : Integer;
5931          A_Value : Integer;
5932       end record;
5933    pragma Convention (C, A);
5935    procedure Method1 (This : in out A);
5936    pragma Import (C, Method1);
5938    procedure Ada_Method2 (This : in out A; V : Integer);
5939    pragma Export (C, Ada_Method2);
5941 end Simple_Cpp_Interface;
5942 @end example
5944 @example
5945 -- simple_cpp_interface.adb
5946 package body Simple_Cpp_Interface is
5948    procedure Ada_Method2 (This : in out A; V : Integer) is
5949    begin
5950       Method1 (This);
5951       This.A_Value := V;
5952    end Ada_Method2;
5954 end Simple_Cpp_Interface;
5955 @end example
5957 @node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
5958 @anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{ad}
5959 @subsubsection Interfacing with C++ constructors
5962 In order to interface with C++ constructors GNAT provides the
5963 @code{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
5964 for additional information).
5965 In this section we present some common uses of C++ constructors
5966 in mixed-languages programs in GNAT.
5968 Let us assume that we need to interface with the following
5969 C++ class:
5971 @example
5972 class Root @{
5973 public:
5974   int  a_value;
5975   int  b_value;
5976   virtual int Get_Value ();
5977   Root();              // Default constructor
5978   Root(int v);         // 1st non-default constructor
5979   Root(int v, int w);  // 2nd non-default constructor
5981 @end example
5983 For this purpose we can write the following package spec (further
5984 information on how to build this spec is available in
5985 @ref{ae,,Interfacing with C++ at the Class Level} and
5986 @ref{a7,,Generating Ada Bindings for C and C++ headers}).
5988 @example
5989 with Interfaces.C; use Interfaces.C;
5990 package Pkg_Root is
5991   type Root is tagged limited record
5992      A_Value : int;
5993      B_Value : int;
5994   end record;
5995   pragma Import (CPP, Root);
5997   function Get_Value (Obj : Root) return int;
5998   pragma Import (CPP, Get_Value);
6000   function Constructor return Root;
6001   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
6003   function Constructor (v : Integer) return Root;
6004   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
6006   function Constructor (v, w : Integer) return Root;
6007   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
6008 end Pkg_Root;
6009 @end example
6011 On the Ada side the constructor is represented by a function (whose
6012 name is arbitrary) that returns the classwide type corresponding to
6013 the imported C++ class. Although the constructor is described as a
6014 function, it is typically a procedure with an extra implicit argument
6015 (the object being initialized) at the implementation level. GNAT
6016 issues the appropriate call, whatever it is, to get the object
6017 properly initialized.
6019 Constructors can only appear in the following contexts:
6022 @itemize *
6024 @item 
6025 On the right side of an initialization of an object of type @code{T}.
6027 @item 
6028 On the right side of an initialization of a record component of type @code{T}.
6030 @item 
6031 In an Ada 2005 limited aggregate.
6033 @item 
6034 In an Ada 2005 nested limited aggregate.
6036 @item 
6037 In an Ada 2005 limited aggregate that initializes an object built in
6038 place by an extended return statement.
6039 @end itemize
6041 In a declaration of an object whose type is a class imported from C++,
6042 either the default C++ constructor is implicitly called by GNAT, or
6043 else the required C++ constructor must be explicitly called in the
6044 expression that initializes the object. For example:
6046 @example
6047 Obj1 : Root;
6048 Obj2 : Root := Constructor;
6049 Obj3 : Root := Constructor (v => 10);
6050 Obj4 : Root := Constructor (30, 40);
6051 @end example
6053 The first two declarations are equivalent: in both cases the default C++
6054 constructor is invoked (in the former case the call to the constructor is
6055 implicit, and in the latter case the call is explicit in the object
6056 declaration). @code{Obj3} is initialized by the C++ non-default constructor
6057 that takes an integer argument, and @code{Obj4} is initialized by the
6058 non-default C++ constructor that takes two integers.
6060 Let us derive the imported C++ class in the Ada side. For example:
6062 @example
6063 type DT is new Root with record
6064    C_Value : Natural := 2009;
6065 end record;
6066 @end example
6068 In this case the components DT inherited from the C++ side must be
6069 initialized by a C++ constructor, and the additional Ada components
6070 of type DT are initialized by GNAT. The initialization of such an
6071 object is done either by default, or by means of a function returning
6072 an aggregate of type DT, or by means of an extension aggregate.
6074 @example
6075 Obj5 : DT;
6076 Obj6 : DT := Function_Returning_DT (50);
6077 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6078 @end example
6080 The declaration of @code{Obj5} invokes the default constructors: the
6081 C++ default constructor of the parent type takes care of the initialization
6082 of the components inherited from Root, and GNAT takes care of the default
6083 initialization of the additional Ada components of type DT (that is,
6084 @code{C_Value} is initialized to value 2009). The order of invocation of
6085 the constructors is consistent with the order of elaboration required by
6086 Ada and C++. That is, the constructor of the parent type is always called
6087 before the constructor of the derived type.
6089 Let us now consider a record that has components whose type is imported
6090 from C++. For example:
6092 @example
6093 type Rec1 is limited record
6094    Data1 : Root := Constructor (10);
6095    Value : Natural := 1000;
6096 end record;
6098 type Rec2 (D : Integer := 20) is limited record
6099    Rec   : Rec1;
6100    Data2 : Root := Constructor (D, 30);
6101 end record;
6102 @end example
6104 The initialization of an object of type @code{Rec2} will call the
6105 non-default C++ constructors specified for the imported components.
6106 For example:
6108 @example
6109 Obj8 : Rec2 (40);
6110 @end example
6112 Using Ada 2005 we can use limited aggregates to initialize an object
6113 invoking C++ constructors that differ from those specified in the type
6114 declarations. For example:
6116 @example
6117 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6118                         others => <>),
6119                 others => <>);
6120 @end example
6122 The above declaration uses an Ada 2005 limited aggregate to
6123 initialize @code{Obj9}, and the C++ constructor that has two integer
6124 arguments is invoked to initialize the @code{Data1} component instead
6125 of the constructor specified in the declaration of type @code{Rec1}. In
6126 Ada 2005 the box in the aggregate indicates that unspecified components
6127 are initialized using the expression (if any) available in the component
6128 declaration. That is, in this case discriminant @code{D} is initialized
6129 to value @code{20}, @code{Value} is initialized to value 1000, and the
6130 non-default C++ constructor that handles two integers takes care of
6131 initializing component @code{Data2} with values @code{20,30}.
6133 In Ada 2005 we can use the extended return statement to build the Ada
6134 equivalent to C++ non-default constructors. For example:
6136 @example
6137 function Constructor (V : Integer) return Rec2 is
6138 begin
6139    return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
6140                                  others => <>),
6141                          others => <>) do
6142       --  Further actions required for construction of
6143       --  objects of type Rec2
6144       ...
6145    end record;
6146 end Constructor;
6147 @end example
6149 In this example the extended return statement construct is used to
6150 build in place the returned object whose components are initialized
6151 by means of a limited aggregate. Any further action associated with
6152 the constructor can be placed inside the construct.
6154 @node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6155 @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}
6156 @subsubsection Interfacing with C++ at the Class Level
6159 In this section we demonstrate the GNAT features for interfacing with
6160 C++ by means of an example making use of Ada 2005 abstract interface
6161 types. This example consists of a classification of animals; classes
6162 have been used to model our main classification of animals, and
6163 interfaces provide support for the management of secondary
6164 classifications. We first demonstrate a case in which the types and
6165 constructors are defined on the C++ side and imported from the Ada
6166 side, and latter the reverse case.
6168 The root of our derivation will be the @code{Animal} class, with a
6169 single private attribute (the @code{Age} of the animal), a constructor,
6170 and two public primitives to set and get the value of this attribute.
6172 @example
6173 class Animal @{
6174  public:
6175    virtual void Set_Age (int New_Age);
6176    virtual int Age ();
6177    Animal() @{Age_Count = 0;@};
6178  private:
6179    int Age_Count;
6181 @end example
6183 Abstract interface types are defined in C++ by means of classes with pure
6184 virtual functions and no data members. In our example we will use two
6185 interfaces that provide support for the common management of @code{Carnivore}
6186 and @code{Domestic} animals:
6188 @example
6189 class Carnivore @{
6190 public:
6191    virtual int Number_Of_Teeth () = 0;
6194 class Domestic @{
6195 public:
6196    virtual void Set_Owner (char* Name) = 0;
6198 @end example
6200 Using these declarations, we can now say that a @code{Dog} is an animal that is
6201 both Carnivore and Domestic, that is:
6203 @example
6204 class Dog : Animal, Carnivore, Domestic @{
6205  public:
6206    virtual int  Number_Of_Teeth ();
6207    virtual void Set_Owner (char* Name);
6209    Dog(); // Constructor
6210  private:
6211    int  Tooth_Count;
6212    char *Owner;
6214 @end example
6216 In the following examples we will assume that the previous declarations are
6217 located in a file named @code{animals.h}. The following package demonstrates
6218 how to import these C++ declarations from the Ada side:
6220 @example
6221 with Interfaces.C.Strings; use Interfaces.C.Strings;
6222 package Animals is
6223   type Carnivore is limited interface;
6224   pragma Convention (C_Plus_Plus, Carnivore);
6225   function Number_Of_Teeth (X : Carnivore)
6226      return Natural is abstract;
6228   type Domestic is limited interface;
6229   pragma Convention (C_Plus_Plus, Domestic);
6230   procedure Set_Owner
6231     (X    : in out Domestic;
6232      Name : Chars_Ptr) is abstract;
6234   type Animal is tagged limited record
6235     Age : Natural;
6236   end record;
6237   pragma Import (C_Plus_Plus, Animal);
6239   procedure Set_Age (X : in out Animal; Age : Integer);
6240   pragma Import (C_Plus_Plus, Set_Age);
6242   function Age (X : Animal) return Integer;
6243   pragma Import (C_Plus_Plus, Age);
6245   function New_Animal return Animal;
6246   pragma CPP_Constructor (New_Animal);
6247   pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6249   type Dog is new Animal and Carnivore and Domestic with record
6250     Tooth_Count : Natural;
6251     Owner       : Chars_Ptr;
6252   end record;
6253   pragma Import (C_Plus_Plus, Dog);
6255   function Number_Of_Teeth (A : Dog) return Natural;
6256   pragma Import (C_Plus_Plus, Number_Of_Teeth);
6258   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6259   pragma Import (C_Plus_Plus, Set_Owner);
6261   function New_Dog return Dog;
6262   pragma CPP_Constructor (New_Dog);
6263   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6264 end Animals;
6265 @end example
6267 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6268 interfacing with these C++ classes is easy. The only requirement is that all
6269 the primitives and components must be declared exactly in the same order in
6270 the two languages.
6272 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6273 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
6274 the arguments to the called primitives will be the same as for C++. For the
6275 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
6276 to indicate that they have been defined on the C++ side; this is required
6277 because the dispatch table associated with these tagged types will be built
6278 in the C++ side and therefore will not contain the predefined Ada primitives
6279 which Ada would otherwise expect.
6281 As the reader can see there is no need to indicate the C++ mangled names
6282 associated with each subprogram because it is assumed that all the calls to
6283 these primitives will be dispatching calls. The only exception is the
6284 constructor, which must be registered with the compiler by means of
6285 @code{pragma CPP_Constructor} and needs to provide its associated C++
6286 mangled name because the Ada compiler generates direct calls to it.
6288 With the above packages we can now declare objects of type Dog on the Ada side
6289 and dispatch calls to the corresponding subprograms on the C++ side. We can
6290 also extend the tagged type Dog with further fields and primitives, and
6291 override some of its C++ primitives on the Ada side. For example, here we have
6292 a type derivation defined on the Ada side that inherits all the dispatching
6293 primitives of the ancestor from the C++ side.
6295 @example
6296 with Animals; use Animals;
6297 package Vaccinated_Animals is
6298   type Vaccinated_Dog is new Dog with null record;
6299   function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6300 end Vaccinated_Animals;
6301 @end example
6303 It is important to note that, because of the ABI compatibility, the programmer
6304 does not need to add any further information to indicate either the object
6305 layout or the dispatch table entry associated with each dispatching operation.
6307 Now let us define all the types and constructors on the Ada side and export
6308 them to C++, using the same hierarchy of our previous example:
6310 @example
6311 with Interfaces.C.Strings;
6312 use Interfaces.C.Strings;
6313 package Animals is
6314   type Carnivore is limited interface;
6315   pragma Convention (C_Plus_Plus, Carnivore);
6316   function Number_Of_Teeth (X : Carnivore)
6317      return Natural is abstract;
6319   type Domestic is limited interface;
6320   pragma Convention (C_Plus_Plus, Domestic);
6321   procedure Set_Owner
6322     (X    : in out Domestic;
6323      Name : Chars_Ptr) is abstract;
6325   type Animal is tagged record
6326     Age : Natural;
6327   end record;
6328   pragma Convention (C_Plus_Plus, Animal);
6330   procedure Set_Age (X : in out Animal; Age : Integer);
6331   pragma Export (C_Plus_Plus, Set_Age);
6333   function Age (X : Animal) return Integer;
6334   pragma Export (C_Plus_Plus, Age);
6336   function New_Animal return Animal'Class;
6337   pragma Export (C_Plus_Plus, New_Animal);
6339   type Dog is new Animal and Carnivore and Domestic with record
6340     Tooth_Count : Natural;
6341     Owner       : String (1 .. 30);
6342   end record;
6343   pragma Convention (C_Plus_Plus, Dog);
6345   function Number_Of_Teeth (A : Dog) return Natural;
6346   pragma Export (C_Plus_Plus, Number_Of_Teeth);
6348   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6349   pragma Export (C_Plus_Plus, Set_Owner);
6351   function New_Dog return Dog'Class;
6352   pragma Export (C_Plus_Plus, New_Dog);
6353 end Animals;
6354 @end example
6356 Compared with our previous example the only differences are the use of
6357 @code{pragma Convention} (instead of @code{pragma Import}), and the use of
6358 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
6359 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6360 nothing else to be done; as explained above, the only requirement is that all
6361 the primitives and components are declared in exactly the same order.
6363 For completeness, let us see a brief C++ main program that uses the
6364 declarations available in @code{animals.h} (presented in our first example) to
6365 import and use the declarations from the Ada side, properly initializing and
6366 finalizing the Ada run-time system along the way:
6368 @example
6369 #include "animals.h"
6370 #include <iostream>
6371 using namespace std;
6373 void Check_Carnivore (Carnivore *obj) @{...@}
6374 void Check_Domestic (Domestic *obj)   @{...@}
6375 void Check_Animal (Animal *obj)       @{...@}
6376 void Check_Dog (Dog *obj)             @{...@}
6378 extern "C" @{
6379   void adainit (void);
6380   void adafinal (void);
6381   Dog* new_dog ();
6384 void test ()
6386   Dog *obj = new_dog();  // Ada constructor
6387   Check_Carnivore (obj); // Check secondary DT
6388   Check_Domestic (obj);  // Check secondary DT
6389   Check_Animal (obj);    // Check primary DT
6390   Check_Dog (obj);       // Check primary DT
6393 int main ()
6395   adainit ();  test();  adafinal ();
6396   return 0;
6398 @end example
6400 @node Partition-Wide Settings,Generating Ada Bindings for C and C++ headers,Building Mixed Ada and C++ Programs,Mixed Language Programming
6401 @anchor{gnat_ugn/the_gnat_compilation_model id70}@anchor{b0}@anchor{gnat_ugn/the_gnat_compilation_model partition-wide-settings}@anchor{b1}
6402 @subsection Partition-Wide Settings
6405 When building a mixed-language application it is important to be aware that
6406 Ada enforces some partition-wide settings that may implicitly impact the
6407 behavior of the other languages.
6409 This is the case of certain signals that are reserved to the
6410 implementation to implement proper Ada semantics (such as the behavior
6411 of @code{abort} statements).
6413 It means that the Ada part of the application may override signal handlers
6414 that were previously installed by either the system or by other user code.
6416 If your application requires that either system or user signals be preserved
6417 then you need to instruct the Ada part not to install its own signal handler.
6418 This is done using @code{pragma Interrupt_State} that provides a general
6419 mechanism for overriding such uses of interrupts.
6421 The set of interrupts for which the Ada run-time library sets a specific signal
6422 handler is the following:
6425 @itemize *
6427 @item 
6428 Ada.Interrupts.Names.SIGSEGV
6430 @item 
6431 Ada.Interrupts.Names.SIGBUS
6433 @item 
6434 Ada.Interrupts.Names.SIGFPE
6436 @item 
6437 Ada.Interrupts.Names.SIGILL
6439 @item 
6440 Ada.Interrupts.Names.SIGABRT
6441 @end itemize
6443 The run-time library can be instructed not to install its signal handler for a
6444 particular signal by using the configuration pragma @code{Interrupt_State} in the
6445 Ada code. For example:
6447 @example
6448 pragma Interrupt_State (Ada.Interrupts.Names.SIGSEGV, System);
6449 pragma Interrupt_State (Ada.Interrupts.Names.SIGBUS,  System);
6450 pragma Interrupt_State (Ada.Interrupts.Names.SIGFPE,  System);
6451 pragma Interrupt_State (Ada.Interrupts.Names.SIGILL,  System);
6452 pragma Interrupt_State (Ada.Interrupts.Names.SIGABRT, System);
6453 @end example
6455 Obviously, if the Ada run-time system cannot set these handlers it comes with the
6456 drawback of not fully preserving Ada semantics. @code{SIGSEGV}, @code{SIGBUS}, @code{SIGFPE}
6457 and @code{SIGILL} are used to raise corresponding Ada exceptions in the application,
6458 while @code{SIGABRT} is used to asynchronously abort an action or a task.
6460 @node Generating Ada Bindings for C and C++ headers,Generating C Headers for Ada Specifications,Partition-Wide Settings,Mixed Language Programming
6461 @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}
6462 @subsection Generating Ada Bindings for C and C++ headers
6465 @geindex Binding generation (for C and C++ headers)
6467 @geindex C headers (binding generation)
6469 @geindex C++ headers (binding generation)
6471 GNAT includes a binding generator for C and C++ headers which is
6472 intended to do 95% of the tedious work of generating Ada specs from C
6473 or C++ header files.
6475 Note that this capability is not intended to generate 100% correct Ada specs,
6476 and will is some cases require manual adjustments, although it can often
6477 be used out of the box in practice.
6479 Some of the known limitations include:
6482 @itemize *
6484 @item 
6485 only very simple character constant macros are translated into Ada
6486 constants. Function macros (macros with arguments) are partially translated
6487 as comments, to be completed manually if needed.
6489 @item 
6490 some extensions (e.g. vector types) are not supported
6492 @item 
6493 pointers to pointers are mapped to System.Address
6495 @item 
6496 identifiers with identical name (except casing) may generate compilation
6497 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
6498 @end itemize
6500 The code is generated using Ada 2012 syntax, which makes it easier to interface
6501 with other languages. In most cases you can still use the generated binding
6502 even if your code is compiled using earlier versions of Ada (e.g. @code{-gnat95}).
6504 @menu
6505 * Running the Binding Generator:: 
6506 * Generating Bindings for C++ Headers:: 
6507 * Switches:: 
6509 @end menu
6511 @node Running the Binding Generator,Generating Bindings for C++ Headers,,Generating Ada Bindings for C and C++ headers
6512 @anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{b3}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{b4}
6513 @subsubsection Running the Binding Generator
6516 The binding generator is part of the @code{gcc} compiler and can be
6517 invoked via the @code{-fdump-ada-spec} switch, which will generate Ada
6518 spec files for the header files specified on the command line, and all
6519 header files needed by these files transitively. For example:
6521 @example
6522 $ gcc -c -fdump-ada-spec -C /usr/include/time.h
6523 $ gcc -c *.ads
6524 @end example
6526 will generate, under GNU/Linux, the following files: @code{time_h.ads},
6527 @code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6528 correspond to the files @code{/usr/include/time.h},
6529 @code{/usr/include/bits/time.h}, etc…, and then compile these Ada specs.
6530 That is to say, the name of the Ada specs is in keeping with the relative path
6531 under @code{/usr/include/} of the header files. This behavior is specific to
6532 paths ending with @code{/include/}; in all the other cases, the name of the
6533 Ada specs is derived from the simple name of the header files instead.
6535 The @code{-C} switch tells @code{gcc} to extract comments from headers,
6536 and will attempt to generate corresponding Ada comments.
6538 If you want to generate a single Ada file and not the transitive closure, you
6539 can use instead the @code{-fdump-ada-spec-slim} switch.
6541 You can optionally specify a parent unit, of which all generated units will
6542 be children, using @code{-fada-spec-parent=@emph{unit}}.
6544 The simple @code{gcc}-based command works only for C headers. For C++ headers
6545 you need to use either the @code{g++} command or the combination @code{gcc -x c++}.
6547 In some cases, the generated bindings will be more complete or more meaningful
6548 when defining some macros, which you can do via the @code{-D} switch. This
6549 is for example the case with @code{Xlib.h} under GNU/Linux:
6551 @example
6552 $ gcc -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6553 @end example
6555 The above will generate more complete bindings than a straight call without
6556 the @code{-DXLIB_ILLEGAL_ACCESS} switch.
6558 In other cases, it is not possible to parse a header file in a stand-alone
6559 manner, because other include files need to be included first. In this
6560 case, the solution is to create a small header file including the needed
6561 @code{#include} and possible @code{#define} directives. For example, to
6562 generate Ada bindings for @code{readline/readline.h}, you need to first
6563 include @code{stdio.h}, so you can create a file with the following two
6564 lines in e.g. @code{readline1.h}:
6566 @example
6567 #include <stdio.h>
6568 #include <readline/readline.h>
6569 @end example
6571 and then generate Ada bindings from this file:
6573 @example
6574 $ gcc -c -fdump-ada-spec readline1.h
6575 @end example
6577 @node Generating Bindings for C++ Headers,Switches,Running the Binding Generator,Generating Ada Bindings for C and C++ headers
6578 @anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{b5}@anchor{gnat_ugn/the_gnat_compilation_model id73}@anchor{b6}
6579 @subsubsection Generating Bindings for C++ Headers
6582 Generating bindings for C++ headers is done using the same options, always
6583 with the @emph{g++} compiler. Note that generating Ada spec from C++ headers is a
6584 much more complex job and support for C++ headers is much more limited that
6585 support for C headers. As a result, you will need to modify the resulting
6586 bindings by hand more extensively when using C++ headers.
6588 In this mode, C++ classes will be mapped to Ada tagged types, constructors
6589 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
6590 multiple inheritance of abstract classes will be mapped to Ada interfaces
6591 (see the @emph{Interfacing to C++} section in the @cite{GNAT Reference Manual}
6592 for additional information on interfacing to C++).
6594 For example, given the following C++ header file:
6596 @example
6597 class Carnivore @{
6598 public:
6599    virtual int Number_Of_Teeth () = 0;
6602 class Domestic @{
6603 public:
6604    virtual void Set_Owner (char* Name) = 0;
6607 class Animal @{
6608 public:
6609   int Age_Count;
6610   virtual void Set_Age (int New_Age);
6613 class Dog : Animal, Carnivore, Domestic @{
6614  public:
6615   int  Tooth_Count;
6616   char *Owner;
6618   virtual int  Number_Of_Teeth ();
6619   virtual void Set_Owner (char* Name);
6621   Dog();
6623 @end example
6625 The corresponding Ada code is generated:
6627 @example
6628 package Class_Carnivore is
6629   type Carnivore is limited interface;
6630   pragma Import (CPP, Carnivore);
6632   function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6633 end;
6634 use Class_Carnivore;
6636 package Class_Domestic is
6637   type Domestic is limited interface;
6638   pragma Import (CPP, Domestic);
6640   procedure Set_Owner
6641     (this : access Domestic;
6642      Name : Interfaces.C.Strings.chars_ptr) is abstract;
6643 end;
6644 use Class_Domestic;
6646 package Class_Animal is
6647   type Animal is tagged limited record
6648     Age_Count : aliased int;
6649   end record;
6650   pragma Import (CPP, Animal);
6652   procedure Set_Age (this : access Animal; New_Age : int);
6653   pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6654 end;
6655 use Class_Animal;
6657 package Class_Dog is
6658   type Dog is new Animal and Carnivore and Domestic with record
6659     Tooth_Count : aliased int;
6660     Owner : Interfaces.C.Strings.chars_ptr;
6661   end record;
6662   pragma Import (CPP, Dog);
6664   function Number_Of_Teeth (this : access Dog) return int;
6665   pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6667   procedure Set_Owner
6668     (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6669   pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6671   function New_Dog return Dog;
6672   pragma CPP_Constructor (New_Dog);
6673   pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6674 end;
6675 use Class_Dog;
6676 @end example
6678 @node Switches,,Generating Bindings for C++ Headers,Generating Ada Bindings for C and C++ headers
6679 @anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{b7}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{b8}
6680 @subsubsection Switches
6683 @geindex -fdump-ada-spec (gcc)
6686 @table @asis
6688 @item @code{-fdump-ada-spec}
6690 Generate Ada spec files for the given header files transitively (including
6691 all header files that these headers depend upon).
6692 @end table
6694 @geindex -fdump-ada-spec-slim (gcc)
6697 @table @asis
6699 @item @code{-fdump-ada-spec-slim}
6701 Generate Ada spec files for the header files specified on the command line
6702 only.
6703 @end table
6705 @geindex -fada-spec-parent (gcc)
6708 @table @asis
6710 @item @code{-fada-spec-parent=@emph{unit}}
6712 Specifies that all files generated by @code{-fdump-ada-spec} are
6713 to be child units of the specified parent unit.
6714 @end table
6716 @geindex -C (gcc)
6719 @table @asis
6721 @item @code{-C}
6723 Extract comments from headers and generate Ada comments in the Ada spec files.
6724 @end table
6726 @node Generating C Headers for Ada Specifications,,Generating Ada Bindings for C and C++ headers,Mixed Language Programming
6727 @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}
6728 @subsection Generating C Headers for Ada Specifications
6731 @geindex Binding generation (for Ada specs)
6733 @geindex C headers (binding generation)
6735 GNAT includes a C header generator for Ada specifications which supports
6736 Ada types that have a direct mapping to C types. This includes in particular
6737 support for:
6740 @itemize *
6742 @item 
6743 Scalar types
6745 @item 
6746 Constrained arrays
6748 @item 
6749 Records (untagged)
6751 @item 
6752 Composition of the above types
6754 @item 
6755 Constant declarations
6757 @item 
6758 Object declarations
6760 @item 
6761 Subprogram declarations
6762 @end itemize
6764 @menu
6765 * Running the C Header Generator:: 
6767 @end menu
6769 @node Running the C Header Generator,,,Generating C Headers for Ada Specifications
6770 @anchor{gnat_ugn/the_gnat_compilation_model running-the-c-header-generator}@anchor{bb}
6771 @subsubsection Running the C Header Generator
6774 The C header generator is part of the GNAT compiler and can be invoked via
6775 the @code{-gnatceg} combination of switches, which will generate a @code{.h}
6776 file corresponding to the given input file (Ada spec or body). Note that
6777 only spec files are processed in any case, so giving a spec or a body file
6778 as input is equivalent. For example:
6780 @example
6781 $ gcc -c -gnatceg pack1.ads
6782 @end example
6784 will generate a self-contained file called @code{pack1.h} including
6785 common definitions from the Ada Standard package, followed by the
6786 definitions included in @code{pack1.ads}, as well as all the other units
6787 withed by this file.
6789 For instance, given the following Ada files:
6791 @example
6792 package Pack2 is
6793    type Int is range 1 .. 10;
6794 end Pack2;
6795 @end example
6797 @example
6798 with Pack2;
6800 package Pack1 is
6801    type Rec is record
6802       Field1, Field2 : Pack2.Int;
6803    end record;
6805    Global : Rec := (1, 2);
6807    procedure Proc1 (R : Rec);
6808    procedure Proc2 (R : in out Rec);
6809 end Pack1;
6810 @end example
6812 The above @code{gcc} command will generate the following @code{pack1.h} file:
6814 @example
6815 /* Standard definitions skipped */
6816 #ifndef PACK2_ADS
6817 #define PACK2_ADS
6818 typedef short_short_integer pack2__TintB;
6819 typedef pack2__TintB pack2__int;
6820 #endif /* PACK2_ADS */
6822 #ifndef PACK1_ADS
6823 #define PACK1_ADS
6824 typedef struct _pack1__rec @{
6825   pack2__int field1;
6826   pack2__int field2;
6827 @} pack1__rec;
6828 extern pack1__rec pack1__global;
6829 extern void pack1__proc1(const pack1__rec r);
6830 extern void pack1__proc2(pack1__rec *r);
6831 #endif /* PACK1_ADS */
6832 @end example
6834 You can then @code{include} @code{pack1.h} from a C source file and use the types,
6835 call subprograms, reference objects, and constants.
6837 @node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
6838 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{2d}@anchor{gnat_ugn/the_gnat_compilation_model id75}@anchor{bc}
6839 @section GNAT and Other Compilation Models
6842 This section compares the GNAT model with the approaches taken in
6843 other environments, first the C/C++ model and then the mechanism that
6844 has been used in other Ada systems, in particular those traditionally
6845 used for Ada 83.
6847 @menu
6848 * Comparison between GNAT and C/C++ Compilation Models:: 
6849 * Comparison between GNAT and Conventional Ada Library Models:: 
6851 @end menu
6853 @node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
6854 @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}
6855 @subsection Comparison between GNAT and C/C++ Compilation Models
6858 The GNAT model of compilation is close to the C and C++ models. You can
6859 think of Ada specs as corresponding to header files in C. As in C, you
6860 don’t need to compile specs; they are compiled when they are used. The
6861 Ada @emph{with} is similar in effect to the @code{#include} of a C
6862 header.
6864 One notable difference is that, in Ada, you may compile specs separately
6865 to check them for semantic and syntactic accuracy. This is not always
6866 possible with C headers because they are fragments of programs that have
6867 less specific syntactic or semantic rules.
6869 The other major difference is the requirement for running the binder,
6870 which performs two important functions. First, it checks for
6871 consistency. In C or C++, the only defense against assembling
6872 inconsistent programs lies outside the compiler, in a makefile, for
6873 example. The binder satisfies the Ada requirement that it be impossible
6874 to construct an inconsistent program when the compiler is used in normal
6875 mode.
6877 @geindex Elaboration order control
6879 The other important function of the binder is to deal with elaboration
6880 issues. There are also elaboration issues in C++ that are handled
6881 automatically. This automatic handling has the advantage of being
6882 simpler to use, but the C++ programmer has no control over elaboration.
6883 Where @code{gnatbind} might complain there was no valid order of
6884 elaboration, a C++ compiler would simply construct a program that
6885 malfunctioned at run time.
6887 @node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
6888 @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}
6889 @subsection Comparison between GNAT and Conventional Ada Library Models
6892 This section is intended for Ada programmers who have
6893 used an Ada compiler implementing the traditional Ada library
6894 model, as described in the Ada Reference Manual.
6896 @geindex GNAT library
6898 In GNAT, there is no ‘library’ in the normal sense. Instead, the set of
6899 source files themselves acts as the library. Compiling Ada programs does
6900 not generate any centralized information, but rather an object file and
6901 a ALI file, which are of interest only to the binder and linker.
6902 In a traditional system, the compiler reads information not only from
6903 the source file being compiled, but also from the centralized library.
6904 This means that the effect of a compilation depends on what has been
6905 previously compiled. In particular:
6908 @itemize *
6910 @item 
6911 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
6912 to the version of the unit most recently compiled into the library.
6914 @item 
6915 Inlining is effective only if the necessary body has already been
6916 compiled into the library.
6918 @item 
6919 Compiling a unit may obsolete other units in the library.
6920 @end itemize
6922 In GNAT, compiling one unit never affects the compilation of any other
6923 units because the compiler reads only source files. Only changes to source
6924 files can affect the results of a compilation. In particular:
6927 @itemize *
6929 @item 
6930 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
6931 to the source version of the unit that is currently accessible to the
6932 compiler.
6934 @geindex Inlining
6936 @item 
6937 Inlining requires the appropriate source files for the package or
6938 subprogram bodies to be available to the compiler. Inlining is always
6939 effective, independent of the order in which units are compiled.
6941 @item 
6942 Compiling a unit never affects any other compilations. The editing of
6943 sources may cause previous compilations to be out of date if they
6944 depended on the source file being modified.
6945 @end itemize
6947 The most important result of these differences is that order of compilation
6948 is never significant in GNAT. There is no situation in which one is
6949 required to do one compilation before another. What shows up as order of
6950 compilation requirements in the traditional Ada library becomes, in
6951 GNAT, simple source dependencies; in other words, there is only a set
6952 of rules saying what source files must be present when a file is
6953 compiled.
6955 @node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
6956 @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}
6957 @section Using GNAT Files with External Tools
6960 This section explains how files that are produced by GNAT may be
6961 used with tools designed for other languages.
6963 @menu
6964 * Using Other Utility Programs with GNAT:: 
6965 * The External Symbol Naming Scheme of GNAT:: 
6967 @end menu
6969 @node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
6970 @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}
6971 @subsection Using Other Utility Programs with GNAT
6974 The object files generated by GNAT are in standard system format and in
6975 particular the debugging information uses this format. This means
6976 programs generated by GNAT can be used with existing utilities that
6977 depend on these formats.
6979 In general, any utility program that works with C will also often work with
6980 Ada programs generated by GNAT. This includes software utilities such as
6981 gprof (a profiling program), gdb (the FSF debugger), and utilities such
6982 as Purify.
6984 @node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
6985 @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}
6986 @subsection The External Symbol Naming Scheme of GNAT
6989 In order to interpret the output from GNAT, when using tools that are
6990 originally intended for use with other languages, it is useful to
6991 understand the conventions used to generate link names from the Ada
6992 entity names.
6994 All link names are in all lowercase letters. With the exception of library
6995 procedure names, the mechanism used is simply to use the full expanded
6996 Ada name with dots replaced by double underscores. For example, suppose
6997 we have the following package spec:
6999 @example
7000 package QRS is
7001    MN : Integer;
7002 end QRS;
7003 @end example
7005 @geindex pragma Export
7007 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
7008 the corresponding link name is @code{qrs__mn}.
7009 Of course if a @code{pragma Export} is used this may be overridden:
7011 @example
7012 package Exports is
7013    Var1 : Integer;
7014    pragma Export (Var1, C, External_Name => "var1_name");
7015    Var2 : Integer;
7016    pragma Export (Var2, C, Link_Name => "var2_link_name");
7017 end Exports;
7018 @end example
7020 In this case, the link name for @code{Var1} is whatever link name the
7021 C compiler would assign for the C function @code{var1_name}. This typically
7022 would be either @code{var1_name} or @code{_var1_name}, depending on operating
7023 system conventions, but other possibilities exist. The link name for
7024 @code{Var2} is @code{var2_link_name}, and this is not operating system
7025 dependent.
7027 One exception occurs for library level procedures. A potential ambiguity
7028 arises between the required name @code{_main} for the C main program,
7029 and the name we would otherwise assign to an Ada library level procedure
7030 called @code{Main} (which might well not be the main program).
7032 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
7033 names. So if we have a library level procedure such as:
7035 @example
7036 procedure Hello (S : String);
7037 @end example
7039 the external name of this procedure will be @code{_ada_hello}.
7041 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7043 @node Building Executable Programs with GNAT,GNAT Utility Programs,The GNAT Compilation Model,Top
7044 @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}
7045 @chapter Building Executable Programs with GNAT
7048 This chapter describes first the gnatmake tool
7049 (@ref{c8,,Building with gnatmake}),
7050 which automatically determines the set of sources
7051 needed by an Ada compilation unit and executes the necessary
7052 (re)compilations, binding and linking.
7053 It also explains how to use each tool individually: the
7054 compiler (gcc, see @ref{c9,,Compiling with gcc}),
7055 binder (gnatbind, see @ref{ca,,Binding with gnatbind}),
7056 and linker (gnatlink, see @ref{cb,,Linking with gnatlink})
7057 to build executable programs.
7058 Finally, this chapter provides examples of
7059 how to make use of the general GNU make mechanism
7060 in a GNAT context (see @ref{70,,Using the GNU make Utility}).
7063 @menu
7064 * Building with gnatmake:: 
7065 * Compiling with gcc:: 
7066 * Compiler Switches:: 
7067 * Linker Switches:: 
7068 * Binding with gnatbind:: 
7069 * Linking with gnatlink:: 
7070 * Using the GNU make Utility:: 
7072 @end menu
7074 @node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
7075 @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}
7076 @section Building with @code{gnatmake}
7079 @geindex gnatmake
7081 A typical development cycle when working on an Ada program consists of
7082 the following steps:
7085 @enumerate 
7087 @item 
7088 Edit some sources to fix bugs;
7090 @item 
7091 Add enhancements;
7093 @item 
7094 Compile all sources affected;
7096 @item 
7097 Rebind and relink; and
7099 @item 
7100 Test.
7101 @end enumerate
7103 @geindex Dependency rules (compilation)
7105 The third step in particular can be tricky, because not only do the modified
7106 files have to be compiled, but any files depending on these files must also be
7107 recompiled. The dependency rules in Ada can be quite complex, especially
7108 in the presence of overloading, @code{use} clauses, generics and inlined
7109 subprograms.
7111 @code{gnatmake} automatically takes care of the third and fourth steps
7112 of this process. It determines which sources need to be compiled,
7113 compiles them, and binds and links the resulting object files.
7115 Unlike some other Ada make programs, the dependencies are always
7116 accurately recomputed from the new sources. The source based approach of
7117 the GNAT compilation model makes this possible. This means that if
7118 changes to the source program cause corresponding changes in
7119 dependencies, they will always be tracked exactly correctly by
7120 @code{gnatmake}.
7122 Note that for advanced forms of project structure, we recommend creating
7123 a project file as explained in the @emph{GNAT_Project_Manager} chapter in the
7124 @emph{GPRbuild User’s Guide}, and using the
7125 @code{gprbuild} tool which supports building with project files and works similarly
7126 to @code{gnatmake}.
7128 @menu
7129 * Running gnatmake:: 
7130 * Switches for gnatmake:: 
7131 * Mode Switches for gnatmake:: 
7132 * Notes on the Command Line:: 
7133 * How gnatmake Works:: 
7134 * Examples of gnatmake Usage:: 
7136 @end menu
7138 @node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7139 @anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{cd}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{ce}
7140 @subsection Running @code{gnatmake}
7143 The usual form of the @code{gnatmake} command is
7145 @example
7146 $ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7147 @end example
7149 The only required argument is one @code{file_name}, which specifies
7150 a compilation unit that is a main program. Several @code{file_names} can be
7151 specified: this will result in several executables being built.
7152 If @code{switches} are present, they can be placed before the first
7153 @code{file_name}, between @code{file_names} or after the last @code{file_name}.
7154 If @code{mode_switches} are present, they must always be placed after
7155 the last @code{file_name} and all @code{switches}.
7157 If you are using standard file extensions (@code{.adb} and
7158 @code{.ads}), then the
7159 extension may be omitted from the @code{file_name} arguments. However, if
7160 you are using non-standard extensions, then it is required that the
7161 extension be given. A relative or absolute directory path can be
7162 specified in a @code{file_name}, in which case, the input source file will
7163 be searched for in the specified directory only. Otherwise, the input
7164 source file will first be searched in the directory where
7165 @code{gnatmake} was invoked and if it is not found, it will be search on
7166 the source path of the compiler as described in
7167 @ref{73,,Search Paths and the Run-Time Library (RTL)}.
7169 All @code{gnatmake} output (except when you specify @code{-M}) is sent to
7170 @code{stderr}. The output produced by the
7171 @code{-M} switch is sent to @code{stdout}.
7173 @node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7174 @anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{cf}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{d0}
7175 @subsection Switches for @code{gnatmake}
7178 You may specify any of the following switches to @code{gnatmake}:
7180 @geindex --version (gnatmake)
7183 @table @asis
7185 @item @code{--version}
7187 Display Copyright and version, then exit disregarding all other options.
7188 @end table
7190 @geindex --help (gnatmake)
7193 @table @asis
7195 @item @code{--help}
7197 If @code{--version} was not used, display usage, then exit disregarding
7198 all other options.
7199 @end table
7201 @geindex -P (gnatmake)
7204 @table @asis
7206 @item @code{-P@emph{project}}
7208 Build GNAT project file @code{project} using GPRbuild. When this switch is
7209 present, all other command-line switches are treated as GPRbuild switches
7210 and not @code{gnatmake} switches.
7211 @end table
7213 @c -- Comment:
7214 @c :ref:`gnatmake_and_Project_Files`.
7216 @geindex --GCC=compiler_name (gnatmake)
7219 @table @asis
7221 @item @code{--GCC=@emph{compiler_name}}
7223 Program used for compiling. The default is @code{gcc}. You need to use
7224 quotes around @code{compiler_name} if @code{compiler_name} contains
7225 spaces or other separator characters.
7226 As an example @code{--GCC="foo -x  -y"}
7227 will instruct @code{gnatmake} to use @code{foo -x -y} as your
7228 compiler. A limitation of this syntax is that the name and path name of
7229 the executable itself must not include any embedded spaces. Note that
7230 switch @code{-c} is always inserted after your command name. Thus in the
7231 above example the compiler command that will be used by @code{gnatmake}
7232 will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7233 used, only the last @code{compiler_name} is taken into account. However,
7234 all the additional switches are also taken into account. Thus,
7235 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7236 @code{--GCC="bar -x -y -z -t"}.
7237 @end table
7239 @geindex --GNATBIND=binder_name (gnatmake)
7242 @table @asis
7244 @item @code{--GNATBIND=@emph{binder_name}}
7246 Program used for binding. The default is @code{gnatbind}. You need to
7247 use quotes around @code{binder_name} if @code{binder_name} contains spaces
7248 or other separator characters.
7249 As an example @code{--GNATBIND="bar -x  -y"}
7250 will instruct @code{gnatmake} to use @code{bar -x -y} as your
7251 binder. Binder switches that are normally appended by @code{gnatmake}
7252 to @code{gnatbind} are now appended to the end of @code{bar -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.
7255 @end table
7257 @geindex --GNATLINK=linker_name (gnatmake)
7260 @table @asis
7262 @item @code{--GNATLINK=@emph{linker_name}}
7264 Program used for linking. The default is @code{gnatlink}. You need to
7265 use quotes around @code{linker_name} if @code{linker_name} contains spaces
7266 or other separator characters.
7267 As an example @code{--GNATLINK="lan -x  -y"}
7268 will instruct @code{gnatmake} to use @code{lan -x -y} as your
7269 linker. Linker switches that are normally appended by @code{gnatmake} to
7270 @code{gnatlink} are now appended to the end of @code{lan -x -y}.
7271 A limitation of this syntax is that the name and path name of the executable
7272 itself must not include any embedded spaces.
7274 @item @code{--create-map-file}
7276 When linking an executable, create a map file. The name of the map file
7277 has the same name as the executable with extension “.map”.
7279 @item @code{--create-map-file=@emph{mapfile}}
7281 When linking an executable, create a map file with the specified name.
7282 @end table
7284 @geindex --create-missing-dirs (gnatmake)
7287 @table @asis
7289 @item @code{--create-missing-dirs}
7291 When using project files (@code{-P@emph{project}}), automatically create
7292 missing object directories, library directories and exec
7293 directories.
7295 @item @code{--single-compile-per-obj-dir}
7297 Disallow simultaneous compilations in the same object directory when
7298 project files are used.
7300 @item @code{--subdirs=@emph{subdir}}
7302 Actual object directory of each project file is the subdirectory subdir of the
7303 object directory specified or defaulted in the project file.
7305 @item @code{--unchecked-shared-lib-imports}
7307 By default, shared library projects are not allowed to import static library
7308 projects. When this switch is used on the command line, this restriction is
7309 relaxed.
7311 @item @code{--source-info=@emph{source info file}}
7313 Specify a source info file. This switch is active only when project files
7314 are used. If the source info file is specified as a relative path, then it is
7315 relative to the object directory of the main project. If the source info file
7316 does not exist, then after the Project Manager has successfully parsed and
7317 processed the project files and found the sources, it creates the source info
7318 file. If the source info file already exists and can be read successfully,
7319 then the Project Manager will get all the needed information about the sources
7320 from the source info file and will not look for them. This reduces the time
7321 to process the project files, especially when looking for sources that take a
7322 long time. If the source info file exists but cannot be parsed successfully,
7323 the Project Manager will attempt to recreate it. If the Project Manager fails
7324 to create the source info file, a message is issued, but gnatmake does not
7325 fail. @code{gnatmake} “trusts” the source info file. This means that
7326 if the source files have changed (addition, deletion, moving to a different
7327 source directory), then the source info file need to be deleted and recreated.
7328 @end table
7330 @geindex -a (gnatmake)
7333 @table @asis
7335 @item @code{-a}
7337 Consider all files in the make process, even the GNAT internal system
7338 files (for example, the predefined Ada library files), as well as any
7339 locked files. Locked files are files whose ALI file is write-protected.
7340 By default,
7341 @code{gnatmake} does not check these files,
7342 because the assumption is that the GNAT internal files are properly up
7343 to date, and also that any write protected ALI files have been properly
7344 installed. Note that if there is an installation problem, such that one
7345 of these files is not up to date, it will be properly caught by the
7346 binder.
7347 You may have to specify this switch if you are working on GNAT
7348 itself. The switch @code{-a} is also useful
7349 in conjunction with @code{-f}
7350 if you need to recompile an entire application,
7351 including run-time files, using special configuration pragmas,
7352 such as a @code{Normalize_Scalars} pragma.
7354 By default
7355 @code{gnatmake -a} compiles all GNAT
7356 internal files with
7357 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7358 @end table
7360 @geindex -b (gnatmake)
7363 @table @asis
7365 @item @code{-b}
7367 Bind only. Can be combined with @code{-c} to do
7368 compilation and binding, but no link.
7369 Can be combined with @code{-l}
7370 to do binding and linking. When not combined with
7371 @code{-c}
7372 all the units in the closure of the main program must have been previously
7373 compiled and must be up to date. The root unit specified by @code{file_name}
7374 may be given without extension, with the source extension or, if no GNAT
7375 Project File is specified, with the ALI file extension.
7376 @end table
7378 @geindex -c (gnatmake)
7381 @table @asis
7383 @item @code{-c}
7385 Compile only. Do not perform binding, except when @code{-b}
7386 is also specified. Do not perform linking, except if both
7387 @code{-b} and
7388 @code{-l} are also specified.
7389 If the root unit specified by @code{file_name} is not a main unit, this is the
7390 default. Otherwise @code{gnatmake} will attempt binding and linking
7391 unless all objects are up to date and the executable is more recent than
7392 the objects.
7393 @end table
7395 @geindex -C (gnatmake)
7398 @table @asis
7400 @item @code{-C}
7402 Use a temporary mapping file. A mapping file is a way to communicate
7403 to the compiler two mappings: from unit names to file names (without
7404 any directory information) and from file names to path names (with
7405 full directory information). A mapping file can make the compiler’s
7406 file searches faster, especially if there are many source directories,
7407 or the sources are read over a slow network connection. If
7408 @code{-P} is used, a mapping file is always used, so
7409 @code{-C} is unnecessary; in this case the mapping file
7410 is initially populated based on the project file. If
7411 @code{-C} is used without
7412 @code{-P},
7413 the mapping file is initially empty. Each invocation of the compiler
7414 will add any newly accessed sources to the mapping file.
7415 @end table
7417 @geindex -C= (gnatmake)
7420 @table @asis
7422 @item @code{-C=@emph{file}}
7424 Use a specific mapping file. The file, specified as a path name (absolute or
7425 relative) by this switch, should already exist, otherwise the switch is
7426 ineffective. The specified mapping file will be communicated to the compiler.
7427 This switch is not compatible with a project file
7428 (-P`file`) or with multiple compiling processes
7429 (-jnnn, when nnn is greater than 1).
7430 @end table
7432 @geindex -d (gnatmake)
7435 @table @asis
7437 @item @code{-d}
7439 Display progress for each source, up to date or not, as a single line:
7441 @example
7442 completed x out of y (zz%)
7443 @end example
7445 If the file needs to be compiled this is displayed after the invocation of
7446 the compiler. These lines are displayed even in quiet output mode.
7447 @end table
7449 @geindex -D (gnatmake)
7452 @table @asis
7454 @item @code{-D @emph{dir}}
7456 Put all object files and ALI file in directory @code{dir}.
7457 If the @code{-D} switch is not used, all object files
7458 and ALI files go in the current working directory.
7460 This switch cannot be used when using a project file.
7461 @end table
7463 @geindex -eI (gnatmake)
7466 @table @asis
7468 @item @code{-eI@emph{nnn}}
7470 Indicates that the main source is a multi-unit source and the rank of the unit
7471 in the source file is nnn. nnn needs to be a positive number and a valid
7472 index in the source. This switch cannot be used when @code{gnatmake} is
7473 invoked for several mains.
7474 @end table
7476 @geindex -eL (gnatmake)
7478 @geindex symbolic links
7481 @table @asis
7483 @item @code{-eL}
7485 Follow all symbolic links when processing project files.
7486 This should be used if your project uses symbolic links for files or
7487 directories, but is not needed in other cases.
7489 @geindex naming scheme
7491 This also assumes that no directory matches the naming scheme for files (for
7492 instance that you do not have a directory called “sources.ads” when using the
7493 default GNAT naming scheme).
7495 When you do not have to use this switch (i.e., by default), gnatmake is able to
7496 save a lot of system calls (several per source file and object file), which
7497 can result in a significant speed up to load and manipulate a project file,
7498 especially when using source files from a remote system.
7499 @end table
7501 @geindex -eS (gnatmake)
7504 @table @asis
7506 @item @code{-eS}
7508 Output the commands for the compiler, the binder and the linker
7509 on standard output,
7510 instead of standard error.
7511 @end table
7513 @geindex -f (gnatmake)
7516 @table @asis
7518 @item @code{-f}
7520 Force recompilations. Recompile all sources, even though some object
7521 files may be up to date, but don’t recompile predefined or GNAT internal
7522 files or locked files (files with a write-protected ALI file),
7523 unless the @code{-a} switch is also specified.
7524 @end table
7526 @geindex -F (gnatmake)
7529 @table @asis
7531 @item @code{-F}
7533 When using project files, if some errors or warnings are detected during
7534 parsing and verbose mode is not in effect (no use of switch
7535 -v), then error lines start with the full path name of the project
7536 file, rather than its simple file name.
7537 @end table
7539 @geindex -g (gnatmake)
7542 @table @asis
7544 @item @code{-g}
7546 Enable debugging. This switch is simply passed to the compiler and to the
7547 linker.
7548 @end table
7550 @geindex -i (gnatmake)
7553 @table @asis
7555 @item @code{-i}
7557 In normal mode, @code{gnatmake} compiles all object files and ALI files
7558 into the current directory. If the @code{-i} switch is used,
7559 then instead object files and ALI files that already exist are overwritten
7560 in place. This means that once a large project is organized into separate
7561 directories in the desired manner, then @code{gnatmake} will automatically
7562 maintain and update this organization. If no ALI files are found on the
7563 Ada object path (see @ref{73,,Search Paths and the Run-Time Library (RTL)}),
7564 the new object and ALI files are created in the
7565 directory containing the source being compiled. If another organization
7566 is desired, where objects and sources are kept in different directories,
7567 a useful technique is to create dummy ALI files in the desired directories.
7568 When detecting such a dummy file, @code{gnatmake} will be forced to
7569 recompile the corresponding source file, and it will be put the resulting
7570 object and ALI files in the directory where it found the dummy file.
7571 @end table
7573 @geindex -j (gnatmake)
7575 @geindex Parallel make
7578 @table @asis
7580 @item @code{-j@emph{n}}
7582 Use @code{n} processes to carry out the (re)compilations. On a multiprocessor
7583 machine compilations will occur in parallel. If @code{n} is 0, then the
7584 maximum number of parallel compilations is the number of core processors
7585 on the platform. In the event of compilation errors, messages from various
7586 compilations might get interspersed (but @code{gnatmake} will give you the
7587 full ordered list of failing compiles at the end). If this is problematic,
7588 rerun the make process with n set to 1 to get a clean list of messages.
7589 @end table
7591 @geindex -k (gnatmake)
7594 @table @asis
7596 @item @code{-k}
7598 Keep going. Continue as much as possible after a compilation error. To
7599 ease the programmer’s task in case of compilation errors, the list of
7600 sources for which the compile fails is given when @code{gnatmake}
7601 terminates.
7603 If @code{gnatmake} is invoked with several @code{file_names} and with this
7604 switch, if there are compilation errors when building an executable,
7605 @code{gnatmake} will not attempt to build the following executables.
7606 @end table
7608 @geindex -l (gnatmake)
7611 @table @asis
7613 @item @code{-l}
7615 Link only. Can be combined with @code{-b} to binding
7616 and linking. Linking will not be performed if combined with
7617 @code{-c}
7618 but not with @code{-b}.
7619 When not combined with @code{-b}
7620 all the units in the closure of the main program must have been previously
7621 compiled and must be up to date, and the main program needs to have been bound.
7622 The root unit specified by @code{file_name}
7623 may be given without extension, with the source extension or, if no GNAT
7624 Project File is specified, with the ALI file extension.
7625 @end table
7627 @geindex -m (gnatmake)
7630 @table @asis
7632 @item @code{-m}
7634 Specify that the minimum necessary amount of recompilations
7635 be performed. In this mode @code{gnatmake} ignores time
7636 stamp differences when the only
7637 modifications to a source file consist in adding/removing comments,
7638 empty lines, spaces or tabs. This means that if you have changed the
7639 comments in a source file or have simply reformatted it, using this
7640 switch will tell @code{gnatmake} not to recompile files that depend on it
7641 (provided other sources on which these files depend have undergone no
7642 semantic modifications). Note that the debugging information may be
7643 out of date with respect to the sources if the @code{-m} switch causes
7644 a compilation to be switched, so the use of this switch represents a
7645 trade-off between compilation time and accurate debugging information.
7646 @end table
7648 @geindex Dependencies
7649 @geindex producing list
7651 @geindex -M (gnatmake)
7654 @table @asis
7656 @item @code{-M}
7658 Check if all objects are up to date. If they are, output the object
7659 dependences to @code{stdout} in a form that can be directly exploited in
7660 a @code{Makefile}. By default, each source file is prefixed with its
7661 (relative or absolute) directory name. This name is whatever you
7662 specified in the various @code{-aI}
7663 and @code{-I} switches. If you use
7664 @code{gnatmake -M}  @code{-q}
7665 (see below), only the source file names,
7666 without relative paths, are output. If you just specify the  @code{-M}
7667 switch, dependencies of the GNAT internal system files are omitted. This
7668 is typically what you want. If you also specify
7669 the @code{-a} switch,
7670 dependencies of the GNAT internal files are also listed. Note that
7671 dependencies of the objects in external Ada libraries (see
7672 switch  @code{-aL@emph{dir}} in the following list)
7673 are never reported.
7674 @end table
7676 @geindex -n (gnatmake)
7679 @table @asis
7681 @item @code{-n}
7683 Don’t compile, bind, or link. Checks if all objects are up to date.
7684 If they are not, the full name of the first file that needs to be
7685 recompiled is printed.
7686 Repeated use of this option, followed by compiling the indicated source
7687 file, will eventually result in recompiling all required units.
7688 @end table
7690 @geindex -o (gnatmake)
7693 @table @asis
7695 @item @code{-o @emph{exec_name}}
7697 Output executable name. The name of the final executable program will be
7698 @code{exec_name}. If the @code{-o} switch is omitted the default
7699 name for the executable will be the name of the input file in appropriate form
7700 for an executable file on the host system.
7702 This switch cannot be used when invoking @code{gnatmake} with several
7703 @code{file_names}.
7704 @end table
7706 @geindex -p (gnatmake)
7709 @table @asis
7711 @item @code{-p}
7713 Same as @code{--create-missing-dirs}
7714 @end table
7716 @geindex -q (gnatmake)
7719 @table @asis
7721 @item @code{-q}
7723 Quiet. When this flag is not set, the commands carried out by
7724 @code{gnatmake} are displayed.
7725 @end table
7727 @geindex -s (gnatmake)
7730 @table @asis
7732 @item @code{-s}
7734 Recompile if compiler switches have changed since last compilation.
7735 All compiler switches but -I and -o are taken into account in the
7736 following way:
7737 orders between different ‘first letter’ switches are ignored, but
7738 orders between same switches are taken into account. For example,
7739 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O}
7740 is equivalent to @code{-O -g}.
7742 This switch is recommended when Integrated Preprocessing is used.
7743 @end table
7745 @geindex -u (gnatmake)
7748 @table @asis
7750 @item @code{-u}
7752 Unique. Recompile at most the main files. It implies -c. Combined with
7753 -f, it is equivalent to calling the compiler directly. Note that using
7754 -u with a project file and no main has a special meaning.
7755 @end table
7757 @c --Comment
7758 @c (See :ref:`Project_Files_and_Main_Subprograms`.)
7760 @geindex -U (gnatmake)
7763 @table @asis
7765 @item @code{-U}
7767 When used without a project file or with one or several mains on the command
7768 line, is equivalent to -u. When used with a project file and no main
7769 on the command line, all sources of all project files are checked and compiled
7770 if not up to date, and libraries are rebuilt, if necessary.
7771 @end table
7773 @geindex -v (gnatmake)
7776 @table @asis
7778 @item @code{-v}
7780 Verbose. Display the reason for all recompilations @code{gnatmake}
7781 decides are necessary, with the highest verbosity level.
7782 @end table
7784 @geindex -vl (gnatmake)
7787 @table @asis
7789 @item @code{-vl}
7791 Verbosity level Low. Display fewer lines than in verbosity Medium.
7792 @end table
7794 @geindex -vm (gnatmake)
7797 @table @asis
7799 @item @code{-vm}
7801 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7802 @end table
7804 @geindex -vm (gnatmake)
7807 @table @asis
7809 @item @code{-vh}
7811 Verbosity level High. Equivalent to -v.
7813 @item @code{-vP@emph{x}}
7815 Indicate the verbosity of the parsing of GNAT project files.
7816 See @ref{d1,,Switches Related to Project Files}.
7817 @end table
7819 @geindex -x (gnatmake)
7822 @table @asis
7824 @item @code{-x}
7826 Indicate that sources that are not part of any Project File may be compiled.
7827 Normally, when using Project Files, only sources that are part of a Project
7828 File may be compile. When this switch is used, a source outside of all Project
7829 Files may be compiled. The ALI file and the object file will be put in the
7830 object directory of the main Project. The compilation switches used will only
7831 be those specified on the command line. Even when
7832 @code{-x} is used, mains specified on the
7833 command line need to be sources of a project file.
7835 @item @code{-X@emph{name}=@emph{value}}
7837 Indicate that external variable @code{name} has the value @code{value}.
7838 The Project Manager will use this value for occurrences of
7839 @code{external(name)} when parsing the project file.
7840 @ref{d1,,Switches Related to Project Files}.
7841 @end table
7843 @geindex -z (gnatmake)
7846 @table @asis
7848 @item @code{-z}
7850 No main subprogram. Bind and link the program even if the unit name
7851 given on the command line is a package name. The resulting executable
7852 will execute the elaboration routines of the package and its closure,
7853 then the finalization routines.
7854 @end table
7856 @subsubheading GCC switches
7859 Any uppercase or multi-character switch that is not a @code{gnatmake} switch
7860 is passed to @code{gcc} (e.g., @code{-O}, @code{-gnato,} etc.)
7862 @subsubheading Source and library search path switches
7865 @geindex -aI (gnatmake)
7868 @table @asis
7870 @item @code{-aI@emph{dir}}
7872 When looking for source files also look in directory @code{dir}.
7873 The order in which source files search is undertaken is
7874 described in @ref{73,,Search Paths and the Run-Time Library (RTL)}.
7875 @end table
7877 @geindex -aL (gnatmake)
7880 @table @asis
7882 @item @code{-aL@emph{dir}}
7884 Consider @code{dir} as being an externally provided Ada library.
7885 Instructs @code{gnatmake} to skip compilation units whose @code{.ALI}
7886 files have been located in directory @code{dir}. This allows you to have
7887 missing bodies for the units in @code{dir} and to ignore out of date bodies
7888 for the same units. You still need to specify
7889 the location of the specs for these units by using the switches
7890 @code{-aI@emph{dir}}  or @code{-I@emph{dir}}.
7891 Note: this switch is provided for compatibility with previous versions
7892 of @code{gnatmake}. The easier method of causing standard libraries
7893 to be excluded from consideration is to write-protect the corresponding
7894 ALI files.
7895 @end table
7897 @geindex -aO (gnatmake)
7900 @table @asis
7902 @item @code{-aO@emph{dir}}
7904 When searching for library and object files, look in directory
7905 @code{dir}. The order in which library files are searched is described in
7906 @ref{76,,Search Paths for gnatbind}.
7907 @end table
7909 @geindex Search paths
7910 @geindex for gnatmake
7912 @geindex -A (gnatmake)
7915 @table @asis
7917 @item @code{-A@emph{dir}}
7919 Equivalent to @code{-aL@emph{dir}} @code{-aI@emph{dir}}.
7921 @geindex -I (gnatmake)
7923 @item @code{-I@emph{dir}}
7925 Equivalent to @code{-aO@emph{dir} -aI@emph{dir}}.
7926 @end table
7928 @geindex -I- (gnatmake)
7930 @geindex Source files
7931 @geindex suppressing search
7934 @table @asis
7936 @item @code{-I-}
7938 Do not look for source files in the directory containing the source
7939 file named in the command line.
7940 Do not look for ALI or object files in the directory
7941 where @code{gnatmake} was invoked.
7942 @end table
7944 @geindex -L (gnatmake)
7946 @geindex Linker libraries
7949 @table @asis
7951 @item @code{-L@emph{dir}}
7953 Add directory @code{dir} to the list of directories in which the linker
7954 will search for libraries. This is equivalent to
7955 @code{-largs} @code{-L@emph{dir}}.
7956 Furthermore, under Windows, the sources pointed to by the libraries path
7957 set in the registry are not searched for.
7958 @end table
7960 @geindex -nostdinc (gnatmake)
7963 @table @asis
7965 @item @code{-nostdinc}
7967 Do not look for source files in the system default directory.
7968 @end table
7970 @geindex -nostdlib (gnatmake)
7973 @table @asis
7975 @item @code{-nostdlib}
7977 Do not look for library files in the system default directory.
7978 @end table
7980 @geindex --RTS (gnatmake)
7983 @table @asis
7985 @item @code{--RTS=@emph{rts-path}}
7987 Specifies the default location of the run-time library. GNAT looks for the
7988 run-time
7989 in the following directories, and stops as soon as a valid run-time is found
7990 (@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
7991 @code{ada_object_path} present):
7994 @itemize *
7996 @item 
7997 @emph{<current directory>/$rts_path}
7999 @item 
8000 @emph{<default-search-dir>/$rts_path}
8002 @item 
8003 @emph{<default-search-dir>/rts-$rts_path}
8005 @item 
8006 The selected path is handled like a normal RTS path.
8007 @end itemize
8008 @end table
8010 @node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
8011 @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}
8012 @subsection Mode Switches for @code{gnatmake}
8015 The mode switches (referred to as @code{mode_switches}) allow the
8016 inclusion of switches that are to be passed to the compiler itself, the
8017 binder or the linker. The effect of a mode switch is to cause all
8018 subsequent switches up to the end of the switch list, or up to the next
8019 mode switch, to be interpreted as switches to be passed on to the
8020 designated component of GNAT.
8022 @geindex -cargs (gnatmake)
8025 @table @asis
8027 @item @code{-cargs @emph{switches}}
8029 Compiler switches. Here @code{switches} is a list of switches
8030 that are valid switches for @code{gcc}. They will be passed on to
8031 all compile steps performed by @code{gnatmake}.
8032 @end table
8034 @geindex -bargs (gnatmake)
8037 @table @asis
8039 @item @code{-bargs @emph{switches}}
8041 Binder switches. Here @code{switches} is a list of switches
8042 that are valid switches for @code{gnatbind}. They will be passed on to
8043 all bind steps performed by @code{gnatmake}.
8044 @end table
8046 @geindex -largs (gnatmake)
8049 @table @asis
8051 @item @code{-largs @emph{switches}}
8053 Linker switches. Here @code{switches} is a list of switches
8054 that are valid switches for @code{gnatlink}. They will be passed on to
8055 all link steps performed by @code{gnatmake}.
8056 @end table
8058 @geindex -margs (gnatmake)
8061 @table @asis
8063 @item @code{-margs @emph{switches}}
8065 Make switches. The switches are directly interpreted by @code{gnatmake},
8066 regardless of any previous occurrence of @code{-cargs}, @code{-bargs}
8067 or @code{-largs}.
8068 @end table
8070 @node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
8071 @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}
8072 @subsection Notes on the Command Line
8075 This section contains some additional useful notes on the operation
8076 of the @code{gnatmake} command.
8078 @geindex Recompilation (by gnatmake)
8081 @itemize *
8083 @item 
8084 If @code{gnatmake} finds no ALI files, it recompiles the main program
8085 and all other units required by the main program.
8086 This means that @code{gnatmake}
8087 can be used for the initial compile, as well as during subsequent steps of
8088 the development cycle.
8090 @item 
8091 If you enter @code{gnatmake foo.adb}, where @code{foo}
8092 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8093 @code{foo.adb} (because it finds no ALI) and stops, issuing a
8094 warning.
8096 @item 
8097 In @code{gnatmake} the switch @code{-I}
8098 is used to specify both source and
8099 library file paths. Use @code{-aI}
8100 instead if you just want to specify
8101 source paths only and @code{-aO}
8102 if you want to specify library paths
8103 only.
8105 @item 
8106 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8107 This may conveniently be used to exclude standard libraries from
8108 consideration and in particular it means that the use of the
8109 @code{-f} switch will not recompile these files
8110 unless @code{-a} is also specified.
8112 @item 
8113 @code{gnatmake} has been designed to make the use of Ada libraries
8114 particularly convenient. Assume you have an Ada library organized
8115 as follows: @emph{obj-dir} contains the objects and ALI files for
8116 of your Ada compilation units,
8117 whereas @emph{include-dir} contains the
8118 specs of these units, but no bodies. Then to compile a unit
8119 stored in @code{main.adb}, which uses this Ada library you would just type:
8121 @example
8122 $ gnatmake -aI`include-dir`  -aL`obj-dir`  main
8123 @end example
8125 @item 
8126 Using @code{gnatmake} along with the @code{-m (minimal recompilation)}
8127 switch provides a mechanism for avoiding unnecessary recompilations. Using
8128 this switch,
8129 you can update the comments/format of your
8130 source files without having to recompile everything. Note, however, that
8131 adding or deleting lines in a source files may render its debugging
8132 info obsolete. If the file in question is a spec, the impact is rather
8133 limited, as that debugging info will only be useful during the
8134 elaboration phase of your program. For bodies the impact can be more
8135 significant. In all events, your debugger will warn you if a source file
8136 is more recent than the corresponding object, and alert you to the fact
8137 that the debugging information may be out of date.
8138 @end itemize
8140 @node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8141 @anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{d6}@anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{d7}
8142 @subsection How @code{gnatmake} Works
8145 Generally @code{gnatmake} automatically performs all necessary
8146 recompilations and you don’t need to worry about how it works. However,
8147 it may be useful to have some basic understanding of the @code{gnatmake}
8148 approach and in particular to understand how it uses the results of
8149 previous compilations without incorrectly depending on them.
8151 First a definition: an object file is considered @emph{up to date} if the
8152 corresponding ALI file exists and if all the source files listed in the
8153 dependency section of this ALI file have time stamps matching those in
8154 the ALI file. This means that neither the source file itself nor any
8155 files that it depends on have been modified, and hence there is no need
8156 to recompile this file.
8158 @code{gnatmake} works by first checking if the specified main unit is up
8159 to date. If so, no compilations are required for the main unit. If not,
8160 @code{gnatmake} compiles the main program to build a new ALI file that
8161 reflects the latest sources. Then the ALI file of the main unit is
8162 examined to find all the source files on which the main program depends,
8163 and @code{gnatmake} recursively applies the above procedure on all these
8164 files.
8166 This process ensures that @code{gnatmake} only trusts the dependencies
8167 in an existing ALI file if they are known to be correct. Otherwise it
8168 always recompiles to determine a new, guaranteed accurate set of
8169 dependencies. As a result the program is compiled ‘upside down’ from what may
8170 be more familiar as the required order of compilation in some other Ada
8171 systems. In particular, clients are compiled before the units on which
8172 they depend. The ability of GNAT to compile in any order is critical in
8173 allowing an order of compilation to be chosen that guarantees that
8174 @code{gnatmake} will recompute a correct set of new dependencies if
8175 necessary.
8177 When invoking @code{gnatmake} with several @code{file_names}, if a unit is
8178 imported by several of the executables, it will be recompiled at most once.
8180 Note: when using non-standard naming conventions
8181 (@ref{1c,,Using Other File Names}), changing through a configuration pragmas
8182 file the version of a source and invoking @code{gnatmake} to recompile may
8183 have no effect, if the previous version of the source is still accessible
8184 by @code{gnatmake}. It may be necessary to use the switch
8187 @node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8188 @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}
8189 @subsection Examples of @code{gnatmake} Usage
8193 @table @asis
8195 @item @code{gnatmake hello.adb}
8197 Compile all files necessary to bind and link the main program
8198 @code{hello.adb} (containing unit @code{Hello}) and bind and link the
8199 resulting object files to generate an executable file @code{hello}.
8201 @item @code{gnatmake main1 main2 main3}
8203 Compile all files necessary to bind and link the main programs
8204 @code{main1.adb} (containing unit @code{Main1}), @code{main2.adb}
8205 (containing unit @code{Main2}) and @code{main3.adb}
8206 (containing unit @code{Main3}) and bind and link the resulting object files
8207 to generate three executable files @code{main1},
8208 @code{main2}  and @code{main3}.
8210 @item @code{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8212 Compile all files necessary to bind and link the main program unit
8213 @code{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8214 be done with optimization level 2 and the order of elaboration will be
8215 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8216 displaying commands it is executing.
8217 @end table
8219 @node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8220 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{c9}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{da}
8221 @section Compiling with @code{gcc}
8224 This section discusses how to compile Ada programs using the @code{gcc}
8225 command. It also describes the set of switches
8226 that can be used to control the behavior of the compiler.
8228 @menu
8229 * Compiling Programs:: 
8230 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
8231 * Order of Compilation Issues:: 
8232 * Examples:: 
8234 @end menu
8236 @node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8237 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{db}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{dc}
8238 @subsection Compiling Programs
8241 The first step in creating an executable program is to compile the units
8242 of the program using the @code{gcc} command. You must compile the
8243 following files:
8246 @itemize *
8248 @item 
8249 the body file (@code{.adb}) for a library level subprogram or generic
8250 subprogram
8252 @item 
8253 the spec file (@code{.ads}) for a library level package or generic
8254 package that has no body
8256 @item 
8257 the body file (@code{.adb}) for a library level package
8258 or generic package that has a body
8259 @end itemize
8261 You need @emph{not} compile the following files
8264 @itemize *
8266 @item 
8267 the spec of a library unit which has a body
8269 @item 
8270 subunits
8271 @end itemize
8273 because they are compiled as part of compiling related units. GNAT compiles
8274 package specs
8275 when the corresponding body is compiled, and subunits when the parent is
8276 compiled.
8278 @geindex cannot generate code
8280 If you attempt to compile any of these files, you will get one of the
8281 following error messages (where @code{fff} is the name of the file you
8282 compiled):
8284 @quotation
8286 @example
8287 cannot generate code for file `@w{`}fff`@w{`} (package spec)
8288 to check package spec, use -gnatc
8290 cannot generate code for file `@w{`}fff`@w{`} (missing subunits)
8291 to check parent unit, use -gnatc
8293 cannot generate code for file `@w{`}fff`@w{`} (subprogram spec)
8294 to check subprogram spec, use -gnatc
8296 cannot generate code for file `@w{`}fff`@w{`} (subunit)
8297 to check subunit, use -gnatc
8298 @end example
8299 @end quotation
8301 As indicated by the above error messages, if you want to submit
8302 one of these files to the compiler to check for correct semantics
8303 without generating code, then use the @code{-gnatc} switch.
8305 The basic command for compiling a file containing an Ada unit is:
8307 @example
8308 $ gcc -c [switches] <file name>
8309 @end example
8311 where @code{file name} is the name of the Ada file (usually
8312 having an extension @code{.ads} for a spec or @code{.adb} for a body).
8313 You specify the
8314 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
8315 The result of a successful compilation is an object file, which has the
8316 same name as the source file but an extension of @code{.o} and an Ada
8317 Library Information (ALI) file, which also has the same name as the
8318 source file, but with @code{.ali} as the extension. GNAT creates these
8319 two output files in the current directory, but you may specify a source
8320 file in any directory using an absolute or relative path specification
8321 containing the directory information.
8323 @geindex gnat1
8325 @code{gcc} is actually a driver program that looks at the extensions of
8326 the file arguments and loads the appropriate compiler. For example, the
8327 GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8328 These programs are in directories known to the driver program (in some
8329 configurations via environment variables you set), but need not be in
8330 your path. The @code{gcc} driver also calls the assembler and any other
8331 utilities needed to complete the generation of the required object
8332 files.
8334 It is possible to supply several file names on the same @code{gcc}
8335 command. This causes @code{gcc} to call the appropriate compiler for
8336 each file. For example, the following command lists two separate
8337 files to be compiled:
8339 @example
8340 $ gcc -c x.adb y.adb
8341 @end example
8343 calls @code{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8344 @code{y.adb}.
8345 The compiler generates two object files @code{x.o} and @code{y.o}
8346 and the two ALI files @code{x.ali} and @code{y.ali}.
8348 Any switches apply to all the files listed, see @ref{dd,,Compiler Switches} for a
8349 list of available @code{gcc} switches.
8351 @node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8352 @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}
8353 @subsection Search Paths and the Run-Time Library (RTL)
8356 With the GNAT source-based library system, the compiler must be able to
8357 find source files for units that are needed by the unit being compiled.
8358 Search paths are used to guide this process.
8360 The compiler compiles one source file whose name must be given
8361 explicitly on the command line. In other words, no searching is done
8362 for this file. To find all other source files that are needed (the most
8363 common being the specs of units), the compiler examines the following
8364 directories, in the following order:
8367 @itemize *
8369 @item 
8370 The directory containing the source file of the main unit being compiled
8371 (the file name on the command line).
8373 @item 
8374 Each directory named by an @code{-I} switch given on the @code{gcc}
8375 command line, in the order given.
8377 @geindex ADA_PRJ_INCLUDE_FILE
8379 @item 
8380 Each of the directories listed in the text file whose name is given
8381 by the 
8382 @geindex ADA_PRJ_INCLUDE_FILE
8383 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8384 @code{ADA_PRJ_INCLUDE_FILE} environment variable.
8385 @geindex ADA_PRJ_INCLUDE_FILE
8386 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8387 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8388 driver when project files are used. It should not normally be set
8389 by other means.
8391 @geindex ADA_INCLUDE_PATH
8393 @item 
8394 Each of the directories listed in the value of the
8395 @geindex ADA_INCLUDE_PATH
8396 @geindex environment variable; ADA_INCLUDE_PATH
8397 @code{ADA_INCLUDE_PATH} environment variable.
8398 Construct this value
8399 exactly as the 
8400 @geindex PATH
8401 @geindex environment variable; PATH
8402 @code{PATH} environment variable: a list of directory
8403 names separated by colons (semicolons when working with the NT version).
8405 @item 
8406 The content of the @code{ada_source_path} file which is part of the GNAT
8407 installation tree and is used to store standard libraries such as the
8408 GNAT Run Time Library (RTL) source files.
8409 See also @ref{72,,Installing a library}.
8410 @end itemize
8412 Specifying the switch @code{-I-}
8413 inhibits the use of the directory
8414 containing the source file named in the command line. You can still
8415 have this directory on your search path, but in this case it must be
8416 explicitly requested with a @code{-I} switch.
8418 Specifying the switch @code{-nostdinc}
8419 inhibits the search of the default location for the GNAT Run Time
8420 Library (RTL) source files.
8422 The compiler outputs its object files and ALI files in the current
8423 working directory.
8424 Caution: The object file can be redirected with the @code{-o} switch;
8425 however, @code{gcc} and @code{gnat1} have not been coordinated on this
8426 so the @code{ALI} file will not go to the right place. Therefore, you should
8427 avoid using the @code{-o} switch.
8429 @geindex System.IO
8431 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8432 children make up the GNAT RTL, together with the simple @code{System.IO}
8433 package used in the @code{"Hello World"} example. The sources for these units
8434 are needed by the compiler and are kept together in one directory. Not
8435 all of the bodies are needed, but all of the sources are kept together
8436 anyway. In a normal installation, you need not specify these directory
8437 names when compiling or binding. Either the environment variables or
8438 the built-in defaults cause these files to be found.
8440 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8441 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8442 consisting of child units of @code{GNAT}. This is a collection of generally
8443 useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8444 for further details.
8446 Besides simplifying access to the RTL, a major use of search paths is
8447 in compiling sources from multiple directories. This can make
8448 development environments much more flexible.
8450 @node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8451 @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}
8452 @subsection Order of Compilation Issues
8455 If, in our earlier example, there was a spec for the @code{hello}
8456 procedure, it would be contained in the file @code{hello.ads}; yet this
8457 file would not have to be explicitly compiled. This is the result of the
8458 model we chose to implement library management. Some of the consequences
8459 of this model are as follows:
8462 @itemize *
8464 @item 
8465 There is no point in compiling specs (except for package
8466 specs with no bodies) because these are compiled as needed by clients. If
8467 you attempt a useless compilation, you will receive an error message.
8468 It is also useless to compile subunits because they are compiled as needed
8469 by the parent.
8471 @item 
8472 There are no order of compilation requirements: performing a
8473 compilation never obsoletes anything. The only way you can obsolete
8474 something and require recompilations is to modify one of the
8475 source files on which it depends.
8477 @item 
8478 There is no library as such, apart from the ALI files
8479 (@ref{28,,The Ada Library Information Files}, for information on the format
8480 of these files). For now we find it convenient to create separate ALI files,
8481 but eventually the information therein may be incorporated into the object
8482 file directly.
8484 @item 
8485 When you compile a unit, the source files for the specs of all units
8486 that it @emph{with}s, all its subunits, and the bodies of any generics it
8487 instantiates must be available (reachable by the search-paths mechanism
8488 described above), or you will receive a fatal error message.
8489 @end itemize
8491 @node Examples,,Order of Compilation Issues,Compiling with gcc
8492 @anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{e1}@anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{e2}
8493 @subsection Examples
8496 The following are some typical Ada compilation command line examples:
8498 @example
8499 $ gcc -c xyz.adb
8500 @end example
8502 Compile body in file @code{xyz.adb} with all default options.
8504 @example
8505 $ gcc -c -O2 -gnata xyz-def.adb
8506 @end example
8508 Compile the child unit package in file @code{xyz-def.adb} with extensive
8509 optimizations, and pragma @code{Assert}/@code{Debug} statements
8510 enabled.
8512 @example
8513 $ gcc -c -gnatc abc-def.adb
8514 @end example
8516 Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8517 mode.
8519 @node Compiler Switches,Linker Switches,Compiling with gcc,Building Executable Programs with GNAT
8520 @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}
8521 @section Compiler Switches
8524 The @code{gcc} command accepts switches that control the
8525 compilation process. These switches are fully described in this section:
8526 first an alphabetical listing of all switches with a brief description,
8527 and then functionally grouped sets of switches with more detailed
8528 information.
8530 More switches exist for GCC than those documented here, especially
8531 for specific targets. However, their use is not recommended as
8532 they may change code generation in ways that are incompatible with
8533 the Ada run-time library, or can cause inconsistencies between
8534 compilation units.
8536 @menu
8537 * Alphabetical List of All Switches:: 
8538 * Output and Error Message Control:: 
8539 * Warning Message Control:: 
8540 * Debugging and Assertion Control:: 
8541 * Validity Checking:: 
8542 * Style Checking:: 
8543 * Run-Time Checks:: 
8544 * Using gcc for Syntax Checking:: 
8545 * Using gcc for Semantic Checking:: 
8546 * Compiling Different Versions of Ada:: 
8547 * Character Set Control:: 
8548 * File Naming Control:: 
8549 * Subprogram Inlining Control:: 
8550 * Auxiliary Output Control:: 
8551 * Debugging Control:: 
8552 * Exception Handling Control:: 
8553 * Units to Sources Mapping Files:: 
8554 * Code Generation Control:: 
8556 @end menu
8558 @node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8559 @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}
8560 @subsection Alphabetical List of All Switches
8563 @geindex -b (gcc)
8566 @table @asis
8568 @item @code{-b @emph{target}}
8570 Compile your program to run on @code{target}, which is the name of a
8571 system configuration. You must have a GNAT cross-compiler built if
8572 @code{target} is not the same as your host system.
8573 @end table
8575 @geindex -B (gcc)
8578 @table @asis
8580 @item @code{-B@emph{dir}}
8582 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8583 from @code{dir} instead of the default location. Only use this switch
8584 when multiple versions of the GNAT compiler are available.
8585 See the “Options for Directory Search” section in the
8586 @cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8587 You would normally use the @code{-b} or @code{-V} switch instead.
8588 @end table
8590 @geindex -c (gcc)
8593 @table @asis
8595 @item @code{-c}
8597 Compile. Always use this switch when compiling Ada programs.
8599 Note: for some other languages when using @code{gcc}, notably in
8600 the case of C and C++, it is possible to use
8601 use @code{gcc} without a @code{-c} switch to
8602 compile and link in one step. In the case of GNAT, you
8603 cannot use this approach, because the binder must be run
8604 and @code{gcc} cannot be used to run the GNAT binder.
8605 @end table
8607 @geindex -fcallgraph-info (gcc)
8610 @table @asis
8612 @item @code{-fcallgraph-info[=su,da]}
8614 Makes the compiler output callgraph information for the program, on a
8615 per-file basis. The information is generated in the VCG format.  It can
8616 be decorated with additional, per-node and/or per-edge information, if a
8617 list of comma-separated markers is additionally specified. When the
8618 @code{su} marker is specified, the callgraph is decorated with stack usage
8619 information; it is equivalent to @code{-fstack-usage}. When the @code{da}
8620 marker is specified, the callgraph is decorated with information about
8621 dynamically allocated objects.
8622 @end table
8624 @geindex -fdiagnostics-format (gcc)
8627 @table @asis
8629 @item @code{-fdiagnostics-format=json}
8631 Makes GNAT emit warning and error messages as JSON. Inhibits printing of
8632 text warning and errors messages except if @code{-gnatv} or
8633 @code{-gnatl} are present. Uses absolute file paths when used along
8634 @code{-gnatef}.
8635 @end table
8637 @geindex -fdump-scos (gcc)
8640 @table @asis
8642 @item @code{-fdump-scos}
8644 Generates SCO (Source Coverage Obligation) information in the ALI file.
8645 This information is used by advanced coverage tools. See unit @code{SCOs}
8646 in the compiler sources for details in files @code{scos.ads} and
8647 @code{scos.adb}.
8648 @end table
8650 @geindex -fgnat-encodings (gcc)
8653 @table @asis
8655 @item @code{-fgnat-encodings=[all|gdb|minimal]}
8657 This switch controls the balance between GNAT encodings and standard DWARF
8658 emitted in the debug information.
8659 @end table
8661 @geindex -flto (gcc)
8664 @table @asis
8666 @item @code{-flto[=@emph{n}]}
8668 Enables Link Time Optimization. This switch must be used in conjunction
8669 with the @code{-Ox} switches (but not with the @code{-gnatn} switch
8670 since it is a full replacement for the latter) and instructs the compiler
8671 to defer most optimizations until the link stage. The advantage of this
8672 approach is that the compiler can do a whole-program analysis and choose
8673 the best interprocedural optimization strategy based on a complete view
8674 of the program, instead of a fragmentary view with the usual approach.
8675 This can also speed up the compilation of big programs and reduce the
8676 size of the executable, compared with a traditional per-unit compilation
8677 with inlining across units enabled by the @code{-gnatn} switch.
8678 The drawback of this approach is that it may require more memory and that
8679 the debugging information generated by @code{-g} with it might be hardly usable.
8680 The switch, as well as the accompanying @code{-Ox} switches, must be
8681 specified both for the compilation and the link phases.
8682 If the @code{n} parameter is specified, the optimization and final code
8683 generation at link time are executed using @code{n} parallel jobs by
8684 means of an installed @code{make} program.
8685 @end table
8687 @geindex -fno-inline (gcc)
8690 @table @asis
8692 @item @code{-fno-inline}
8694 Suppresses all inlining, unless requested with pragma @code{Inline_Always}. The
8695 effect is enforced regardless of other optimization or inlining switches.
8696 Note that inlining can also be suppressed on a finer-grained basis with
8697 pragma @code{No_Inline}.
8698 @end table
8700 @geindex -fno-inline-functions (gcc)
8703 @table @asis
8705 @item @code{-fno-inline-functions}
8707 Suppresses automatic inlining of subprograms, which is enabled
8708 if @code{-O3} is used.
8709 @end table
8711 @geindex -fno-inline-small-functions (gcc)
8714 @table @asis
8716 @item @code{-fno-inline-small-functions}
8718 Suppresses automatic inlining of small subprograms, which is enabled
8719 if @code{-O2} is used.
8720 @end table
8722 @geindex -fno-inline-functions-called-once (gcc)
8725 @table @asis
8727 @item @code{-fno-inline-functions-called-once}
8729 Suppresses inlining of subprograms local to the unit and called once
8730 from within it, which is enabled if @code{-O1} is used.
8731 @end table
8733 @geindex -fno-ivopts (gcc)
8736 @table @asis
8738 @item @code{-fno-ivopts}
8740 Suppresses high-level loop induction variable optimizations, which are
8741 enabled if @code{-O1} is used. These optimizations are generally
8742 profitable but, for some specific cases of loops with numerous uses
8743 of the iteration variable that follow a common pattern, they may end
8744 up destroying the regularity that could be exploited at a lower level
8745 and thus producing inferior code.
8746 @end table
8748 @geindex -fno-strict-aliasing (gcc)
8751 @table @asis
8753 @item @code{-fno-strict-aliasing}
8755 Causes the compiler to avoid assumptions regarding non-aliasing
8756 of objects of different types. See
8757 @ref{e6,,Optimization and Strict Aliasing} for details.
8758 @end table
8760 @geindex -fno-strict-overflow (gcc)
8763 @table @asis
8765 @item @code{-fno-strict-overflow}
8767 Causes the compiler to avoid assumptions regarding the rules of signed
8768 integer overflow. These rules specify that signed integer overflow will
8769 result in a Constraint_Error exception at run time and are enforced in
8770 default mode by the compiler, so this switch should not be necessary in
8771 normal operating mode. It might be useful in conjunction with @code{-gnato0}
8772 for very peculiar cases of low-level programming.
8773 @end table
8775 @geindex -fstack-check (gcc)
8778 @table @asis
8780 @item @code{-fstack-check}
8782 Activates stack checking.
8783 See @ref{e7,,Stack Overflow Checking} for details.
8784 @end table
8786 @geindex -fstack-usage (gcc)
8789 @table @asis
8791 @item @code{-fstack-usage}
8793 Makes the compiler output stack usage information for the program, on a
8794 per-subprogram basis. See @ref{e8,,Static Stack Usage Analysis} for details.
8795 @end table
8797 @geindex -g (gcc)
8800 @table @asis
8802 @item @code{-g}
8804 Generate debugging information. This information is stored in the object
8805 file and copied from there to the final executable file by the linker,
8806 where it can be read by the debugger. You must use the
8807 @code{-g} switch if you plan on using the debugger.
8808 @end table
8810 @geindex -gnat05 (gcc)
8813 @table @asis
8815 @item @code{-gnat05}
8817 Allow full Ada 2005 features.
8818 @end table
8820 @geindex -gnat12 (gcc)
8823 @table @asis
8825 @item @code{-gnat12}
8827 Allow full Ada 2012 features.
8828 @end table
8830 @geindex -gnat83 (gcc)
8832 @geindex -gnat2005 (gcc)
8835 @table @asis
8837 @item @code{-gnat2005}
8839 Allow full Ada 2005 features (same as @code{-gnat05})
8840 @end table
8842 @geindex -gnat2012 (gcc)
8845 @table @asis
8847 @item @code{-gnat2012}
8849 Allow full Ada 2012 features (same as @code{-gnat12})
8850 @end table
8852 @geindex -gnat2022 (gcc)
8855 @table @asis
8857 @item @code{-gnat2022}
8859 Allow full Ada 2022 features
8861 @item @code{-gnat83}
8863 Enforce Ada 83 restrictions.
8864 @end table
8866 @geindex -gnat95 (gcc)
8869 @table @asis
8871 @item @code{-gnat95}
8873 Enforce Ada 95 restrictions.
8875 Note: for compatibility with some Ada 95 compilers which support only
8876 the @code{overriding} keyword of Ada 2005, the @code{-gnatd.D} switch can
8877 be used along with @code{-gnat95} to achieve a similar effect with GNAT.
8879 @code{-gnatd.D} instructs GNAT to consider @code{overriding} as a keyword
8880 and handle its associated semantic checks, even in Ada 95 mode.
8881 @end table
8883 @geindex -gnata (gcc)
8886 @table @asis
8888 @item @code{-gnata}
8890 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
8891 activated. Note that these pragmas can also be controlled using the
8892 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
8893 It also activates pragmas @code{Check}, @code{Precondition}, and
8894 @code{Postcondition}. Note that these pragmas can also be controlled
8895 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
8896 also activates all assertions defined in the RM as aspects: preconditions,
8897 postconditions, type invariants and (sub)type predicates. In all Ada modes,
8898 corresponding pragmas for type invariants and (sub)type predicates are
8899 also activated. The default is that all these assertions are disabled,
8900 and have no effect, other than being checked for syntactic validity, and
8901 in the case of subtype predicates, constructions such as membership tests
8902 still test predicates even if assertions are turned off.
8903 @end table
8905 @geindex -gnatA (gcc)
8908 @table @asis
8910 @item @code{-gnatA}
8912 Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
8913 it will be ignored.
8914 @end table
8916 @geindex -gnatb (gcc)
8919 @table @asis
8921 @item @code{-gnatb}
8923 Generate brief messages to @code{stderr} even if verbose mode set.
8924 @end table
8926 @geindex -gnatB (gcc)
8929 @table @asis
8931 @item @code{-gnatB}
8933 Assume no invalid (bad) values except for ‘Valid attribute use
8934 (@ref{e9,,Validity Checking}).
8935 @end table
8937 @geindex -gnatc (gcc)
8940 @table @asis
8942 @item @code{-gnatc}
8944 Check syntax and semantics only (no code generation attempted). When the
8945 compiler is invoked by @code{gnatmake}, if the switch @code{-gnatc} is
8946 only given to the compiler (after @code{-cargs} or in package Compiler of
8947 the project file), @code{gnatmake} will fail because it will not find the
8948 object file after compilation. If @code{gnatmake} is called with
8949 @code{-gnatc} as a builder switch (before @code{-cargs} or in package
8950 Builder of the project file) then @code{gnatmake} will not fail because
8951 it will not look for the object files after compilation, and it will not try
8952 to build and link.
8953 @end table
8955 @geindex -gnatC (gcc)
8958 @table @asis
8960 @item @code{-gnatC}
8962 Generate CodePeer intermediate format (no code generation attempted).
8963 This switch will generate an intermediate representation suitable for
8964 use by CodePeer (@code{.scil} files). This switch is not compatible with
8965 code generation (it will, among other things, disable some switches such
8966 as @code{-gnatn}, and enable others such as @code{-gnata}).
8967 @end table
8969 @geindex -gnatd (gcc)
8972 @table @asis
8974 @item @code{-gnatd}
8976 Specify debug options for the compiler. The string of characters after
8977 the @code{-gnatd} specifies the specific debug options. The possible
8978 characters are 0-9, a-z, A-Z, optionally preceded by a dot or underscore.
8979 See compiler source file @code{debug.adb} for details of the implemented
8980 debug options. Certain debug options are relevant to application
8981 programmers, and these are documented at appropriate points in this
8982 user’s guide.
8983 @end table
8985 @geindex -gnatD[nn] (gcc)
8988 @table @asis
8990 @item @code{-gnatD}
8992 Create expanded source files for source level debugging. This switch
8993 also suppresses generation of cross-reference information
8994 (see @code{-gnatx}). Note that this switch is not allowed if a previous
8995 @code{-gnatR} switch has been given, since these two switches are not compatible.
8996 @end table
8998 @geindex -gnateA (gcc)
9001 @table @asis
9003 @item @code{-gnateA}
9005 Check that the actual parameters of a subprogram call are not aliases of one
9006 another. To qualify as aliasing, their memory locations must be identical or
9007 overlapping, at least one of the corresponding formal parameters must be of
9008 mode OUT or IN OUT, and at least one of the corresponding formal parameters
9009 must have its parameter passing mechanism not specified.
9011 @example
9012 type Rec_Typ is record
9013    Data : Integer := 0;
9014 end record;
9016 function Self (Val : Rec_Typ) return Rec_Typ is
9017 begin
9018    return Val;
9019 end Self;
9021 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
9022 begin
9023    null;
9024 end Detect_Aliasing;
9026 Obj : Rec_Typ;
9028 Detect_Aliasing (Obj, Obj);
9029 Detect_Aliasing (Obj, Self (Obj));
9030 @end example
9032 In the example above, the first call to @code{Detect_Aliasing} fails with a
9033 @code{Program_Error} at run time because the actuals for @code{Val_1} and
9034 @code{Val_2} denote the same object. The second call executes without raising
9035 an exception because @code{Self(Obj)} produces an anonymous object which does
9036 not share the memory location of @code{Obj}.
9037 @end table
9039 @geindex -gnateb (gcc)
9042 @table @asis
9044 @item @code{-gnateb}
9046 Store configuration files by their basename in ALI files. This switch is
9047 used for instance by gprbuild for distributed builds in order to prevent
9048 issues where machine-specific absolute paths could end up being stored in
9049 ALI files.
9050 @end table
9052 @geindex -gnatec (gcc)
9055 @table @asis
9057 @item @code{-gnatec=@emph{path}}
9059 Specify a configuration pragma file
9060 (the equal sign is optional)
9061 (@ref{63,,The Configuration Pragmas Files}).
9062 @end table
9064 @geindex -gnateC (gcc)
9067 @table @asis
9069 @item @code{-gnateC}
9071 Generate CodePeer messages in a compiler-like format. This switch is only
9072 effective if @code{-gnatcC} is also specified and requires an installation
9073 of CodePeer.
9074 @end table
9076 @geindex -gnated (gcc)
9079 @table @asis
9081 @item @code{-gnated}
9083 Disable atomic synchronization
9084 @end table
9086 @geindex -gnateD (gcc)
9089 @table @asis
9091 @item @code{-gnateDsymbol[=@emph{value}]}
9093 Defines a symbol, associated with @code{value}, for preprocessing.
9094 (@ref{91,,Integrated Preprocessing}).
9095 @end table
9097 @geindex -gnateE (gcc)
9100 @table @asis
9102 @item @code{-gnateE}
9104 Generate extra information in exception messages. In particular, display
9105 extra column information and the value and range associated with index and
9106 range check failures, and extra column information for access checks.
9107 In cases where the compiler is able to determine at compile time that
9108 a check will fail, it gives a warning, and the extra information is not
9109 produced at run time.
9110 @end table
9112 @geindex -gnatef (gcc)
9115 @table @asis
9117 @item @code{-gnatef}
9119 Display full source path name in brief error messages and absolute paths in
9120 @code{-fdiagnostics-format=json}’s output.
9121 @end table
9123 @geindex -gnateF (gcc)
9126 @table @asis
9128 @item @code{-gnateF}
9130 Check for overflow on all floating-point operations, including those
9131 for unconstrained predefined types. See description of pragma
9132 @code{Check_Float_Overflow} in GNAT RM.
9133 @end table
9135 @geindex -gnateg (gcc)
9137 @code{-gnateg}
9138 @code{-gnatceg}
9140 @quotation
9142 The @code{-gnatc} switch must always be specified before this switch, e.g.
9143 @code{-gnatceg}. Generate a C header from the Ada input file. See
9144 @ref{b9,,Generating C Headers for Ada Specifications} for more
9145 information.
9146 @end quotation
9148 @geindex -gnateG (gcc)
9151 @table @asis
9153 @item @code{-gnateG}
9155 Save result of preprocessing in a text file.
9156 @end table
9158 @geindex -gnateH (gcc)
9161 @table @asis
9163 @item @code{-gnateH}
9165 Set the threshold from which the RM 13.5.1(13.3/2) clause applies to 64.
9166 This is useful only on 64-bit plaforms where this threshold is 128, but
9167 used to be 64 in earlier versions of the compiler.
9168 @end table
9170 @geindex -gnatei (gcc)
9173 @table @asis
9175 @item @code{-gnatei@emph{nnn}}
9177 Set maximum number of instantiations during compilation of a single unit to
9178 @code{nnn}. This may be useful in increasing the default maximum of 8000 for
9179 the rare case when a single unit legitimately exceeds this limit.
9180 @end table
9182 @geindex -gnateI (gcc)
9185 @table @asis
9187 @item @code{-gnateI@emph{nnn}}
9189 Indicates that the source is a multi-unit source and that the index of the
9190 unit to compile is @code{nnn}. @code{nnn} needs to be a positive number and need
9191 to be a valid index in the multi-unit source.
9192 @end table
9194 @geindex -gnatel (gcc)
9197 @table @asis
9199 @item @code{-gnatel}
9201 This switch can be used with the static elaboration model to issue info
9202 messages showing
9203 where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
9204 are generated. This is useful in diagnosing elaboration circularities
9205 caused by these implicit pragmas when using the static elaboration
9206 model. See the section in this guide on elaboration checking for
9207 further details. These messages are not generated by default, and are
9208 intended only for temporary use when debugging circularity problems.
9209 @end table
9211 @geindex -gnatel (gcc)
9214 @table @asis
9216 @item @code{-gnateL}
9218 This switch turns off the info messages about implicit elaboration pragmas.
9219 @end table
9221 @geindex -gnatem (gcc)
9224 @table @asis
9226 @item @code{-gnatem=@emph{path}}
9228 Specify a mapping file
9229 (the equal sign is optional)
9230 (@ref{ea,,Units to Sources Mapping Files}).
9231 @end table
9233 @geindex -gnatep (gcc)
9236 @table @asis
9238 @item @code{-gnatep=@emph{file}}
9240 Specify a preprocessing data file
9241 (the equal sign is optional)
9242 (@ref{91,,Integrated Preprocessing}).
9243 @end table
9245 @geindex -gnateP (gcc)
9248 @table @asis
9250 @item @code{-gnateP}
9252 Turn categorization dependency errors into warnings.
9253 Ada requires that units that WITH one another have compatible categories, for
9254 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9255 these errors become warnings (which can be ignored, or suppressed in the usual
9256 manner). This can be useful in some specialized circumstances such as the
9257 temporary use of special test software.
9258 @end table
9260 @geindex -gnateS (gcc)
9263 @table @asis
9265 @item @code{-gnateS}
9267 Synonym of @code{-fdump-scos}, kept for backwards compatibility.
9268 @end table
9270 @geindex -gnatet=file (gcc)
9273 @table @asis
9275 @item @code{-gnatet=@emph{path}}
9277 Generate target dependent information. The format of the output file is
9278 described in the section about switch @code{-gnateT}.
9279 @end table
9281 @geindex -gnateT (gcc)
9284 @table @asis
9286 @item @code{-gnateT=@emph{path}}
9288 Read target dependent information, such as endianness or sizes and alignments
9289 of base type. If this switch is passed, the default target dependent
9290 information of the compiler is replaced by the one read from the input file.
9291 This is used by tools other than the compiler, e.g. to do
9292 semantic analysis of programs that will run on some other target than
9293 the machine on which the tool is run.
9295 The following target dependent values should be defined,
9296 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
9297 positive integer value, and fields marked with a question mark are
9298 boolean fields, where a value of 0 is False, and a value of 1 is True:
9300 @example
9301 Bits_BE                    : Nat; -- Bits stored big-endian?
9302 Bits_Per_Unit              : Pos; -- Bits in a storage unit
9303 Bits_Per_Word              : Pos; -- Bits in a word
9304 Bytes_BE                   : Nat; -- Bytes stored big-endian?
9305 Char_Size                  : Pos; -- Standard.Character'Size
9306 Double_Float_Alignment     : Nat; -- Alignment of double float
9307 Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
9308 Double_Size                : Pos; -- Standard.Long_Float'Size
9309 Float_Size                 : Pos; -- Standard.Float'Size
9310 Float_Words_BE             : Nat; -- Float words stored big-endian?
9311 Int_Size                   : Pos; -- Standard.Integer'Size
9312 Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
9313 Long_Long_Long_Size        : Pos; -- Standard.Long_Long_Long_Integer'Size
9314 Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
9315 Long_Size                  : Pos; -- Standard.Long_Integer'Size
9316 Maximum_Alignment          : Pos; -- Maximum permitted alignment
9317 Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
9318 Pointer_Size               : Pos; -- System.Address'Size
9319 Short_Enums                : Nat; -- Foreign enums use short size?
9320 Short_Size                 : Pos; -- Standard.Short_Integer'Size
9321 Strict_Alignment           : Nat; -- Strict alignment?
9322 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9323 Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
9324 Words_BE                   : Nat; -- Words stored big-endian?
9325 @end example
9327 @code{Bits_Per_Unit} is the number of bits in a storage unit, the equivalent of
9328 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.}
9330 @code{Bits_Per_Word} is the number of bits in a machine word, the equivalent of
9331 GCC macro @code{BITS_PER_WORD} documented as follows: @cite{Number of bits in a word; normally 32.}
9333 @code{Double_Float_Alignment}, if not zero, is the maximum alignment that the
9334 compiler can choose by default for a 64-bit floating-point type or object.
9336 @code{Double_Scalar_Alignment}, if not zero, is the maximum alignment that the
9337 compiler can choose by default for a 64-bit or larger scalar type or object.
9339 @code{Maximum_Alignment} is the maximum alignment that the compiler can choose
9340 by default for a type or object, which is also the maximum alignment that can
9341 be specified in GNAT. It is computed for GCC backends as @code{BIGGEST_ALIGNMENT
9342 / BITS_PER_UNIT} where GCC macro @code{BIGGEST_ALIGNMENT} is documented as
9343 follows: @cite{Biggest alignment that any data type can require on this machine@comma{} in bits.}
9345 @code{Max_Unaligned_Field} is the maximum size for unaligned bit field, which is
9346 64 for the majority of GCC targets (but can be different on some targets).
9348 @code{Strict_Alignment} is the equivalent of GCC macro @code{STRICT_ALIGNMENT}
9349 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.}
9351 @code{System_Allocator_Alignment} is the guaranteed alignment of data returned
9352 by calls to @code{malloc}.
9354 The format of the input file is as follows. First come the values of
9355 the variables defined above, with one line per value:
9357 @example
9358 name  value
9359 @end example
9361 where @code{name} is the name of the parameter, spelled out in full,
9362 and cased as in the above list, and @code{value} is an unsigned decimal
9363 integer. Two or more blanks separates the name from the value.
9365 All the variables must be present, in alphabetical order (i.e. the
9366 same order as the list above).
9368 Then there is a blank line to separate the two parts of the file. Then
9369 come the lines showing the floating-point types to be registered, with
9370 one line per registered mode:
9372 @example
9373 name  digs float_rep size alignment
9374 @end example
9376 where @code{name} is the string name of the type (which can have
9377 single spaces embedded in the name, e.g. long double), @code{digs} is
9378 the number of digits for the floating-point type, @code{float_rep} is
9379 the float representation (I for IEEE-754-Binary, which is
9380 the only one supported at this time),
9381 @code{size} is the size in bits, @code{alignment} is the
9382 alignment in bits. The name is followed by at least two blanks, fields
9383 are separated by at least one blank, and a LF character immediately
9384 follows the alignment field.
9386 Here is an example of a target parameterization file:
9388 @example
9389 Bits_BE                       0
9390 Bits_Per_Unit                 8
9391 Bits_Per_Word                64
9392 Bytes_BE                      0
9393 Char_Size                     8
9394 Double_Float_Alignment        0
9395 Double_Scalar_Alignment       0
9396 Double_Size                  64
9397 Float_Size                   32
9398 Float_Words_BE                0
9399 Int_Size                     64
9400 Long_Double_Size            128
9401 Long_Long_Long_Size         128
9402 Long_Long_Size               64
9403 Long_Size                    64
9404 Maximum_Alignment            16
9405 Max_Unaligned_Field          64
9406 Pointer_Size                 64
9407 Short_Size                   16
9408 Strict_Alignment              0
9409 System_Allocator_Alignment   16
9410 Wchar_T_Size                 32
9411 Words_BE                      0
9413 float         15  I  64  64
9414 double        15  I  64  64
9415 long double   18  I  80 128
9416 TF            33  I 128 128
9417 @end example
9418 @end table
9420 @geindex -gnateu (gcc)
9423 @table @asis
9425 @item @code{-gnateu}
9427 Ignore unrecognized validity, warning, and style switches that
9428 appear after this switch is given. This may be useful when
9429 compiling sources developed on a later version of the compiler
9430 with an earlier version. Of course the earlier version must
9431 support this switch.
9432 @end table
9434 @geindex -gnateV (gcc)
9437 @table @asis
9439 @item @code{-gnateV}
9441 Check that all actual parameters of a subprogram call are valid according to
9442 the rules of validity checking (@ref{e9,,Validity Checking}).
9443 @end table
9445 @geindex -gnateY (gcc)
9448 @table @asis
9450 @item @code{-gnateY}
9452 Ignore all STYLE_CHECKS pragmas. Full legality checks
9453 are still carried out, but the pragmas have no effect
9454 on what style checks are active. This allows all style
9455 checking options to be controlled from the command line.
9456 @end table
9458 @geindex -gnatE (gcc)
9461 @table @asis
9463 @item @code{-gnatE}
9465 Dynamic elaboration checking mode enabled. For further details see
9466 @ref{f,,Elaboration Order Handling in GNAT}.
9467 @end table
9469 @geindex -gnatf (gcc)
9472 @table @asis
9474 @item @code{-gnatf}
9476 Full errors. Multiple errors per line, all undefined references, do not
9477 attempt to suppress cascaded errors.
9478 @end table
9480 @geindex -gnatF (gcc)
9483 @table @asis
9485 @item @code{-gnatF}
9487 Externals names are folded to all uppercase.
9488 @end table
9490 @geindex -gnatg (gcc)
9493 @table @asis
9495 @item @code{-gnatg}
9497 Internal GNAT implementation mode. This should not be used for applications
9498 programs, it is intended only for use by the compiler and its run-time
9499 library. For documentation, see the GNAT sources. Note that @code{-gnatg}
9500 implies @code{-gnatw.ge} and @code{-gnatyg} so that all standard
9501 warnings and all standard style options are turned on. All warnings and style
9502 messages are treated as errors.
9503 @end table
9505 @geindex -gnatG[nn] (gcc)
9508 @table @asis
9510 @item @code{-gnatG=nn}
9512 List generated expanded code in source form.
9513 @end table
9515 @geindex -gnath (gcc)
9518 @table @asis
9520 @item @code{-gnath}
9522 Output usage information. The output is written to @code{stdout}.
9523 @end table
9525 @geindex -gnatH (gcc)
9528 @table @asis
9530 @item @code{-gnatH}
9532 Legacy elaboration-checking mode enabled. When this switch is in effect,
9533 the pre-18.x access-before-elaboration model becomes the de facto model.
9534 For further details see @ref{f,,Elaboration Order Handling in GNAT}.
9535 @end table
9537 @geindex -gnati (gcc)
9540 @table @asis
9542 @item @code{-gnati@emph{c}}
9544 Identifier character set (@code{c} = 1/2/3/4/5/9/p/8/f/n/w).
9545 For details of the possible selections for @code{c},
9546 see @ref{31,,Character Set Control}.
9547 @end table
9549 @geindex -gnatI (gcc)
9552 @table @asis
9554 @item @code{-gnatI}
9556 Ignore representation clauses. When this switch is used,
9557 representation clauses are treated as comments. This is useful
9558 when initially porting code where you want to ignore rep clause
9559 problems, and also for compiling foreign code (particularly
9560 for use with ASIS). The representation clauses that are ignored
9561 are: enumeration_representation_clause, record_representation_clause,
9562 and attribute_definition_clause for the following attributes:
9563 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9564 Object_Size, Scalar_Storage_Order, Size, Small, Stream_Size,
9565 and Value_Size. Pragma Default_Scalar_Storage_Order is also ignored.
9566 Note that this option should be used only for compiling – the
9567 code is likely to malfunction at run time.
9568 @end table
9570 @geindex -gnatjnn (gcc)
9573 @table @asis
9575 @item @code{-gnatj@emph{nn}}
9577 Reformat error messages to fit on @code{nn} character lines
9578 @end table
9580 @geindex -gnatJ (gcc)
9583 @table @asis
9585 @item @code{-gnatJ}
9587 Permissive elaboration-checking mode enabled. When this switch is in effect,
9588 the post-18.x access-before-elaboration model ignores potential issues with:
9591 @itemize -
9593 @item 
9594 Accept statements
9596 @item 
9597 Activations of tasks defined in instances
9599 @item 
9600 Assertion pragmas
9602 @item 
9603 Calls from within an instance to its enclosing context
9605 @item 
9606 Calls through generic formal parameters
9608 @item 
9609 Calls to subprograms defined in instances
9611 @item 
9612 Entry calls
9614 @item 
9615 Indirect calls using ‘Access
9617 @item 
9618 Requeue statements
9620 @item 
9621 Select statements
9623 @item 
9624 Synchronous task suspension
9625 @end itemize
9627 and does not emit compile-time diagnostics or run-time checks. For further
9628 details see @ref{f,,Elaboration Order Handling in GNAT}.
9629 @end table
9631 @geindex -gnatk (gcc)
9634 @table @asis
9636 @item @code{-gnatk=@emph{n}}
9638 Limit file names to @code{n} (1-999) characters (@code{k} = krunch).
9639 @end table
9641 @geindex -gnatl (gcc)
9644 @table @asis
9646 @item @code{-gnatl}
9648 Output full source listing with embedded error messages.
9649 @end table
9651 @geindex -gnatL (gcc)
9654 @table @asis
9656 @item @code{-gnatL}
9658 Used in conjunction with -gnatG or -gnatD to intersperse original
9659 source lines (as comment lines with line numbers) in the expanded
9660 source output.
9661 @end table
9663 @geindex -gnatm (gcc)
9666 @table @asis
9668 @item @code{-gnatm=@emph{n}}
9670 Limit number of detected error or warning messages to @code{n}
9671 where @code{n} is in the range 1..999999. The default setting if
9672 no switch is given is 9999. If the number of warnings reaches this
9673 limit, then a message is output and further warnings are suppressed,
9674 but the compilation is continued. If the number of error messages
9675 reaches this limit, then a message is output and the compilation
9676 is abandoned. The equal sign here is optional. A value of zero
9677 means that no limit applies.
9678 @end table
9680 @geindex -gnatn (gcc)
9683 @table @asis
9685 @item @code{-gnatn[12]}
9687 Activate inlining across units for subprograms for which pragma @code{Inline}
9688 is specified. This inlining is performed by the GCC back-end. An optional
9689 digit sets the inlining level: 1 for moderate inlining across units
9690 or 2 for full inlining across units. If no inlining level is specified,
9691 the compiler will pick it based on the optimization level.
9692 @end table
9694 @geindex -gnatN (gcc)
9697 @table @asis
9699 @item @code{-gnatN}
9701 Activate front end inlining for subprograms for which
9702 pragma @code{Inline} is specified. This inlining is performed
9703 by the front end and will be visible in the
9704 @code{-gnatG} output.
9706 When using a gcc-based back end, then the use of
9707 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
9708 Historically front end inlining was more extensive than the gcc back end
9709 inlining, but that is no longer the case.
9710 @end table
9712 @geindex -gnato0 (gcc)
9715 @table @asis
9717 @item @code{-gnato0}
9719 Suppresses overflow checking. This causes the behavior of the compiler to
9720 match the default for older versions where overflow checking was suppressed
9721 by default. This is equivalent to having
9722 @code{pragma Suppress (Overflow_Check)} in a configuration pragma file.
9723 @end table
9725 @geindex -gnato?? (gcc)
9728 @table @asis
9730 @item @code{-gnato??}
9732 Set default mode for handling generation of code to avoid intermediate
9733 arithmetic overflow. Here @code{??} is two digits, a
9734 single digit, or nothing. Each digit is one of the digits @code{1}
9735 through @code{3}:
9738 @multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
9739 @item
9741 Digit
9743 @tab
9745 Interpretation
9747 @item
9749 @emph{1}
9751 @tab
9753 All intermediate overflows checked against base type (@code{STRICT})
9755 @item
9757 @emph{2}
9759 @tab
9761 Minimize intermediate overflows (@code{MINIMIZED})
9763 @item
9765 @emph{3}
9767 @tab
9769 Eliminate intermediate overflows (@code{ELIMINATED})
9771 @end multitable
9774 If only one digit appears, then it applies to all
9775 cases; if two digits are given, then the first applies outside
9776 assertions, pre/postconditions, and type invariants, and the second
9777 applies within assertions, pre/postconditions, and type invariants.
9779 If no digits follow the @code{-gnato}, then it is equivalent to
9780 @code{-gnato11},
9781 causing all intermediate overflows to be handled in strict
9782 mode.
9784 This switch also causes arithmetic overflow checking to be performed
9785 (as though @code{pragma Unsuppress (Overflow_Check)} had been specified).
9787 The default if no option @code{-gnato} is given is that overflow handling
9788 is in @code{STRICT} mode (computations done using the base type), and that
9789 overflow checking is enabled.
9791 Note that division by zero is a separate check that is not
9792 controlled by this switch (divide-by-zero checking is on by default).
9794 See also @ref{eb,,Specifying the Desired Mode}.
9795 @end table
9797 @geindex -gnatp (gcc)
9800 @table @asis
9802 @item @code{-gnatp}
9804 Suppress all checks. See @ref{ec,,Run-Time Checks} for details. This switch
9805 has no effect if cancelled by a subsequent @code{-gnat-p} switch.
9806 @end table
9808 @geindex -gnat-p (gcc)
9811 @table @asis
9813 @item @code{-gnat-p}
9815 Cancel effect of previous @code{-gnatp} switch.
9816 @end table
9818 @geindex -gnatq (gcc)
9821 @table @asis
9823 @item @code{-gnatq}
9825 Don’t quit. Try semantics, even if parse errors.
9826 @end table
9828 @geindex -gnatQ (gcc)
9831 @table @asis
9833 @item @code{-gnatQ}
9835 Don’t quit. Generate @code{ALI} and tree files even if illegalities.
9836 Note that code generation is still suppressed in the presence of any
9837 errors, so even with @code{-gnatQ} no object file is generated.
9838 @end table
9840 @geindex -gnatr (gcc)
9843 @table @asis
9845 @item @code{-gnatr}
9847 Treat pragma Restrictions as Restriction_Warnings.
9848 @end table
9850 @geindex -gnatR (gcc)
9853 @table @asis
9855 @item @code{-gnatR[0|1|2|3|4][e][j][m][s]}
9857 Output representation information for declared types, objects and
9858 subprograms. Note that this switch is not allowed if a previous
9859 @code{-gnatD} switch has been given, since these two switches
9860 are not compatible.
9861 @end table
9863 @geindex -gnats (gcc)
9866 @table @asis
9868 @item @code{-gnats}
9870 Syntax check only.
9871 @end table
9873 @geindex -gnatS (gcc)
9876 @table @asis
9878 @item @code{-gnatS}
9880 Print package Standard.
9881 @end table
9883 @geindex -gnatT (gcc)
9886 @table @asis
9888 @item @code{-gnatT@emph{nnn}}
9890 All compiler tables start at @code{nnn} times usual starting size.
9891 @end table
9893 @geindex -gnatu (gcc)
9896 @table @asis
9898 @item @code{-gnatu}
9900 List units for this compilation.
9901 @end table
9903 @geindex -gnatU (gcc)
9906 @table @asis
9908 @item @code{-gnatU}
9910 Tag all error messages with the unique string ‘error:’
9911 @end table
9913 @geindex -gnatv (gcc)
9916 @table @asis
9918 @item @code{-gnatv}
9920 Verbose mode. Full error output with source lines to @code{stdout}.
9921 @end table
9923 @geindex -gnatV (gcc)
9926 @table @asis
9928 @item @code{-gnatV}
9930 Control level of validity checking (@ref{e9,,Validity Checking}).
9931 @end table
9933 @geindex -gnatw (gcc)
9936 @table @asis
9938 @item @code{-gnatw@emph{xxx}}
9940 Warning mode where
9941 @code{xxx} is a string of option letters that denotes
9942 the exact warnings that
9943 are enabled or disabled (@ref{ed,,Warning Message Control}).
9944 @end table
9946 @geindex -gnatW (gcc)
9949 @table @asis
9951 @item @code{-gnatW@emph{e}}
9953 Wide character encoding method
9954 (@code{e}=n/h/u/s/e/8).
9955 @end table
9957 @geindex -gnatx (gcc)
9960 @table @asis
9962 @item @code{-gnatx}
9964 Suppress generation of cross-reference information.
9965 @end table
9967 @geindex -gnatX (gcc)
9970 @table @asis
9972 @item @code{-gnatX}
9974 Enable core GNAT implementation extensions and latest Ada version.
9975 @end table
9977 @geindex -gnatX0 (gcc)
9980 @table @asis
9982 @item @code{-gnatX0}
9984 Enable all GNAT implementation extensions and latest Ada version.
9985 @end table
9987 @geindex -gnaty (gcc)
9990 @table @asis
9992 @item @code{-gnaty}
9994 Enable built-in style checks (@ref{ee,,Style Checking}).
9995 @end table
9997 @geindex -gnatz (gcc)
10000 @table @asis
10002 @item @code{-gnatz@emph{m}}
10004 Distribution stub generation and compilation
10005 (@code{m}=r/c for receiver/caller stubs).
10006 @end table
10008 @geindex -I (gcc)
10011 @table @asis
10013 @item @code{-I@emph{dir}}
10015 @geindex RTL
10017 Direct GNAT to search the @code{dir} directory for source files needed by
10018 the current compilation
10019 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
10020 @end table
10022 @geindex -I- (gcc)
10025 @table @asis
10027 @item @code{-I-}
10029 @geindex RTL
10031 Except for the source file named in the command line, do not look for source
10032 files in the directory containing the source file named in the command line
10033 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
10034 @end table
10036 @geindex -o (gcc)
10039 @table @asis
10041 @item @code{-o @emph{file}}
10043 This switch is used in @code{gcc} to redirect the generated object file
10044 and its associated ALI file. Beware of this switch with GNAT, because it may
10045 cause the object file and ALI file to have different names which in turn
10046 may confuse the binder and the linker.
10047 @end table
10049 @geindex -nostdinc (gcc)
10052 @table @asis
10054 @item @code{-nostdinc}
10056 Inhibit the search of the default location for the GNAT Run Time
10057 Library (RTL) source files.
10058 @end table
10060 @geindex -nostdlib (gcc)
10063 @table @asis
10065 @item @code{-nostdlib}
10067 Inhibit the search of the default location for the GNAT Run Time
10068 Library (RTL) ALI files.
10069 @end table
10071 @geindex -O (gcc)
10074 @table @asis
10076 @item @code{-O[@emph{n}]}
10078 @code{n} controls the optimization level:
10081 @multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
10082 @item
10084 @emph{n}
10086 @tab
10088 Effect
10090 @item
10092 @emph{0}
10094 @tab
10096 No optimization, the default setting if no @code{-O} appears
10098 @item
10100 @emph{1}
10102 @tab
10104 Normal optimization, the default if you specify @code{-O} without an
10105 operand. A good compromise between code quality and compilation
10106 time.
10108 @item
10110 @emph{2}
10112 @tab
10114 Extensive optimization, may improve execution time, possibly at
10115 the cost of substantially increased compilation time.
10117 @item
10119 @emph{3}
10121 @tab
10123 Same as @code{-O2}, and also includes inline expansion for small
10124 subprograms in the same unit.
10126 @item
10128 @emph{s}
10130 @tab
10132 Optimize space usage
10134 @end multitable
10137 See also @ref{ef,,Optimization Levels}.
10138 @end table
10140 @geindex -pass-exit-codes (gcc)
10143 @table @asis
10145 @item @code{-pass-exit-codes}
10147 Catch exit codes from the compiler and use the most meaningful as
10148 exit status.
10149 @end table
10151 @geindex --RTS (gcc)
10154 @table @asis
10156 @item @code{--RTS=@emph{rts-path}}
10158 Specifies the default location of the run-time library. Same meaning as the
10159 equivalent @code{gnatmake} flag (@ref{d0,,Switches for gnatmake}).
10160 @end table
10162 @geindex -S (gcc)
10165 @table @asis
10167 @item @code{-S}
10169 Used in place of @code{-c} to
10170 cause the assembler source file to be
10171 generated, using @code{.s} as the extension,
10172 instead of the object file.
10173 This may be useful if you need to examine the generated assembly code.
10174 @end table
10176 @geindex -fverbose-asm (gcc)
10179 @table @asis
10181 @item @code{-fverbose-asm}
10183 Used in conjunction with @code{-S}
10184 to cause the generated assembly code file to be annotated with variable
10185 names, making it significantly easier to follow.
10186 @end table
10188 @geindex -v (gcc)
10191 @table @asis
10193 @item @code{-v}
10195 Show commands generated by the @code{gcc} driver. Normally used only for
10196 debugging purposes or if you need to be sure what version of the
10197 compiler you are executing.
10198 @end table
10200 @geindex -V (gcc)
10203 @table @asis
10205 @item @code{-V @emph{ver}}
10207 Execute @code{ver} version of the compiler. This is the @code{gcc}
10208 version, not the GNAT version.
10209 @end table
10211 @geindex -w (gcc)
10214 @table @asis
10216 @item @code{-w}
10218 Turn off warnings generated by the back end of the compiler. Use of
10219 this switch also causes the default for front end warnings to be set
10220 to suppress (as though @code{-gnatws} had appeared at the start of
10221 the options).
10222 @end table
10224 @geindex Combining GNAT switches
10226 You may combine a sequence of GNAT switches into a single switch. For
10227 example, the combined switch
10229 @quotation
10231 @example
10232 -gnatofi3
10233 @end example
10234 @end quotation
10236 is equivalent to specifying the following sequence of switches:
10238 @quotation
10240 @example
10241 -gnato -gnatf -gnati3
10242 @end example
10243 @end quotation
10245 The following restrictions apply to the combination of switches
10246 in this manner:
10249 @itemize *
10251 @item 
10252 The switch @code{-gnatc} if combined with other switches must come
10253 first in the string.
10255 @item 
10256 The switch @code{-gnats} if combined with other switches must come
10257 first in the string.
10259 @item 
10260 The switches
10261 @code{-gnatzc} and @code{-gnatzr} may not be combined with any other
10262 switches, and only one of them may appear in the command line.
10264 @item 
10265 The switch @code{-gnat-p} may not be combined with any other switch.
10267 @item 
10268 Once a ‘y’ appears in the string (that is a use of the @code{-gnaty}
10269 switch), then all further characters in the switch are interpreted
10270 as style modifiers (see description of @code{-gnaty}).
10272 @item 
10273 Once a ‘d’ appears in the string (that is a use of the @code{-gnatd}
10274 switch), then all further characters in the switch are interpreted
10275 as debug flags (see description of @code{-gnatd}).
10277 @item 
10278 Once a ‘w’ appears in the string (that is a use of the @code{-gnatw}
10279 switch), then all further characters in the switch are interpreted
10280 as warning mode modifiers (see description of @code{-gnatw}).
10282 @item 
10283 Once a ‘V’ appears in the string (that is a use of the @code{-gnatV}
10284 switch), then all further characters in the switch are interpreted
10285 as validity checking options (@ref{e9,,Validity Checking}).
10287 @item 
10288 Option ‘em’, ‘ec’, ‘ep’, ‘l=’ and ‘R’ must be the last options in
10289 a combined list of options.
10290 @end itemize
10292 @node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10293 @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}
10294 @subsection Output and Error Message Control
10297 @geindex stderr
10299 The standard default format for error messages is called ‘brief format’.
10300 Brief format messages are written to @code{stderr} (the standard error
10301 file) and have the following form:
10303 @example
10304 e.adb:3:04: Incorrect spelling of keyword "function"
10305 e.adb:4:20: ";" should be "is"
10306 @end example
10308 The first integer after the file name is the line number in the file,
10309 and the second integer is the column number within the line.
10310 @code{GNAT Studio} can parse the error messages
10311 and point to the referenced character.
10312 The following switches provide control over the error message
10313 format:
10315 @geindex -gnatv (gcc)
10318 @table @asis
10320 @item @code{-gnatv}
10322 The @code{v} stands for verbose.
10323 The effect of this setting is to write long-format error
10324 messages to @code{stdout} (the standard output file).
10325 The same program compiled with the
10326 @code{-gnatv} switch would generate:
10328 @example
10329 3. funcion X (Q : Integer)
10330    |
10331 >>> Incorrect spelling of keyword "function"
10332 4. return Integer;
10333                  |
10334 >>> ";" should be "is"
10335 @end example
10337 The vertical bar indicates the location of the error, and the @code{>>>}
10338 prefix can be used to search for error messages. When this switch is
10339 used the only source lines output are those with errors.
10340 @end table
10342 @geindex -gnatl (gcc)
10345 @table @asis
10347 @item @code{-gnatl}
10349 The @code{l} stands for list.
10350 This switch causes a full listing of
10351 the file to be generated. In the case where a body is
10352 compiled, the corresponding spec is also listed, along
10353 with any subunits. Typical output from compiling a package
10354 body @code{p.adb} might look like:
10356 @example
10357 Compiling: p.adb
10359      1. package body p is
10360      2.    procedure a;
10361      3.    procedure a is separate;
10362      4. begin
10363      5.    null
10364                |
10365         >>> missing ";"
10367      6. end;
10369 Compiling: p.ads
10371      1. package p is
10372      2.    pragma Elaborate_Body
10373                                 |
10374         >>> missing ";"
10376      3. end p;
10378 Compiling: p-a.adb
10380      1. separate p
10381                 |
10382         >>> missing "("
10384      2. procedure a is
10385      3. begin
10386      4.    null
10387                |
10388         >>> missing ";"
10390      5. end;
10391 @end example
10393 When you specify the @code{-gnatv} or @code{-gnatl} switches and
10394 standard output is redirected, a brief summary is written to
10395 @code{stderr} (standard error) giving the number of error messages and
10396 warning messages generated.
10397 @end table
10399 @geindex -gnatl=fname (gcc)
10402 @table @asis
10404 @item @code{-gnatl=@emph{fname}}
10406 This has the same effect as @code{-gnatl} except that the output is
10407 written to a file instead of to standard output. If the given name
10408 @code{fname} does not start with a period, then it is the full name
10409 of the file to be written. If @code{fname} is an extension, it is
10410 appended to the name of the file being compiled. For example, if
10411 file @code{xyz.adb} is compiled with @code{-gnatl=.lst},
10412 then the output is written to file xyz.adb.lst.
10413 @end table
10415 @geindex -gnatU (gcc)
10418 @table @asis
10420 @item @code{-gnatU}
10422 This switch forces all error messages to be preceded by the unique
10423 string ‘error:’. This means that error messages take a few more
10424 characters in space, but allows easy searching for and identification
10425 of error messages.
10426 @end table
10428 @geindex -gnatb (gcc)
10431 @table @asis
10433 @item @code{-gnatb}
10435 The @code{b} stands for brief.
10436 This switch causes GNAT to generate the
10437 brief format error messages to @code{stderr} (the standard error
10438 file) as well as the verbose
10439 format message or full listing (which as usual is written to
10440 @code{stdout}, the standard output file).
10441 @end table
10443 @geindex -gnatm (gcc)
10446 @table @asis
10448 @item @code{-gnatm=@emph{n}}
10450 The @code{m} stands for maximum.
10451 @code{n} is a decimal integer in the
10452 range of 1 to 999999 and limits the number of error or warning
10453 messages to be generated. For example, using
10454 @code{-gnatm2} might yield
10456 @example
10457 e.adb:3:04: Incorrect spelling of keyword "function"
10458 e.adb:5:35: missing ".."
10459 fatal error: maximum number of errors detected
10460 compilation abandoned
10461 @end example
10463 The default setting if
10464 no switch is given is 9999. If the number of warnings reaches this
10465 limit, then a message is output and further warnings are suppressed,
10466 but the compilation is continued. If the number of error messages
10467 reaches this limit, then a message is output and the compilation
10468 is abandoned. A value of zero means that no limit applies.
10470 Note that the equal sign is optional, so the switches
10471 @code{-gnatm2} and @code{-gnatm=2} are equivalent.
10472 @end table
10474 @geindex -gnatf (gcc)
10477 @table @asis
10479 @item @code{-gnatf}
10481 @geindex Error messages
10482 @geindex suppressing
10484 The @code{f} stands for full.
10485 Normally, the compiler suppresses error messages that are likely to be
10486 redundant. This switch causes all error
10487 messages to be generated. In particular, in the case of
10488 references to undefined variables. If a given variable is referenced
10489 several times, the normal format of messages is
10491 @example
10492 e.adb:7:07: "V" is undefined (more references follow)
10493 @end example
10495 where the parenthetical comment warns that there are additional
10496 references to the variable @code{V}. Compiling the same program with the
10497 @code{-gnatf} switch yields
10499 @example
10500 e.adb:7:07: "V" is undefined
10501 e.adb:8:07: "V" is undefined
10502 e.adb:8:12: "V" is undefined
10503 e.adb:8:16: "V" is undefined
10504 e.adb:9:07: "V" is undefined
10505 e.adb:9:12: "V" is undefined
10506 @end example
10508 The @code{-gnatf} switch also generates additional information for
10509 some error messages.  Some examples are:
10512 @itemize *
10514 @item 
10515 Details on possibly non-portable unchecked conversion
10517 @item 
10518 List possible interpretations for ambiguous calls
10520 @item 
10521 Additional details on incorrect parameters
10522 @end itemize
10523 @end table
10525 @geindex -gnatjnn (gcc)
10528 @table @asis
10530 @item @code{-gnatjnn}
10532 In normal operation mode (or if @code{-gnatj0} is used), then error messages
10533 with continuation lines are treated as though the continuation lines were
10534 separate messages (and so a warning with two continuation lines counts as
10535 three warnings, and is listed as three separate messages).
10537 If the @code{-gnatjnn} switch is used with a positive value for nn, then
10538 messages are output in a different manner. A message and all its continuation
10539 lines are treated as a unit, and count as only one warning or message in the
10540 statistics totals. Furthermore, the message is reformatted so that no line
10541 is longer than nn characters.
10542 @end table
10544 @geindex -gnatq (gcc)
10547 @table @asis
10549 @item @code{-gnatq}
10551 The @code{q} stands for quit (really ‘don’t quit’).
10552 In normal operation mode, the compiler first parses the program and
10553 determines if there are any syntax errors. If there are, appropriate
10554 error messages are generated and compilation is immediately terminated.
10555 This switch tells
10556 GNAT to continue with semantic analysis even if syntax errors have been
10557 found. This may enable the detection of more errors in a single run. On
10558 the other hand, the semantic analyzer is more likely to encounter some
10559 internal fatal error when given a syntactically invalid tree.
10560 @end table
10562 @geindex -gnatQ (gcc)
10565 @table @asis
10567 @item @code{-gnatQ}
10569 In normal operation mode, the @code{ALI} file is not generated if any
10570 illegalities are detected in the program. The use of @code{-gnatQ} forces
10571 generation of the @code{ALI} file. This file is marked as being in
10572 error, so it cannot be used for binding purposes, but it does contain
10573 reasonably complete cross-reference information, and thus may be useful
10574 for use by tools (e.g., semantic browsing tools or integrated development
10575 environments) that are driven from the @code{ALI} file. This switch
10576 implies @code{-gnatq}, since the semantic phase must be run to get a
10577 meaningful ALI file.
10579 When @code{-gnatQ} is used and the generated @code{ALI} file is marked as
10580 being in error, @code{gnatmake} will attempt to recompile the source when it
10581 finds such an @code{ALI} file, including with switch @code{-gnatc}.
10583 Note that @code{-gnatQ} has no effect if @code{-gnats} is specified,
10584 since ALI files are never generated if @code{-gnats} is set.
10585 @end table
10587 @node Warning Message Control,Debugging and Assertion Control,Output and Error Message Control,Compiler Switches
10588 @anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{f2}@anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{ed}
10589 @subsection Warning Message Control
10592 @geindex Warning messages
10594 In addition to error messages, which correspond to illegalities as defined
10595 in the Ada Reference Manual, the compiler detects two kinds of warning
10596 situations.
10598 First, the compiler considers some constructs suspicious and generates a
10599 warning message to alert you to a possible error. Second, if the
10600 compiler detects a situation that is sure to raise an exception at
10601 run time, it generates a warning message. The following shows an example
10602 of warning messages:
10604 @example
10605 e.adb:4:24: warning: creation of object may raise Storage_Error
10606 e.adb:10:17: warning: static value out of range
10607 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10608 @end example
10610 GNAT considers a large number of situations as appropriate
10611 for the generation of warning messages. As always, warnings are not
10612 definite indications of errors. For example, if you do an out-of-range
10613 assignment with the deliberate intention of raising a
10614 @code{Constraint_Error} exception, then the warning that may be
10615 issued does not indicate an error. Some of the situations for which GNAT
10616 issues warnings (at least some of the time) are given in the following
10617 list. This list is not complete, and new warnings are often added to
10618 subsequent versions of GNAT. The list is intended to give a general idea
10619 of the kinds of warnings that are generated.
10622 @itemize *
10624 @item 
10625 Possible infinitely recursive calls
10627 @item 
10628 Out-of-range values being assigned
10630 @item 
10631 Possible order of elaboration problems
10633 @item 
10634 Size not a multiple of alignment for a record type
10636 @item 
10637 Assertions (pragma Assert) that are sure to fail
10639 @item 
10640 Unreachable code
10642 @item 
10643 Address clauses with possibly unaligned values, or where an attempt is
10644 made to overlay a smaller variable with a larger one.
10646 @item 
10647 Fixed-point type declarations with a null range
10649 @item 
10650 Direct_IO or Sequential_IO instantiated with a type that has access values
10652 @item 
10653 Variables that are never assigned a value
10655 @item 
10656 Variables that are referenced before being initialized
10658 @item 
10659 Task entries with no corresponding @code{accept} statement
10661 @item 
10662 Duplicate accepts for the same task entry in a @code{select}
10664 @item 
10665 Objects that take too much storage
10667 @item 
10668 Unchecked conversion between types of differing sizes
10670 @item 
10671 Missing @code{return} statement along some execution path in a function
10673 @item 
10674 Incorrect (unrecognized) pragmas
10676 @item 
10677 Incorrect external names
10679 @item 
10680 Allocation from empty storage pool
10682 @item 
10683 Potentially blocking operation in protected type
10685 @item 
10686 Suspicious parenthesization of expressions
10688 @item 
10689 Mismatching bounds in an aggregate
10691 @item 
10692 Attempt to return local value by reference
10694 @item 
10695 Premature instantiation of a generic body
10697 @item 
10698 Attempt to pack aliased components
10700 @item 
10701 Out of bounds array subscripts
10703 @item 
10704 Wrong length on string assignment
10706 @item 
10707 Violations of style rules if style checking is enabled
10709 @item 
10710 Unused @emph{with} clauses
10712 @item 
10713 @code{Bit_Order} usage that does not have any effect
10715 @item 
10716 @code{Standard.Duration} used to resolve universal fixed expression
10718 @item 
10719 Dereference of possibly null value
10721 @item 
10722 Declaration that is likely to cause storage error
10724 @item 
10725 Internal GNAT unit @emph{with}ed by application unit
10727 @item 
10728 Values known to be out of range at compile time
10730 @item 
10731 Unreferenced or unmodified variables. Note that a special
10732 exemption applies to variables which contain any of the substrings
10733 @code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
10734 are considered likely to be intentionally used in a situation where
10735 otherwise a warning would be given, so warnings of this kind are
10736 always suppressed for such variables.
10738 @item 
10739 Address overlays that could clobber memory
10741 @item 
10742 Unexpected initialization when address clause present
10744 @item 
10745 Bad alignment for address clause
10747 @item 
10748 Useless type conversions
10750 @item 
10751 Redundant assignment statements and other redundant constructs
10753 @item 
10754 Useless exception handlers
10756 @item 
10757 Accidental hiding of name by child unit
10759 @item 
10760 Access before elaboration detected at compile time
10762 @item 
10763 A range in a @code{for} loop that is known to be null or might be null
10764 @end itemize
10766 The following section lists compiler switches that are available
10767 to control the handling of warning messages. It is also possible
10768 to exercise much finer control over what warnings are issued and
10769 suppressed using the GNAT pragma Warnings (see the description
10770 of the pragma in the @cite{GNAT_Reference_manual}).
10772 @geindex -gnatwa (gcc)
10775 @table @asis
10777 @item @code{-gnatwa}
10779 @emph{Activate most optional warnings.}
10781 This switch activates most optional warning messages. See the remaining list
10782 in this section for details on optional warning messages that can be
10783 individually controlled.  The warnings that are not turned on by this
10784 switch are:
10787 @itemize *
10789 @item 
10790 @code{-gnatwd} (implicit dereferencing)
10792 @item 
10793 @code{-gnatw.d} (tag warnings with -gnatw switch)
10795 @item 
10796 @code{-gnatwh} (hiding)
10798 @item 
10799 @code{-gnatw.h} (holes in record layouts)
10801 @item 
10802 @code{-gnatw.j} (late primitives of tagged types)
10804 @item 
10805 @code{-gnatw.k} (redefinition of names in standard)
10807 @item 
10808 @code{-gnatwl} (elaboration warnings)
10810 @item 
10811 @code{-gnatw.l} (inherited aspects)
10813 @item 
10814 @code{-gnatw.n} (atomic synchronization)
10816 @item 
10817 @code{-gnatwo} (address clause overlay)
10819 @item 
10820 @code{-gnatw.o} (values set by out parameters ignored)
10822 @item 
10823 @code{-gnatw.q} (questionable layout of record types)
10825 @item 
10826 @code{-gnatw_q} (ignored equality)
10828 @item 
10829 @code{-gnatw_r} (out-of-order record representation clauses)
10831 @item 
10832 @code{-gnatw.s} (overridden size clause)
10834 @item 
10835 @code{-gnatw_s} (ineffective predicate test)
10837 @item 
10838 @code{-gnatwt} (tracking of deleted conditional code)
10840 @item 
10841 @code{-gnatw.u} (unordered enumeration)
10843 @item 
10844 @code{-gnatw.w} (use of Warnings Off)
10846 @item 
10847 @code{-gnatw.y} (reasons for package needing body)
10848 @end itemize
10850 All other optional warnings are turned on.
10851 @end table
10853 @geindex -gnatwA (gcc)
10856 @table @asis
10858 @item @code{-gnatwA}
10860 @emph{Suppress all optional errors.}
10862 This switch suppresses all optional warning messages, see remaining list
10863 in this section for details on optional warning messages that can be
10864 individually controlled. Note that unlike switch @code{-gnatws}, the
10865 use of switch @code{-gnatwA} does not suppress warnings that are
10866 normally given unconditionally and cannot be individually controlled
10867 (for example, the warning about a missing exit path in a function).
10868 Also, again unlike switch @code{-gnatws}, warnings suppressed by
10869 the use of switch @code{-gnatwA} can be individually turned back
10870 on. For example the use of switch @code{-gnatwA} followed by
10871 switch @code{-gnatwd} will suppress all optional warnings except
10872 the warnings for implicit dereferencing.
10873 @end table
10875 @geindex -gnatw.a (gcc)
10878 @table @asis
10880 @item @code{-gnatw.a}
10882 @emph{Activate warnings on failing assertions.}
10884 @geindex Assert failures
10886 This switch activates warnings for assertions where the compiler can tell at
10887 compile time that the assertion will fail. Note that this warning is given
10888 even if assertions are disabled. The default is that such warnings are
10889 generated.
10890 @end table
10892 @geindex -gnatw.A (gcc)
10895 @table @asis
10897 @item @code{-gnatw.A}
10899 @emph{Suppress warnings on failing assertions.}
10901 @geindex Assert failures
10903 This switch suppresses warnings for assertions where the compiler can tell at
10904 compile time that the assertion will fail.
10905 @end table
10907 @geindex -gnatw_a
10910 @table @asis
10912 @item @code{-gnatw_a}
10914 @emph{Activate warnings on anonymous allocators.}
10916 @geindex Anonymous allocators
10918 This switch activates warnings for allocators of anonymous access types,
10919 which can involve run-time accessibility checks and lead to unexpected
10920 accessibility violations. For more details on the rules involved, see
10921 RM 3.10.2 (14).
10922 @end table
10924 @geindex -gnatw_A
10927 @table @asis
10929 @item @code{-gnatw_A}
10931 @emph{Suppress warnings on anonymous allocators.}
10933 @geindex Anonymous allocators
10935 This switch suppresses warnings for anonymous access type allocators.
10936 @end table
10938 @geindex -gnatwb (gcc)
10941 @table @asis
10943 @item @code{-gnatwb}
10945 @emph{Activate warnings on bad fixed values.}
10947 @geindex Bad fixed values
10949 @geindex Fixed-point Small value
10951 @geindex Small value
10953 This switch activates warnings for static fixed-point expressions whose
10954 value is not an exact multiple of Small. Such values are implementation
10955 dependent, since an implementation is free to choose either of the multiples
10956 that surround the value. GNAT always chooses the closer one, but this is not
10957 required behavior, and it is better to specify a value that is an exact
10958 multiple, ensuring predictable execution. The default is that such warnings
10959 are not generated.
10960 @end table
10962 @geindex -gnatwB (gcc)
10965 @table @asis
10967 @item @code{-gnatwB}
10969 @emph{Suppress warnings on bad fixed values.}
10971 This switch suppresses warnings for static fixed-point expressions whose
10972 value is not an exact multiple of Small.
10973 @end table
10975 @geindex -gnatw.b (gcc)
10978 @table @asis
10980 @item @code{-gnatw.b}
10982 @emph{Activate warnings on biased representation.}
10984 @geindex Biased representation
10986 This switch activates warnings when a size clause, value size clause, component
10987 clause, or component size clause forces the use of biased representation for an
10988 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
10989 to represent 10/11). The default is that such warnings are generated.
10990 @end table
10992 @geindex -gnatwB (gcc)
10995 @table @asis
10997 @item @code{-gnatw.B}
10999 @emph{Suppress warnings on biased representation.}
11001 This switch suppresses warnings for representation clauses that force the use
11002 of biased representation.
11003 @end table
11005 @geindex -gnatwc (gcc)
11008 @table @asis
11010 @item @code{-gnatwc}
11012 @emph{Activate warnings on conditionals.}
11014 @geindex Conditionals
11015 @geindex constant
11017 This switch activates warnings for boolean expressions that are known to
11018 be True or False at compile time. The default
11019 is that such warnings are not generated.
11020 Note that this warning does
11021 not get issued for the use of boolean constants whose
11022 values are known at compile time, since this is a standard technique
11023 for conditional compilation in Ada, and this would generate too many
11024 false positive warnings.
11026 This warning option also activates a special test for comparisons using
11027 the operators ‘>=’ and’ <=’.
11028 If the compiler can tell that only the equality condition is possible,
11029 then it will warn that the ‘>’ or ‘<’ part of the test
11030 is useless and that the operator could be replaced by ‘=’.
11031 An example would be comparing a @code{Natural} variable <= 0.
11033 This warning option also generates warnings if
11034 one or both tests is optimized away in a membership test for integer
11035 values if the result can be determined at compile time. Range tests on
11036 enumeration types are not included, since it is common for such tests
11037 to include an end point.
11039 This warning can also be turned on using @code{-gnatwa}.
11040 @end table
11042 @geindex -gnatwC (gcc)
11045 @table @asis
11047 @item @code{-gnatwC}
11049 @emph{Suppress warnings on conditionals.}
11051 This switch suppresses warnings for conditional expressions used in
11052 tests that are known to be True or False at compile time.
11053 @end table
11055 @geindex -gnatw.c (gcc)
11058 @table @asis
11060 @item @code{-gnatw.c}
11062 @emph{Activate warnings on missing component clauses.}
11064 @geindex Component clause
11065 @geindex missing
11067 This switch activates warnings for record components where a record
11068 representation clause is present and has component clauses for the
11069 majority, but not all, of the components. A warning is given for each
11070 component for which no component clause is present.
11071 @end table
11073 @geindex -gnatw.C (gcc)
11076 @table @asis
11078 @item @code{-gnatw.C}
11080 @emph{Suppress warnings on missing component clauses.}
11082 This switch suppresses warnings for record components that are
11083 missing a component clause in the situation described above.
11084 @end table
11086 @geindex -gnatw_c (gcc)
11089 @table @asis
11091 @item @code{-gnatw_c}
11093 @emph{Activate warnings on unknown condition in Compile_Time_Warning.}
11095 @geindex Compile_Time_Warning
11097 @geindex Compile_Time_Error
11099 This switch activates warnings on a pragma Compile_Time_Warning
11100 or Compile_Time_Error whose condition has a value that is not
11101 known at compile time.
11102 The default is that such warnings are generated.
11103 @end table
11105 @geindex -gnatw_C (gcc)
11108 @table @asis
11110 @item @code{-gnatw_C}
11112 @emph{Suppress warnings on unknown condition in Compile_Time_Warning.}
11114 This switch suppresses warnings on a pragma Compile_Time_Warning
11115 or Compile_Time_Error whose condition has a value that is not
11116 known at compile time.
11117 @end table
11119 @geindex -gnatwd (gcc)
11122 @table @asis
11124 @item @code{-gnatwd}
11126 @emph{Activate warnings on implicit dereferencing.}
11128 If this switch is set, then the use of a prefix of an access type
11129 in an indexed component, slice, or selected component without an
11130 explicit @code{.all} will generate a warning. With this warning
11131 enabled, access checks occur only at points where an explicit
11132 @code{.all} appears in the source code (assuming no warnings are
11133 generated as a result of this switch). The default is that such
11134 warnings are not generated.
11135 @end table
11137 @geindex -gnatwD (gcc)
11140 @table @asis
11142 @item @code{-gnatwD}
11144 @emph{Suppress warnings on implicit dereferencing.}
11146 @geindex Implicit dereferencing
11148 @geindex Dereferencing
11149 @geindex implicit
11151 This switch suppresses warnings for implicit dereferences in
11152 indexed components, slices, and selected components.
11153 @end table
11155 @geindex -gnatw.d (gcc)
11158 @table @asis
11160 @item @code{-gnatw.d}
11162 @emph{Activate tagging of warning and info messages.}
11164 If this switch is set, then warning messages are tagged, with one of the
11165 following strings:
11167 @quotation
11170 @itemize -
11172 @item 
11173 @emph{[-gnatw?]}
11174 Used to tag warnings controlled by the switch @code{-gnatwx} where x
11175 is a letter a-z.
11177 @item 
11178 @emph{[-gnatw.?]}
11179 Used to tag warnings controlled by the switch @code{-gnatw.x} where x
11180 is a letter a-z.
11182 @item 
11183 @emph{[-gnatel]}
11184 Used to tag elaboration information (info) messages generated when the
11185 static model of elaboration is used and the @code{-gnatel} switch is set.
11187 @item 
11188 @emph{[restriction warning]}
11189 Used to tag warning messages for restriction violations, activated by use
11190 of the pragma @code{Restriction_Warnings}.
11192 @item 
11193 @emph{[warning-as-error]}
11194 Used to tag warning messages that have been converted to error messages by
11195 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
11196 the string “error: “ rather than “warning: “.
11198 @item 
11199 @emph{[enabled by default]}
11200 Used to tag all other warnings that are always given by default, unless
11201 warnings are completely suppressed using pragma @emph{Warnings(Off)} or
11202 the switch @code{-gnatws}.
11203 @end itemize
11204 @end quotation
11205 @end table
11207 @geindex -gnatw.d (gcc)
11210 @table @asis
11212 @item @code{-gnatw.D}
11214 @emph{Deactivate tagging of warning and info messages messages.}
11216 If this switch is set, then warning messages return to the default
11217 mode in which warnings and info messages are not tagged as described above for
11218 @code{-gnatw.d}.
11219 @end table
11221 @geindex -gnatwe (gcc)
11223 @geindex Warnings
11224 @geindex treat as error
11227 @table @asis
11229 @item @code{-gnatwe}
11231 @emph{Treat warnings and style checks as errors.}
11233 This switch causes warning messages and style check messages to be
11234 treated as errors.
11235 The warning string still appears, but the warning messages are counted
11236 as errors, and prevent the generation of an object file. Note that this
11237 is the only -gnatw switch that affects the handling of style check messages.
11238 Note also that this switch has no effect on info (information) messages, which
11239 are not treated as errors if this switch is present.
11240 @end table
11242 @geindex -gnatw.e (gcc)
11245 @table @asis
11247 @item @code{-gnatw.e}
11249 @emph{Activate every optional warning.}
11251 @geindex Warnings
11252 @geindex activate every optional warning
11254 This switch activates all optional warnings, including those which
11255 are not activated by @code{-gnatwa}. The use of this switch is not
11256 recommended for normal use. If you turn this switch on, it is almost
11257 certain that you will get large numbers of useless warnings. The
11258 warnings that are excluded from @code{-gnatwa} are typically highly
11259 specialized warnings that are suitable for use only in code that has
11260 been specifically designed according to specialized coding rules.
11261 @end table
11263 @geindex -gnatwE (gcc)
11265 @geindex Warnings
11266 @geindex treat as error
11269 @table @asis
11271 @item @code{-gnatwE}
11273 @emph{Treat all run-time exception warnings as errors.}
11275 This switch causes warning messages regarding errors that will be raised
11276 during run-time execution to be treated as errors.
11277 @end table
11279 @geindex -gnatwf (gcc)
11282 @table @asis
11284 @item @code{-gnatwf}
11286 @emph{Activate warnings on unreferenced formals.}
11288 @geindex Formals
11289 @geindex unreferenced
11291 This switch causes a warning to be generated if a formal parameter
11292 is not referenced in the body of the subprogram. This warning can
11293 also be turned on using @code{-gnatwu}. The
11294 default is that these warnings are not generated.
11295 @end table
11297 @geindex -gnatwF (gcc)
11300 @table @asis
11302 @item @code{-gnatwF}
11304 @emph{Suppress warnings on unreferenced formals.}
11306 This switch suppresses warnings for unreferenced formal
11307 parameters. Note that the
11308 combination @code{-gnatwu} followed by @code{-gnatwF} has the
11309 effect of warning on unreferenced entities other than subprogram
11310 formals.
11311 @end table
11313 @geindex -gnatwg (gcc)
11316 @table @asis
11318 @item @code{-gnatwg}
11320 @emph{Activate warnings on unrecognized pragmas.}
11322 @geindex Pragmas
11323 @geindex unrecognized
11325 This switch causes a warning to be generated if an unrecognized
11326 pragma is encountered. Apart from issuing this warning, the
11327 pragma is ignored and has no effect. The default
11328 is that such warnings are issued (satisfying the Ada Reference
11329 Manual requirement that such warnings appear).
11330 @end table
11332 @geindex -gnatwG (gcc)
11335 @table @asis
11337 @item @code{-gnatwG}
11339 @emph{Suppress warnings on unrecognized pragmas.}
11341 This switch suppresses warnings for unrecognized pragmas.
11342 @end table
11344 @geindex -gnatw.g (gcc)
11347 @table @asis
11349 @item @code{-gnatw.g}
11351 @emph{Warnings used for GNAT sources.}
11353 This switch sets the warning categories that are used by the standard
11354 GNAT style. Currently this is equivalent to
11355 @code{-gnatwAao.q.s.CI.V.X.Z}
11356 but more warnings may be added in the future without advanced notice.
11357 @end table
11359 @geindex -gnatwh (gcc)
11362 @table @asis
11364 @item @code{-gnatwh}
11366 @emph{Activate warnings on hiding.}
11368 @geindex Hiding of Declarations
11370 This switch activates warnings on hiding declarations that are considered
11371 potentially confusing. Not all cases of hiding cause warnings; for example an
11372 overriding declaration hides an implicit declaration, which is just normal
11373 code. The default is that warnings on hiding are not generated.
11374 @end table
11376 @geindex -gnatwH (gcc)
11379 @table @asis
11381 @item @code{-gnatwH}
11383 @emph{Suppress warnings on hiding.}
11385 This switch suppresses warnings on hiding declarations.
11386 @end table
11388 @geindex -gnatw.h (gcc)
11391 @table @asis
11393 @item @code{-gnatw.h}
11395 @emph{Activate warnings on holes/gaps in records.}
11397 @geindex Record Representation (gaps)
11399 This switch activates warnings on component clauses in record
11400 representation clauses that leave holes (gaps) in the record layout.
11401 If a record representation clause does not specify a location for
11402 every component of the record type, then the warnings generated (or not
11403 generated) are unspecified. For example, there may be gaps for which
11404 either no warning is generated or a warning is generated that
11405 incorrectly describes the location of the gap. This undesirable situation
11406 can sometimes be avoided by adding (and specifying the location for) unused
11407 fill fields.
11408 @end table
11410 @geindex -gnatw.H (gcc)
11413 @table @asis
11415 @item @code{-gnatw.H}
11417 @emph{Suppress warnings on holes/gaps in records.}
11419 This switch suppresses warnings on component clauses in record
11420 representation clauses that leave holes (haps) in the record layout.
11421 @end table
11423 @geindex -gnatwi (gcc)
11426 @table @asis
11428 @item @code{-gnatwi}
11430 @emph{Activate warnings on implementation units.}
11432 This switch activates warnings for a @emph{with} of an internal GNAT
11433 implementation unit, defined as any unit from the @code{Ada},
11434 @code{Interfaces}, @code{GNAT},
11435 or @code{System}
11436 hierarchies that is not
11437 documented in either the Ada Reference Manual or the GNAT
11438 Programmer’s Reference Manual. Such units are intended only
11439 for internal implementation purposes and should not be @emph{with}ed
11440 by user programs. The default is that such warnings are generated
11441 @end table
11443 @geindex -gnatwI (gcc)
11446 @table @asis
11448 @item @code{-gnatwI}
11450 @emph{Disable warnings on implementation units.}
11452 This switch disables warnings for a @emph{with} of an internal GNAT
11453 implementation unit.
11454 @end table
11456 @geindex -gnatw.i (gcc)
11459 @table @asis
11461 @item @code{-gnatw.i}
11463 @emph{Activate warnings on overlapping actuals.}
11465 This switch enables a warning on statically detectable overlapping actuals in
11466 a subprogram call, when one of the actuals is an in-out parameter, and the
11467 types of the actuals are not by-copy types. This warning is off by default.
11468 @end table
11470 @geindex -gnatw.I (gcc)
11473 @table @asis
11475 @item @code{-gnatw.I}
11477 @emph{Disable warnings on overlapping actuals.}
11479 This switch disables warnings on overlapping actuals in a call.
11480 @end table
11482 @geindex -gnatwj (gcc)
11485 @table @asis
11487 @item @code{-gnatwj}
11489 @emph{Activate warnings on obsolescent features (Annex J).}
11491 @geindex Features
11492 @geindex obsolescent
11494 @geindex Obsolescent features
11496 If this warning option is activated, then warnings are generated for
11497 calls to subprograms marked with @code{pragma Obsolescent} and
11498 for use of features in Annex J of the Ada Reference Manual. In the
11499 case of Annex J, not all features are flagged. In particular, uses of package
11500 @code{ASCII} are not flagged, since these are very common and
11501 would generate many annoying positive warnings. The default is that
11502 such warnings are not generated.
11504 In addition to the above cases, warnings are also generated for
11505 GNAT features that have been provided in past versions but which
11506 have been superseded (typically by features in the new Ada standard).
11507 For example, @code{pragma Ravenscar} will be flagged since its
11508 function is replaced by @code{pragma Profile(Ravenscar)}, and
11509 @code{pragma Interface_Name} will be flagged since its function
11510 is replaced by @code{pragma Import}.
11512 Note that this warning option functions differently from the
11513 restriction @code{No_Obsolescent_Features} in two respects.
11514 First, the restriction applies only to annex J features.
11515 Second, the restriction does flag uses of package @code{ASCII}.
11516 @end table
11518 @geindex -gnatwJ (gcc)
11521 @table @asis
11523 @item @code{-gnatwJ}
11525 @emph{Suppress warnings on obsolescent features (Annex J).}
11527 This switch disables warnings on use of obsolescent features.
11528 @end table
11530 @geindex -gnatw.j (gcc)
11533 @table @asis
11535 @item @code{-gnatw.j}
11537 @emph{Activate warnings on late declarations of tagged type primitives.}
11539 This switch activates warnings on visible primitives added to a
11540 tagged type after deriving a private extension from it.
11541 @end table
11543 @geindex -gnatw.J (gcc)
11546 @table @asis
11548 @item @code{-gnatw.J}
11550 @emph{Suppress warnings on late declarations of tagged type primitives.}
11552 This switch suppresses warnings on visible primitives added to a
11553 tagged type after deriving a private extension from it.
11554 @end table
11556 @geindex -gnatwk (gcc)
11559 @table @asis
11561 @item @code{-gnatwk}
11563 @emph{Activate warnings on variables that could be constants.}
11565 This switch activates warnings for variables that are initialized but
11566 never modified, and then could be declared constants. The default is that
11567 such warnings are not given.
11568 @end table
11570 @geindex -gnatwK (gcc)
11573 @table @asis
11575 @item @code{-gnatwK}
11577 @emph{Suppress warnings on variables that could be constants.}
11579 This switch disables warnings on variables that could be declared constants.
11580 @end table
11582 @geindex -gnatw.k (gcc)
11585 @table @asis
11587 @item @code{-gnatw.k}
11589 @emph{Activate warnings on redefinition of names in standard.}
11591 This switch activates warnings for declarations that declare a name that
11592 is defined in package Standard. Such declarations can be confusing,
11593 especially since the names in package Standard continue to be directly
11594 visible, meaning that use visibility on such redeclared names does not
11595 work as expected. Names of discriminants and components in records are
11596 not included in this check.
11597 @end table
11599 @geindex -gnatwK (gcc)
11602 @table @asis
11604 @item @code{-gnatw.K}
11606 @emph{Suppress warnings on redefinition of names in standard.}
11608 This switch disables warnings for declarations that declare a name that
11609 is defined in package Standard.
11610 @end table
11612 @geindex -gnatwl (gcc)
11615 @table @asis
11617 @item @code{-gnatwl}
11619 @emph{Activate warnings for elaboration pragmas.}
11621 @geindex Elaboration
11622 @geindex warnings
11624 This switch activates warnings for possible elaboration problems,
11625 including suspicious use
11626 of @code{Elaborate} pragmas, when using the static elaboration model, and
11627 possible situations that may raise @code{Program_Error} when using the
11628 dynamic elaboration model.
11629 See the section in this guide on elaboration checking for further details.
11630 The default is that such warnings
11631 are not generated.
11632 @end table
11634 @geindex -gnatwL (gcc)
11637 @table @asis
11639 @item @code{-gnatwL}
11641 @emph{Suppress warnings for elaboration pragmas.}
11643 This switch suppresses warnings for possible elaboration problems.
11644 @end table
11646 @geindex -gnatw.l (gcc)
11649 @table @asis
11651 @item @code{-gnatw.l}
11653 @emph{List inherited aspects.}
11655 This switch causes the compiler to list inherited invariants,
11656 preconditions, and postconditions from Type_Invariant’Class, Invariant’Class,
11657 Pre’Class, and Post’Class aspects. Also list inherited subtype predicates.
11658 @end table
11660 @geindex -gnatw.L (gcc)
11663 @table @asis
11665 @item @code{-gnatw.L}
11667 @emph{Suppress listing of inherited aspects.}
11669 This switch suppresses listing of inherited aspects.
11670 @end table
11672 @geindex -gnatwm (gcc)
11675 @table @asis
11677 @item @code{-gnatwm}
11679 @emph{Activate warnings on modified but unreferenced variables.}
11681 This switch activates warnings for variables that are assigned (using
11682 an initialization value or with one or more assignment statements) but
11683 whose value is never read. The warning is suppressed for volatile
11684 variables and also for variables that are renamings of other variables
11685 or for which an address clause is given.
11686 The default is that these warnings are not given.
11687 @end table
11689 @geindex -gnatwM (gcc)
11692 @table @asis
11694 @item @code{-gnatwM}
11696 @emph{Disable warnings on modified but unreferenced variables.}
11698 This switch disables warnings for variables that are assigned or
11699 initialized, but never read.
11700 @end table
11702 @geindex -gnatw.m (gcc)
11705 @table @asis
11707 @item @code{-gnatw.m}
11709 @emph{Activate warnings on suspicious modulus values.}
11711 This switch activates warnings for modulus values that seem suspicious.
11712 The cases caught are where the size is the same as the modulus (e.g.
11713 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11714 with no size clause. The guess in both cases is that 2**x was intended
11715 rather than x. In addition expressions of the form 2*x for small x
11716 generate a warning (the almost certainly accurate guess being that
11717 2**x was intended). This switch also activates warnings for negative
11718 literal values of a modular type, which are interpreted as large positive
11719 integers after wrap-around. The default is that these warnings are given.
11720 @end table
11722 @geindex -gnatw.M (gcc)
11725 @table @asis
11727 @item @code{-gnatw.M}
11729 @emph{Disable warnings on suspicious modulus values.}
11731 This switch disables warnings for suspicious modulus values.
11732 @end table
11734 @geindex -gnatwn (gcc)
11737 @table @asis
11739 @item @code{-gnatwn}
11741 @emph{Set normal warnings mode.}
11743 This switch sets normal warning mode, in which enabled warnings are
11744 issued and treated as warnings rather than errors. This is the default
11745 mode. the switch @code{-gnatwn} can be used to cancel the effect of
11746 an explicit @code{-gnatws} or
11747 @code{-gnatwe}. It also cancels the effect of the
11748 implicit @code{-gnatwe} that is activated by the
11749 use of @code{-gnatg}.
11750 @end table
11752 @geindex -gnatw.n (gcc)
11754 @geindex Atomic Synchronization
11755 @geindex warnings
11758 @table @asis
11760 @item @code{-gnatw.n}
11762 @emph{Activate warnings on atomic synchronization.}
11764 This switch actives warnings when an access to an atomic variable
11765 requires the generation of atomic synchronization code. These
11766 warnings are off by default.
11767 @end table
11769 @geindex -gnatw.N (gcc)
11772 @table @asis
11774 @item @code{-gnatw.N}
11776 @emph{Suppress warnings on atomic synchronization.}
11778 @geindex Atomic Synchronization
11779 @geindex warnings
11781 This switch suppresses warnings when an access to an atomic variable
11782 requires the generation of atomic synchronization code.
11783 @end table
11785 @geindex -gnatwo (gcc)
11787 @geindex Address Clauses
11788 @geindex warnings
11791 @table @asis
11793 @item @code{-gnatwo}
11795 @emph{Activate warnings on address clause overlays.}
11797 This switch activates warnings for possibly unintended initialization
11798 effects of defining address clauses that cause one variable to overlap
11799 another. The default is that such warnings are generated.
11800 @end table
11802 @geindex -gnatwO (gcc)
11805 @table @asis
11807 @item @code{-gnatwO}
11809 @emph{Suppress warnings on address clause overlays.}
11811 This switch suppresses warnings on possibly unintended initialization
11812 effects of defining address clauses that cause one variable to overlap
11813 another.
11814 @end table
11816 @geindex -gnatw.o (gcc)
11819 @table @asis
11821 @item @code{-gnatw.o}
11823 @emph{Activate warnings on modified but unreferenced out parameters.}
11825 This switch activates warnings for variables that are modified by using
11826 them as actuals for a call to a procedure with an out mode formal, where
11827 the resulting assigned value is never read. It is applicable in the case
11828 where there is more than one out mode formal. If there is only one out
11829 mode formal, the warning is issued by default (controlled by -gnatwu).
11830 The warning is suppressed for volatile
11831 variables and also for variables that are renamings of other variables
11832 or for which an address clause is given.
11833 The default is that these warnings are not given.
11834 @end table
11836 @geindex -gnatw.O (gcc)
11839 @table @asis
11841 @item @code{-gnatw.O}
11843 @emph{Disable warnings on modified but unreferenced out parameters.}
11845 This switch suppresses warnings for variables that are modified by using
11846 them as actuals for a call to a procedure with an out mode formal, where
11847 the resulting assigned value is never read.
11848 @end table
11850 @geindex -gnatwp (gcc)
11852 @geindex Inlining
11853 @geindex warnings
11856 @table @asis
11858 @item @code{-gnatwp}
11860 @emph{Activate warnings on ineffective pragma Inlines.}
11862 This switch activates warnings for failure of front end inlining
11863 (activated by @code{-gnatN}) to inline a particular call. There are
11864 many reasons for not being able to inline a call, including most
11865 commonly that the call is too complex to inline. The default is
11866 that such warnings are not given.
11867 Warnings on ineffective inlining by the gcc back-end can be activated
11868 separately, using the gcc switch -Winline.
11869 @end table
11871 @geindex -gnatwP (gcc)
11874 @table @asis
11876 @item @code{-gnatwP}
11878 @emph{Suppress warnings on ineffective pragma Inlines.}
11880 This switch suppresses warnings on ineffective pragma Inlines. If the
11881 inlining mechanism cannot inline a call, it will simply ignore the
11882 request silently.
11883 @end table
11885 @geindex -gnatw.p (gcc)
11887 @geindex Parameter order
11888 @geindex warnings
11891 @table @asis
11893 @item @code{-gnatw.p}
11895 @emph{Activate warnings on parameter ordering.}
11897 This switch activates warnings for cases of suspicious parameter
11898 ordering when the list of arguments are all simple identifiers that
11899 match the names of the formals, but are in a different order. The
11900 warning is suppressed if any use of named parameter notation is used,
11901 so this is the appropriate way to suppress a false positive (and
11902 serves to emphasize that the “misordering” is deliberate). The
11903 default is that such warnings are not given.
11904 @end table
11906 @geindex -gnatw.P (gcc)
11909 @table @asis
11911 @item @code{-gnatw.P}
11913 @emph{Suppress warnings on parameter ordering.}
11915 This switch suppresses warnings on cases of suspicious parameter
11916 ordering.
11917 @end table
11919 @geindex -gnatw_p (gcc)
11922 @table @asis
11924 @item @code{-gnatw_p}
11926 @emph{Activate warnings for pedantic checks.}
11928 This switch activates warnings for the failure of certain pedantic checks.
11929 The only case currently supported is a check that the subtype_marks given
11930 for corresponding formal parameter and function results in a subprogram
11931 declaration and its body denote the same subtype declaration. The default
11932 is that such warnings are not given.
11933 @end table
11935 @geindex -gnatw_P (gcc)
11938 @table @asis
11940 @item @code{-gnatw_P}
11942 @emph{Suppress warnings for pedantic checks.}
11944 This switch suppresses warnings on violations of pedantic checks.
11945 @end table
11947 @geindex -gnatwq (gcc)
11949 @geindex Parentheses
11950 @geindex warnings
11953 @table @asis
11955 @item @code{-gnatwq}
11957 @emph{Activate warnings on questionable missing parentheses.}
11959 This switch activates warnings for cases where parentheses are not used and
11960 the result is potential ambiguity from a readers point of view. For example
11961 (not a > b) when a and b are modular means ((not a) > b) and very likely the
11962 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
11963 quite likely ((-x) mod 5) was intended. In such situations it seems best to
11964 follow the rule of always parenthesizing to make the association clear, and
11965 this warning switch warns if such parentheses are not present. The default
11966 is that these warnings are given.
11967 @end table
11969 @geindex -gnatwQ (gcc)
11972 @table @asis
11974 @item @code{-gnatwQ}
11976 @emph{Suppress warnings on questionable missing parentheses.}
11978 This switch suppresses warnings for cases where the association is not
11979 clear and the use of parentheses is preferred.
11980 @end table
11982 @geindex -gnatw.q (gcc)
11984 @geindex Layout
11985 @geindex warnings
11988 @table @asis
11990 @item @code{-gnatw.q}
11992 @emph{Activate warnings on questionable layout of record types.}
11994 This switch activates warnings for cases where the default layout of
11995 a record type, that is to say the layout of its components in textual
11996 order of the source code, would very likely cause inefficiencies in
11997 the code generated by the compiler, both in terms of space and speed
11998 during execution. One warning is issued for each problematic component
11999 without representation clause in the nonvariant part and then in each
12000 variant recursively, if any.
12002 The purpose of these warnings is neither to prescribe an optimal layout
12003 nor to force the use of representation clauses, but rather to get rid of
12004 the most blatant inefficiencies in the layout. Therefore, the default
12005 layout is matched against the following synthetic ordered layout and
12006 the deviations are flagged on a component-by-component basis:
12009 @itemize *
12011 @item 
12012 first all components or groups of components whose length is fixed
12013 and a multiple of the storage unit,
12015 @item 
12016 then the remaining components whose length is fixed and not a multiple
12017 of the storage unit,
12019 @item 
12020 then the remaining components whose length doesn’t depend on discriminants
12021 (that is to say, with variable but uniform length for all objects),
12023 @item 
12024 then all components whose length depends on discriminants,
12026 @item 
12027 finally the variant part (if any),
12028 @end itemize
12030 for the nonvariant part and for each variant recursively, if any.
12032 The exact wording of the warning depends on whether the compiler is allowed
12033 to reorder the components in the record type or precluded from doing it by
12034 means of pragma @code{No_Component_Reordering}.
12036 The default is that these warnings are not given.
12037 @end table
12039 @geindex -gnatw.Q (gcc)
12042 @table @asis
12044 @item @code{-gnatw.Q}
12046 @emph{Suppress warnings on questionable layout of record types.}
12048 This switch suppresses warnings for cases where the default layout of
12049 a record type would very likely cause inefficiencies.
12050 @end table
12052 @geindex -gnatw_q (gcc)
12055 @table @asis
12057 @item @code{-gnatw_q}
12059 @emph{Activate warnings for ignored equality operators.}
12061 This switch activates warnings for a user-defined “=” function that does
12062 not compose (i.e. is ignored for a predefined “=” for a composite type
12063 containing a component whose type has the user-defined “=” as
12064 primitive). Note that the user-defined “=” must be a primitive operator
12065 in order to trigger the warning.
12066 See RM-4.5.2(14/3-15/5, 21, 24/3, 32.1/1)
12067 for the exact Ada rules on composability of “=”.
12069 The default is that these warnings are not given.
12070 @end table
12072 @geindex -gnatw_Q (gcc)
12075 @table @asis
12077 @item @code{-gnatw_Q}
12079 @emph{Suppress warnings for ignored equality operators.}
12080 @end table
12082 @geindex -gnatwr (gcc)
12085 @table @asis
12087 @item @code{-gnatwr}
12089 @emph{Activate warnings on redundant constructs.}
12091 This switch activates warnings for redundant constructs. The following
12092 is the current list of constructs regarded as redundant:
12095 @itemize *
12097 @item 
12098 Assignment of an item to itself.
12100 @item 
12101 Type conversion that converts an expression to its own type.
12103 @item 
12104 Use of the attribute @code{Base} where @code{typ'Base} is the same
12105 as @code{typ}.
12107 @item 
12108 Use of pragma @code{Pack} when all components are placed by a record
12109 representation clause.
12111 @item 
12112 Exception handler containing only a reraise statement (raise with no
12113 operand) which has no effect.
12115 @item 
12116 Use of the operator abs on an operand that is known at compile time
12117 to be non-negative
12119 @item 
12120 Comparison of an object or (unary or binary) operation of boolean type to
12121 an explicit True value.
12123 @item 
12124 Import of parent package.
12125 @end itemize
12127 The default is that warnings for redundant constructs are not given.
12128 @end table
12130 @geindex -gnatwR (gcc)
12133 @table @asis
12135 @item @code{-gnatwR}
12137 @emph{Suppress warnings on redundant constructs.}
12139 This switch suppresses warnings for redundant constructs.
12140 @end table
12142 @geindex -gnatw.r (gcc)
12145 @table @asis
12147 @item @code{-gnatw.r}
12149 @emph{Activate warnings for object renaming function.}
12151 This switch activates warnings for an object renaming that renames a
12152 function call, which is equivalent to a constant declaration (as
12153 opposed to renaming the function itself).  The default is that these
12154 warnings are given.
12155 @end table
12157 @geindex -gnatw.R (gcc)
12160 @table @asis
12162 @item @code{-gnatw.R}
12164 @emph{Suppress warnings for object renaming function.}
12166 This switch suppresses warnings for object renaming function.
12167 @end table
12169 @geindex -gnatw_r (gcc)
12172 @table @asis
12174 @item @code{-gnatw_r}
12176 @emph{Activate warnings for out-of-order record representation clauses.}
12178 This switch activates warnings for record representation clauses,
12179 if the order of component declarations, component clauses,
12180 and bit-level layout do not all agree.
12181 The default is that these warnings are not given.
12182 @end table
12184 @geindex -gnatw_R (gcc)
12187 @table @asis
12189 @item @code{-gnatw_R}
12191 @emph{Suppress warnings for out-of-order record representation clauses.}
12192 @end table
12194 @geindex -gnatws (gcc)
12197 @table @asis
12199 @item @code{-gnatws}
12201 @emph{Suppress all warnings.}
12203 This switch completely suppresses the
12204 output of all warning messages from the GNAT front end, including
12205 both warnings that can be controlled by switches described in this
12206 section, and those that are normally given unconditionally. The
12207 effect of this suppress action can only be cancelled by a subsequent
12208 use of the switch @code{-gnatwn}.
12210 Note that switch @code{-gnatws} does not suppress
12211 warnings from the @code{gcc} back end.
12212 To suppress these back end warnings as well, use the switch @code{-w}
12213 in addition to @code{-gnatws}. Also this switch has no effect on the
12214 handling of style check messages.
12215 @end table
12217 @geindex -gnatw.s (gcc)
12219 @geindex Record Representation (component sizes)
12222 @table @asis
12224 @item @code{-gnatw.s}
12226 @emph{Activate warnings on overridden size clauses.}
12228 This switch activates warnings on component clauses in record
12229 representation clauses where the length given overrides that
12230 specified by an explicit size clause for the component type. A
12231 warning is similarly given in the array case if a specified
12232 component size overrides an explicit size clause for the array
12233 component type.
12234 @end table
12236 @geindex -gnatw.S (gcc)
12239 @table @asis
12241 @item @code{-gnatw.S}
12243 @emph{Suppress warnings on overridden size clauses.}
12245 This switch suppresses warnings on component clauses in record
12246 representation clauses that override size clauses, and similar
12247 warnings when an array component size overrides a size clause.
12248 @end table
12250 @geindex -gnatw_s (gcc)
12252 @geindex Warnings
12255 @table @asis
12257 @item @code{-gnatw_s}
12259 @emph{Activate warnings on ineffective predicate tests.}
12261 This switch activates warnings on Static_Predicate aspect
12262 specifications that test for values that do not belong to
12263 the parent subtype. Not all such ineffective tests are detected.
12264 @end table
12266 @geindex -gnatw_S (gcc)
12269 @table @asis
12271 @item @code{-gnatw_S}
12273 @emph{Suppress warnings on ineffective predicate tests.}
12275 This switch suppresses warnings on Static_Predicate aspect
12276 specifications that test for values that do not belong to
12277 the parent subtype.
12278 @end table
12280 @geindex -gnatwt (gcc)
12282 @geindex Deactivated code
12283 @geindex warnings
12285 @geindex Deleted code
12286 @geindex warnings
12289 @table @asis
12291 @item @code{-gnatwt}
12293 @emph{Activate warnings for tracking of deleted conditional code.}
12295 This switch activates warnings for tracking of code in conditionals (IF and
12296 CASE statements) that is detected to be dead code which cannot be executed, and
12297 which is removed by the front end. This warning is off by default. This may be
12298 useful for detecting deactivated code in certified applications.
12299 @end table
12301 @geindex -gnatwT (gcc)
12304 @table @asis
12306 @item @code{-gnatwT}
12308 @emph{Suppress warnings for tracking of deleted conditional code.}
12310 This switch suppresses warnings for tracking of deleted conditional code.
12311 @end table
12313 @geindex -gnatw.t (gcc)
12316 @table @asis
12318 @item @code{-gnatw.t}
12320 @emph{Activate warnings on suspicious contracts.}
12322 This switch activates warnings on suspicious contracts. This includes
12323 warnings on suspicious postconditions (whether a pragma @code{Postcondition} or a
12324 @code{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
12325 @code{Contract_Cases}). A function postcondition or contract case is suspicious
12326 when no postcondition or contract case for this function mentions the result
12327 of the function.  A procedure postcondition or contract case is suspicious
12328 when it only refers to the pre-state of the procedure, because in that case
12329 it should rather be expressed as a precondition. This switch also controls
12330 warnings on suspicious cases of expressions typically found in contracts like
12331 quantified expressions and uses of Update attribute. The default is that such
12332 warnings are generated.
12333 @end table
12335 @geindex -gnatw.T (gcc)
12338 @table @asis
12340 @item @code{-gnatw.T}
12342 @emph{Suppress warnings on suspicious contracts.}
12344 This switch suppresses warnings on suspicious contracts.
12345 @end table
12347 @geindex -gnatwu (gcc)
12350 @table @asis
12352 @item @code{-gnatwu}
12354 @emph{Activate warnings on unused entities.}
12356 This switch activates warnings to be generated for entities that
12357 are declared but not referenced, and for units that are @emph{with}ed
12358 and not
12359 referenced. In the case of packages, a warning is also generated if
12360 no entities in the package are referenced. This means that if a with’ed
12361 package is referenced but the only references are in @code{use}
12362 clauses or @code{renames}
12363 declarations, a warning is still generated. A warning is also generated
12364 for a generic package that is @emph{with}ed but never instantiated.
12365 In the case where a package or subprogram body is compiled, and there
12366 is a @emph{with} on the corresponding spec
12367 that is only referenced in the body,
12368 a warning is also generated, noting that the
12369 @emph{with} can be moved to the body. The default is that
12370 such warnings are not generated.
12371 This switch also activates warnings on unreferenced formals
12372 (it includes the effect of @code{-gnatwf}).
12373 @end table
12375 @geindex -gnatwU (gcc)
12378 @table @asis
12380 @item @code{-gnatwU}
12382 @emph{Suppress warnings on unused entities.}
12384 This switch suppresses warnings for unused entities and packages.
12385 It also turns off warnings on unreferenced formals (and thus includes
12386 the effect of @code{-gnatwF}).
12387 @end table
12389 @geindex -gnatw.u (gcc)
12392 @table @asis
12394 @item @code{-gnatw.u}
12396 @emph{Activate warnings on unordered enumeration types.}
12398 This switch causes enumeration types to be considered as conceptually
12399 unordered, unless an explicit pragma @code{Ordered} is given for the type.
12400 The effect is to generate warnings in clients that use explicit comparisons
12401 or subranges, since these constructs both treat objects of the type as
12402 ordered. (A @emph{client} is defined as a unit that is other than the unit in
12403 which the type is declared, or its body or subunits.) Please refer to
12404 the description of pragma @code{Ordered} in the
12405 @cite{GNAT Reference Manual} for further details.
12406 The default is that such warnings are not generated.
12407 @end table
12409 @geindex -gnatw.U (gcc)
12412 @table @asis
12414 @item @code{-gnatw.U}
12416 @emph{Deactivate warnings on unordered enumeration types.}
12418 This switch causes all enumeration types to be considered as ordered, so
12419 that no warnings are given for comparisons or subranges for any type.
12420 @end table
12422 @geindex -gnatwv (gcc)
12424 @geindex Unassigned variable warnings
12427 @table @asis
12429 @item @code{-gnatwv}
12431 @emph{Activate warnings on unassigned variables.}
12433 This switch activates warnings for access to variables which
12434 may not be properly initialized. The default is that
12435 such warnings are generated. This switch will also be emitted when
12436 initializing an array or record object via the following aggregate:
12438 @example
12439 Array_Or_Record : XXX := (others => <>);
12440 @end example
12442 unless the relevant type fully initializes all components.
12443 @end table
12445 @geindex -gnatwV (gcc)
12448 @table @asis
12450 @item @code{-gnatwV}
12452 @emph{Suppress warnings on unassigned variables.}
12454 This switch suppresses warnings for access to variables which
12455 may not be properly initialized.
12456 @end table
12458 @geindex -gnatw.v (gcc)
12460 @geindex bit order warnings
12463 @table @asis
12465 @item @code{-gnatw.v}
12467 @emph{Activate info messages for non-default bit order.}
12469 This switch activates messages (labeled “info”, they are not warnings,
12470 just informational messages) about the effects of non-default bit-order
12471 on records to which a component clause is applied. The effect of specifying
12472 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
12473 these messages, which are given by default, are useful in understanding the
12474 exact consequences of using this feature.
12475 @end table
12477 @geindex -gnatw.V (gcc)
12480 @table @asis
12482 @item @code{-gnatw.V}
12484 @emph{Suppress info messages for non-default bit order.}
12486 This switch suppresses information messages for the effects of specifying
12487 non-default bit order on record components with component clauses.
12488 @end table
12490 @geindex -gnatww (gcc)
12492 @geindex String indexing warnings
12495 @table @asis
12497 @item @code{-gnatww}
12499 @emph{Activate warnings on wrong low bound assumption.}
12501 This switch activates warnings for indexing an unconstrained string parameter
12502 with a literal or S’Length. This is a case where the code is assuming that the
12503 low bound is one, which is in general not true (for example when a slice is
12504 passed). The default is that such warnings are generated.
12505 @end table
12507 @geindex -gnatwW (gcc)
12510 @table @asis
12512 @item @code{-gnatwW}
12514 @emph{Suppress warnings on wrong low bound assumption.}
12516 This switch suppresses warnings for indexing an unconstrained string parameter
12517 with a literal or S’Length. Note that this warning can also be suppressed
12518 in a particular case by adding an assertion that the lower bound is 1,
12519 as shown in the following example:
12521 @example
12522 procedure K (S : String) is
12523    pragma Assert (S'First = 1);
12524    ...
12525 @end example
12526 @end table
12528 @geindex -gnatw.w (gcc)
12530 @geindex Warnings Off control
12533 @table @asis
12535 @item @code{-gnatw.w}
12537 @emph{Activate warnings on Warnings Off pragmas.}
12539 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
12540 where either the pragma is entirely useless (because it suppresses no
12541 warnings), or it could be replaced by @code{pragma Unreferenced} or
12542 @code{pragma Unmodified}.
12543 Also activates warnings for the case of
12544 Warnings (Off, String), where either there is no matching
12545 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12546 The default is that these warnings are not given.
12547 @end table
12549 @geindex -gnatw.W (gcc)
12552 @table @asis
12554 @item @code{-gnatw.W}
12556 @emph{Suppress warnings on unnecessary Warnings Off pragmas.}
12558 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
12559 @end table
12561 @geindex -gnatwx (gcc)
12563 @geindex Export/Import pragma warnings
12566 @table @asis
12568 @item @code{-gnatwx}
12570 @emph{Activate warnings on Export/Import pragmas.}
12572 This switch activates warnings on Export/Import pragmas when
12573 the compiler detects a possible conflict between the Ada and
12574 foreign language calling sequences. For example, the use of
12575 default parameters in a convention C procedure is dubious
12576 because the C compiler cannot supply the proper default, so
12577 a warning is issued. The default is that such warnings are
12578 generated.
12579 @end table
12581 @geindex -gnatwX (gcc)
12584 @table @asis
12586 @item @code{-gnatwX}
12588 @emph{Suppress warnings on Export/Import pragmas.}
12590 This switch suppresses warnings on Export/Import pragmas.
12591 The sense of this is that you are telling the compiler that
12592 you know what you are doing in writing the pragma, and it
12593 should not complain at you.
12594 @end table
12596 @geindex -gnatw.x (gcc)
12599 @table @asis
12601 @item @code{-gnatw.x}
12603 @emph{Activate warnings for No_Exception_Propagation mode.}
12605 This switch activates warnings for exception usage when pragma Restrictions
12606 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
12607 explicit exception raises which are not covered by a local handler, and for
12608 exception handlers which do not cover a local raise. The default is that
12609 these warnings are given for units that contain exception handlers.
12611 @item @code{-gnatw.X}
12613 @emph{Disable warnings for No_Exception_Propagation mode.}
12615 This switch disables warnings for exception usage when pragma Restrictions
12616 (No_Exception_Propagation) is in effect.
12617 @end table
12619 @geindex -gnatwy (gcc)
12621 @geindex Ada compatibility issues warnings
12624 @table @asis
12626 @item @code{-gnatwy}
12628 @emph{Activate warnings for Ada compatibility issues.}
12630 For the most part, newer versions of Ada are upwards compatible
12631 with older versions. For example, Ada 2005 programs will almost
12632 always work when compiled as Ada 2012.
12633 However there are some exceptions (for example the fact that
12634 @code{some} is now a reserved word in Ada 2012). This
12635 switch activates several warnings to help in identifying
12636 and correcting such incompatibilities. The default is that
12637 these warnings are generated. Note that at one point Ada 2005
12638 was called Ada 0Y, hence the choice of character.
12639 @end table
12641 @geindex -gnatwY (gcc)
12643 @geindex Ada compatibility issues warnings
12646 @table @asis
12648 @item @code{-gnatwY}
12650 @emph{Disable warnings for Ada compatibility issues.}
12652 This switch suppresses the warnings intended to help in identifying
12653 incompatibilities between Ada language versions.
12654 @end table
12656 @geindex -gnatw.y (gcc)
12658 @geindex Package spec needing body
12661 @table @asis
12663 @item @code{-gnatw.y}
12665 @emph{Activate information messages for why package spec needs body.}
12667 There are a number of cases in which a package spec needs a body.
12668 For example, the use of pragma Elaborate_Body, or the declaration
12669 of a procedure specification requiring a completion. This switch
12670 causes information messages to be output showing why a package
12671 specification requires a body. This can be useful in the case of
12672 a large package specification which is unexpectedly requiring a
12673 body. The default is that such information messages are not output.
12674 @end table
12676 @geindex -gnatw.Y (gcc)
12678 @geindex No information messages for why package spec needs body
12681 @table @asis
12683 @item @code{-gnatw.Y}
12685 @emph{Disable information messages for why package spec needs body.}
12687 This switch suppresses the output of information messages showing why
12688 a package specification needs a body.
12689 @end table
12691 @geindex -gnatwz (gcc)
12693 @geindex Unchecked_Conversion warnings
12696 @table @asis
12698 @item @code{-gnatwz}
12700 @emph{Activate warnings on unchecked conversions.}
12702 This switch activates warnings for unchecked conversions
12703 where the types are known at compile time to have different
12704 sizes. The default is that such warnings are generated. Warnings are also
12705 generated for subprogram pointers with different conventions.
12706 @end table
12708 @geindex -gnatwZ (gcc)
12711 @table @asis
12713 @item @code{-gnatwZ}
12715 @emph{Suppress warnings on unchecked conversions.}
12717 This switch suppresses warnings for unchecked conversions
12718 where the types are known at compile time to have different
12719 sizes or conventions.
12720 @end table
12722 @geindex -gnatw.z (gcc)
12724 @geindex Size/Alignment warnings
12727 @table @asis
12729 @item @code{-gnatw.z}
12731 @emph{Activate warnings for size not a multiple of alignment.}
12733 This switch activates 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 default
12737 is that such warnings are generated.
12738 @end table
12740 @geindex -gnatw.Z (gcc)
12742 @geindex Size/Alignment warnings
12745 @table @asis
12747 @item @code{-gnatw.Z}
12749 @emph{Suppress warnings for size not a multiple of alignment.}
12751 This switch suppresses warnings for cases of array and record types
12752 with specified @code{Size} and @code{Alignment} attributes where the
12753 size is not a multiple of the alignment, resulting in an object
12754 size that is greater than the specified size. The warning can also
12755 be suppressed by giving an explicit @code{Object_Size} value.
12756 @end table
12758 @geindex -Wunused (gcc)
12761 @table @asis
12763 @item @code{-Wunused}
12765 The warnings controlled by the @code{-gnatw} switch are generated by
12766 the front end of the compiler. The GCC back end can provide
12767 additional warnings and they are controlled by the @code{-W} switch.
12768 For example, @code{-Wunused} activates back end
12769 warnings for entities that are declared but not referenced.
12770 @end table
12772 @geindex -Wuninitialized (gcc)
12775 @table @asis
12777 @item @code{-Wuninitialized}
12779 Similarly, @code{-Wuninitialized} activates
12780 the back end warning for uninitialized variables. This switch must be
12781 used in conjunction with an optimization level greater than zero.
12782 @end table
12784 @geindex -Wstack-usage (gcc)
12787 @table @asis
12789 @item @code{-Wstack-usage=@emph{len}}
12791 Warn if the stack usage of a subprogram might be larger than @code{len} bytes.
12792 See @ref{e8,,Static Stack Usage Analysis} for details.
12793 @end table
12795 @geindex -Wall (gcc)
12798 @table @asis
12800 @item @code{-Wall}
12802 This switch enables most warnings from the GCC back end.
12803 The code generator detects a number of warning situations that are missed
12804 by the GNAT front end, and this switch can be used to activate them.
12805 The use of this switch also sets the default front-end warning mode to
12806 @code{-gnatwa}, that is, most front-end warnings are activated as well.
12807 @end table
12809 @geindex -w (gcc)
12812 @table @asis
12814 @item @code{-w}
12816 Conversely, this switch suppresses warnings from the GCC back end.
12817 The use of this switch also sets the default front-end warning mode to
12818 @code{-gnatws}, that is, front-end warnings are suppressed as well.
12819 @end table
12821 @geindex -Werror (gcc)
12824 @table @asis
12826 @item @code{-Werror}
12828 This switch causes warnings from the GCC back end to be treated as
12829 errors.  The warning string still appears, but the warning messages are
12830 counted as errors, and prevent the generation of an object file.
12831 The use of this switch also sets the default front-end warning mode to
12832 @code{-gnatwe}, that is, front-end warning messages and style check
12833 messages are treated as errors as well.
12834 @end table
12836 A string of warning parameters can be used in the same parameter. For example:
12838 @example
12839 -gnatwaGe
12840 @end example
12842 will turn on all optional warnings except for unrecognized pragma warnings,
12843 and also specify that warnings should be treated as errors.
12845 When no switch @code{-gnatw} is used, this is equivalent to:
12847 @quotation
12850 @itemize *
12852 @item 
12853 @code{-gnatw.a}
12855 @item 
12856 @code{-gnatwB}
12858 @item 
12859 @code{-gnatw.b}
12861 @item 
12862 @code{-gnatwC}
12864 @item 
12865 @code{-gnatw.C}
12867 @item 
12868 @code{-gnatwD}
12870 @item 
12871 @code{-gnatw.D}
12873 @item 
12874 @code{-gnatwF}
12876 @item 
12877 @code{-gnatw.F}
12879 @item 
12880 @code{-gnatwg}
12882 @item 
12883 @code{-gnatwH}
12885 @item 
12886 @code{-gnatw.H}
12888 @item 
12889 @code{-gnatwi}
12891 @item 
12892 @code{-gnatwJ}
12894 @item 
12895 @code{-gnatw.J}
12897 @item 
12898 @code{-gnatwK}
12900 @item 
12901 @code{-gnatw.K}
12903 @item 
12904 @code{-gnatwL}
12906 @item 
12907 @code{-gnatw.L}
12909 @item 
12910 @code{-gnatwM}
12912 @item 
12913 @code{-gnatw.m}
12915 @item 
12916 @code{-gnatwn}
12918 @item 
12919 @code{-gnatw.N}
12921 @item 
12922 @code{-gnatwo}
12924 @item 
12925 @code{-gnatw.O}
12927 @item 
12928 @code{-gnatwP}
12930 @item 
12931 @code{-gnatw.P}
12933 @item 
12934 @code{-gnatwq}
12936 @item 
12937 @code{-gnatw.Q}
12939 @item 
12940 @code{-gnatwR}
12942 @item 
12943 @code{-gnatw.R}
12945 @item 
12946 @code{-gnatw.S}
12948 @item 
12949 @code{-gnatwT}
12951 @item 
12952 @code{-gnatw.t}
12954 @item 
12955 @code{-gnatwU}
12957 @item 
12958 @code{-gnatw.U}
12960 @item 
12961 @code{-gnatwv}
12963 @item 
12964 @code{-gnatw.v}
12966 @item 
12967 @code{-gnatww}
12969 @item 
12970 @code{-gnatw.W}
12972 @item 
12973 @code{-gnatwx}
12975 @item 
12976 @code{-gnatw.X}
12978 @item 
12979 @code{-gnatwy}
12981 @item 
12982 @code{-gnatw.Y}
12984 @item 
12985 @code{-gnatwz}
12987 @item 
12988 @code{-gnatw.z}
12989 @end itemize
12990 @end quotation
12992 @node Debugging and Assertion Control,Validity Checking,Warning Message Control,Compiler Switches
12993 @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}
12994 @subsection Debugging and Assertion Control
12997 @geindex -gnata (gcc)
13000 @table @asis
13002 @item @code{-gnata}
13004 @geindex Assert
13006 @geindex Debug
13008 @geindex Assertions
13010 @geindex Precondition
13012 @geindex Postcondition
13014 @geindex Type invariants
13016 @geindex Subtype predicates
13018 The @code{-gnata} option is equivalent to the following @code{Assertion_Policy} pragma:
13020 @example
13021 pragma Assertion_Policy (Check);
13022 @end example
13024 Which is a shorthand for:
13026 @example
13027 pragma Assertion_Policy
13028 --  Ada RM assertion pragmas
13029   (Assert                    => Check,
13030    Static_Predicate          => Check,
13031    Dynamic_Predicate         => Check,
13032    Pre                       => Check,
13033    Pre'Class                 => Check,
13034    Post                      => Check,
13035    Post'Class                => Check,
13036    Type_Invariant            => Check,
13037    Type_Invariant'Class      => Check,
13038    Default_Initial_Condition => Check,
13039 --  GNAT specific assertion pragmas
13040    Assert_And_Cut            => Check,
13041    Assume                    => Check,
13042    Contract_Cases            => Check,
13043    Debug                     => Check,
13044    Ghost                     => Check,
13045    Initial_Condition         => Check,
13046    Loop_Invariant            => Check,
13047    Loop_Variant              => Check,
13048    Postcondition             => Check,
13049    Precondition              => Check,
13050    Predicate                 => Check,
13051    Refined_Post              => Check,
13052    Subprogram_Variant        => Check);
13053 @end example
13055 The pragmas @code{Assert} and @code{Debug} normally have no effect and
13056 are ignored. This switch, where @code{a} stands for ‘assert’, causes
13057 pragmas @code{Assert} and @code{Debug} to be activated. This switch also
13058 causes preconditions, postconditions, subtype predicates, and
13059 type invariants to be activated.
13061 The pragmas have the form:
13063 @example
13064 pragma Assert (<Boolean-expression> [, <static-string-expression>])
13065 pragma Debug (<procedure call>)
13066 pragma Type_Invariant (<type-local-name>, <Boolean-expression>)
13067 pragma Predicate (<type-local-name>, <Boolean-expression>)
13068 pragma Precondition (<Boolean-expression>, <string-expression>)
13069 pragma Postcondition (<Boolean-expression>, <string-expression>)
13070 @end example
13072 The aspects have the form:
13074 @example
13075 with [Pre|Post|Type_Invariant|Dynamic_Predicate|Static_Predicate]
13076   => <Boolean-expression>;
13077 @end example
13079 The @code{Assert} pragma causes @code{Boolean-expression} to be tested.
13080 If the result is @code{True}, the pragma has no effect (other than
13081 possible side effects from evaluating the expression). If the result is
13082 @code{False}, the exception @code{Assert_Failure} declared in the package
13083 @code{System.Assertions} is raised (passing @code{static-string-expression}, if
13084 present, as the message associated with the exception). If no string
13085 expression is given, the default is a string containing the file name and
13086 line number of the pragma.
13088 The @code{Debug} pragma causes @code{procedure} to be called. Note that
13089 @code{pragma Debug} may appear within a declaration sequence, allowing
13090 debugging procedures to be called between declarations.
13092 For the aspect specification, the @code{Boolean-expression} is evaluated.
13093 If the result is @code{True}, the aspect has no effect. If the result
13094 is @code{False}, the exception @code{Assert_Failure} is raised.
13095 @end table
13097 @node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
13098 @anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{f5}@anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{e9}
13099 @subsection Validity Checking
13102 @geindex Validity Checking
13104 The Ada Reference Manual defines the concept of invalid values (see
13105 RM 13.9.1). The primary source of invalid values is uninitialized
13106 variables. A scalar variable that is left uninitialized may contain
13107 an invalid value; the concept of invalid does not apply to access or
13108 composite types.
13110 It is an error to read an invalid value, but the RM does not require
13111 run-time checks to detect such errors, except for some minimal
13112 checking to prevent erroneous execution (i.e. unpredictable
13113 behavior). This corresponds to the @code{-gnatVd} switch below,
13114 which is the default. For example, by default, if the expression of a
13115 case statement is invalid, it will raise Constraint_Error rather than
13116 causing a wild jump, and if an array index on the left-hand side of an
13117 assignment is invalid, it will raise Constraint_Error rather than
13118 overwriting an arbitrary memory location.
13120 The @code{-gnatVa} may be used to enable additional validity checks,
13121 which are not required by the RM. These checks are often very
13122 expensive (which is why the RM does not require them). These checks
13123 are useful in tracking down uninitialized variables, but they are
13124 not usually recommended for production builds, and in particular
13125 we do not recommend using these extra validity checking options in
13126 combination with optimization, since this can confuse the optimizer.
13127 If performance is a consideration, leading to the need to optimize,
13128 then the validity checking options should not be used.
13130 The other @code{-gnatV@emph{x}} switches below allow finer-grained
13131 control; you can enable whichever validity checks you desire. However,
13132 for most debugging purposes, @code{-gnatVa} is sufficient, and the
13133 default @code{-gnatVd} (i.e. standard Ada behavior) is usually
13134 sufficient for non-debugging use.
13136 The @code{-gnatB} switch tells the compiler to assume that all
13137 values are valid (that is, within their declared subtype range)
13138 except in the context of a use of the Valid attribute. This means
13139 the compiler can generate more efficient code, since the range
13140 of values is better known at compile time. However, an uninitialized
13141 variable can cause wild jumps and memory corruption in this mode.
13143 The @code{-gnatV@emph{x}} switch allows control over the validity
13144 checking mode as described below.
13145 The @code{x} argument is a string of letters that
13146 indicate validity checks that are performed or not performed in addition
13147 to the default checks required by Ada as described above.
13149 @geindex -gnatVa (gcc)
13152 @table @asis
13154 @item @code{-gnatVa}
13156 @emph{All validity checks.}
13158 All validity checks are turned on.
13159 That is, @code{-gnatVa} is
13160 equivalent to @code{gnatVcdefimoprst}.
13161 @end table
13163 @geindex -gnatVc (gcc)
13166 @table @asis
13168 @item @code{-gnatVc}
13170 @emph{Validity checks for copies.}
13172 The right-hand side of assignments, and the (explicit) initializing values
13173 of object declarations are validity checked.
13174 @end table
13176 @geindex -gnatVd (gcc)
13179 @table @asis
13181 @item @code{-gnatVd}
13183 @emph{Default (RM) validity checks.}
13185 Some validity checks are required by Ada (see RM 13.9.1 (9-11)); these
13186 (and only these) validity checks are enabled by default.
13187 For case statements (and case expressions) that lack a “when others =>”
13188 choice, a check is made that the value of the selector expression
13189 belongs to its nominal subtype. If it does not, Constraint_Error is raised.
13190 For assignments to array components (and for indexed components in some
13191 other contexts), a check is made that each index expression belongs to the
13192 corresponding index subtype. If it does not, Constraint_Error is raised.
13193 Both these validity checks may be turned off using switch @code{-gnatVD}.
13194 They are turned on by default. If @code{-gnatVD} is specified, a subsequent
13195 switch @code{-gnatVd} will leave the checks turned on.
13196 Switch @code{-gnatVD} should be used only if you are sure that all such
13197 expressions have valid values. If you use this switch and invalid values
13198 are present, then the program is erroneous, and wild jumps or memory
13199 overwriting may occur.
13200 @end table
13202 @geindex -gnatVe (gcc)
13205 @table @asis
13207 @item @code{-gnatVe}
13209 @emph{Validity checks for scalar components.}
13211 In the absence of this switch, assignments to scalar components of
13212 enclosing record or array objects are not validity checked, even if
13213 validity checks for assignments generally (@code{-gnatVc}) are turned on.
13214 Specifying this switch enables such checks.
13215 This switch has no effect if the @code{-gnatVc} switch is not specified.
13216 @end table
13218 @geindex -gnatVf (gcc)
13221 @table @asis
13223 @item @code{-gnatVf}
13225 @emph{Validity checks for floating-point values.}
13227 Specifying this switch enables validity checking for floating-point
13228 values in the same contexts where validity checking is enabled for
13229 other scalar values.
13230 In the absence of this switch, validity checking is not performed for
13231 floating-point values. This takes precedence over other statements about
13232 performing validity checking for scalar objects in various scenarios.
13233 One way to look at it is that if this switch is not set, then whenever
13234 any of the other rules in this section use the word “scalar” they
13235 really mean “scalar and not floating-point”.
13236 If @code{-gnatVf} is specified, then validity checking also applies
13237 for floating-point values, and NaNs and infinities are considered invalid,
13238 as well as out-of-range values for constrained types. The exact contexts
13239 in which floating-point values are checked depends on the setting of other
13240 options. For example, @code{-gnatVif} or @code{-gnatVfi}
13241 (the order does not matter) specifies that floating-point parameters of mode
13242 @code{in} should be validity checked.
13243 @end table
13245 @geindex -gnatVi (gcc)
13248 @table @asis
13250 @item @code{-gnatVi}
13252 @emph{Validity checks for `@w{`}in`@w{`} mode parameters.}
13254 Arguments for parameters of mode @code{in} are validity checked in function
13255 and procedure calls at the point of call.
13256 @end table
13258 @geindex -gnatVm (gcc)
13261 @table @asis
13263 @item @code{-gnatVm}
13265 @emph{Validity checks for `@w{`}in out`@w{`} mode parameters.}
13267 Arguments for parameters of mode @code{in out} are validity checked in
13268 procedure calls at the point of call. The @code{'m'} here stands for
13269 modify, since this concerns parameters that can be modified by the call.
13270 Note that there is no specific option to test @code{out} parameters,
13271 but any reference within the subprogram will be tested in the usual
13272 manner, and if an invalid value is copied back, any reference to it
13273 will be subject to validity checking.
13274 @end table
13276 @geindex -gnatVn (gcc)
13279 @table @asis
13281 @item @code{-gnatVn}
13283 @emph{No validity checks.}
13285 This switch turns off all validity checking, including the default checking
13286 for case statements and left hand side subscripts. Note that the use of
13287 the switch @code{-gnatp} suppresses all run-time checks, including
13288 validity checks, and thus implies @code{-gnatVn}. When this switch
13289 is used, it cancels any other @code{-gnatV} previously issued.
13290 @end table
13292 @geindex -gnatVo (gcc)
13295 @table @asis
13297 @item @code{-gnatVo}
13299 @emph{Validity checks for operator and attribute operands.}
13301 Scalar arguments for predefined operators and for attributes are
13302 validity checked.
13303 This includes all operators in package @code{Standard},
13304 the shift operators defined as intrinsic in package @code{Interfaces}
13305 and operands for attributes such as @code{Pos}. Checks are also made
13306 on individual component values for composite comparisons, and on the
13307 expressions in type conversions and qualified expressions. Checks are
13308 also made on explicit ranges using @code{..} (e.g., slices, loops etc).
13309 @end table
13311 @geindex -gnatVp (gcc)
13314 @table @asis
13316 @item @code{-gnatVp}
13318 @emph{Validity checks for parameters.}
13320 This controls the treatment of formal parameters within a subprogram (as
13321 opposed to @code{-gnatVi} and @code{-gnatVm}, which control validity
13322 testing of actual parameters of a call). If either of these call options is
13323 specified, then normally an assumption is made within a subprogram that
13324 the validity of any incoming formal parameters of the corresponding mode(s)
13325 has already been checked at the point of call and does not need rechecking.
13326 If @code{-gnatVp} is set, then this assumption is not made and so their
13327 validity may be checked (or rechecked) within the subprogram. If neither of
13328 the two call-related options is specified, then this switch has no effect.
13329 @end table
13331 @geindex -gnatVr (gcc)
13334 @table @asis
13336 @item @code{-gnatVr}
13338 @emph{Validity checks for function returns.}
13340 The expression in simple @code{return} statements in functions is validity
13341 checked.
13342 @end table
13344 @geindex -gnatVs (gcc)
13347 @table @asis
13349 @item @code{-gnatVs}
13351 @emph{Validity checks for subscripts.}
13353 All subscript expressions are checked for validity, whatever context
13354 they occur in (in default mode some subscripts are not validity checked;
13355 for example, validity checking may be omitted in some cases involving
13356 a read of a component of an array).
13357 @end table
13359 @geindex -gnatVt (gcc)
13362 @table @asis
13364 @item @code{-gnatVt}
13366 @emph{Validity checks for tests.}
13368 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
13369 statements are checked, as well as guard expressions in entry calls.
13370 @end table
13372 The @code{-gnatV} switch may be followed by a string of letters
13373 to turn on a series of validity checking options.
13374 For example, @code{-gnatVcr}
13375 specifies that in addition to the default validity checking, copies and
13376 function return expressions are to be validity checked.
13377 In order to make it easier to specify the desired combination of effects,
13378 the upper case letters @code{CDFIMORST} may
13379 be used to turn off the corresponding lower case option.
13380 Thus @code{-gnatVaM} turns on all validity checking options except for
13381 checking of @code{in out} parameters.
13383 The specification of additional validity checking generates extra code (and
13384 in the case of @code{-gnatVa} the code expansion can be substantial).
13385 However, these additional checks can be very useful in detecting
13386 uninitialized variables, incorrect use of unchecked conversion, and other
13387 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
13388 is useful in conjunction with the extra validity checking, since this
13389 ensures that wherever possible uninitialized variables have invalid values.
13391 See also the pragma @code{Validity_Checks} which allows modification of
13392 the validity checking mode at the program source level, and also allows for
13393 temporary disabling of validity checks.
13395 @node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
13396 @anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{ee}
13397 @subsection Style Checking
13400 @geindex Style checking
13402 @geindex -gnaty (gcc)
13404 The @code{-gnaty} switch causes the compiler to
13405 enforce specified style rules. A limited set of style rules has been used
13406 in writing the GNAT sources themselves. This switch allows user programs
13407 to activate all or some of these checks. If the source program fails a
13408 specified style check, an appropriate message is given, preceded by
13409 the character sequence ‘(style)’. This message does not prevent
13410 successful compilation (unless the @code{-gnatwe} switch is used).
13412 Note that this is by no means intended to be a general facility for
13413 checking arbitrary coding standards. It is simply an embedding of the
13414 style rules we have chosen for the GNAT sources. If you are starting
13415 a project which does not have established style standards, you may
13416 find it useful to adopt the entire set of GNAT coding standards, or
13417 some subset of them.
13420 The string @code{x} is a sequence of letters or digits
13421 indicating the particular style
13422 checks to be performed. The following checks are defined:
13424 @geindex -gnaty[0-9] (gcc)
13427 @table @asis
13429 @item @code{-gnaty0}
13431 @emph{Specify indentation level.}
13433 If a digit from 1-9 appears
13434 in the string after @code{-gnaty}
13435 then proper indentation is checked, with the digit indicating the
13436 indentation level required. A value of zero turns off this style check.
13437 The rule checks that the following constructs start on a column that is
13438 a multiple of the alignment level:
13441 @itemize *
13443 @item 
13444 beginnings of declarations (except record component declarations)
13445 and statements;
13447 @item 
13448 beginnings of the structural components of compound statements;
13450 @item 
13451 @code{end} keyword that completes the declaration of a program unit declaration
13452 or body or that completes a compound statement.
13453 @end itemize
13455 Full line comments must be
13456 aligned with the @code{--} starting on a column that is a multiple of
13457 the alignment level, or they may be aligned the same way as the following
13458 non-blank line (this is useful when full line comments appear in the middle
13459 of a statement, or they may be aligned with the source line on the previous
13460 non-blank line.
13461 @end table
13463 @geindex -gnatya (gcc)
13466 @table @asis
13468 @item @code{-gnatya}
13470 @emph{Check attribute casing.}
13472 Attribute names, including the case of keywords such as @code{digits}
13473 used as attributes names, must be written in mixed case, that is, the
13474 initial letter and any letter following an underscore must be uppercase.
13475 All other letters must be lowercase.
13476 @end table
13478 @geindex -gnatyA (gcc)
13481 @table @asis
13483 @item @code{-gnatyA}
13485 @emph{Use of array index numbers in array attributes.}
13487 When using the array attributes First, Last, Range,
13488 or Length, the index number must be omitted for one-dimensional arrays
13489 and is required for multi-dimensional arrays.
13490 @end table
13492 @geindex -gnatyb (gcc)
13495 @table @asis
13497 @item @code{-gnatyb}
13499 @emph{Blanks not allowed at statement end.}
13501 Trailing blanks are not allowed at the end of statements. The purpose of this
13502 rule, together with h (no horizontal tabs), is to enforce a canonical format
13503 for the use of blanks to separate source tokens.
13504 @end table
13506 @geindex -gnatyB (gcc)
13509 @table @asis
13511 @item @code{-gnatyB}
13513 @emph{Check Boolean operators.}
13515 The use of AND/OR operators is not permitted except in the cases of modular
13516 operands, array operands, and simple stand-alone boolean variables or
13517 boolean constants. In all other cases @code{and then}/@cite{or else} are
13518 required.
13519 @end table
13521 @geindex -gnatyc (gcc)
13524 @table @asis
13526 @item @code{-gnatyc}
13528 @emph{Check comments, double space.}
13530 Comments must meet the following set of rules:
13533 @itemize *
13535 @item 
13536 The @code{--} that starts the column must either start in column one,
13537 or else at least one blank must precede this sequence.
13539 @item 
13540 Comments that follow other tokens on a line must have at least one blank
13541 following the @code{--} at the start of the comment.
13543 @item 
13544 Full line comments must have at least two blanks following the
13545 @code{--} that starts the comment, with the following exceptions.
13547 @item 
13548 A line consisting only of the @code{--} characters, possibly preceded
13549 by blanks is permitted.
13551 @item 
13552 A comment starting with @code{--x} where @code{x} is a special character
13553 is permitted.
13554 This allows proper processing of the output from specialized tools
13555 such as @code{gnatprep} (where @code{--!} is used) and in earlier versions of the SPARK
13556 annotation
13557 language (where @code{--#} is used). For the purposes of this rule, a
13558 special character is defined as being in one of the ASCII ranges
13559 @code{16#21#...16#2F#} or @code{16#3A#...16#3F#}.
13560 Note that this usage is not permitted
13561 in GNAT implementation units (i.e., when @code{-gnatg} is used).
13563 @item 
13564 A line consisting entirely of minus signs, possibly preceded by blanks, is
13565 permitted. This allows the construction of box comments where lines of minus
13566 signs are used to form the top and bottom of the box.
13568 @item 
13569 A comment that starts and ends with @code{--} is permitted as long as at
13570 least one blank follows the initial @code{--}. Together with the preceding
13571 rule, this allows the construction of box comments, as shown in the following
13572 example:
13574 @example
13575 ---------------------------
13576 -- This is a box comment --
13577 -- with two text lines.  --
13578 ---------------------------
13579 @end example
13580 @end itemize
13581 @end table
13583 @geindex -gnatyC (gcc)
13586 @table @asis
13588 @item @code{-gnatyC}
13590 @emph{Check comments, single space.}
13592 This is identical to @code{c} except that only one space
13593 is required following the @code{--} of a comment instead of two.
13594 @end table
13596 @geindex -gnatyd (gcc)
13599 @table @asis
13601 @item @code{-gnatyd}
13603 @emph{Check no DOS line terminators present.}
13605 All lines must be terminated by a single ASCII.LF
13606 character (in particular the DOS line terminator sequence CR/LF is not
13607 allowed).
13608 @end table
13610 @geindex -gnatyD (gcc)
13613 @table @asis
13615 @item @code{-gnatyD}
13617 @emph{Check declared identifiers in mixed case.}
13619 Declared identifiers must be in mixed case, as in
13620 This_Is_An_Identifier. Use -gnatyr in addition to ensure
13621 that references match declarations.
13622 @end table
13624 @geindex -gnatye (gcc)
13627 @table @asis
13629 @item @code{-gnatye}
13631 @emph{Check end/exit labels.}
13633 Optional labels on @code{end} statements ending subprograms and on
13634 @code{exit} statements exiting named loops, are required to be present.
13635 @end table
13637 @geindex -gnatyf (gcc)
13640 @table @asis
13642 @item @code{-gnatyf}
13644 @emph{No form feeds or vertical tabs.}
13646 Neither form feeds nor vertical tab characters are permitted
13647 in the source text.
13648 @end table
13650 @geindex -gnatyg (gcc)
13653 @table @asis
13655 @item @code{-gnatyg}
13657 @emph{GNAT style mode.}
13659 The set of style check switches is set to match that used by the GNAT sources.
13660 This may be useful when developing code that is eventually intended to be
13661 incorporated into GNAT. Currently this is equivalent to
13662 @code{-gnatyydISuxz}) but additional style switches may be added to this
13663 set in the future without advance notice.
13664 @end table
13666 @geindex -gnatyh (gcc)
13669 @table @asis
13671 @item @code{-gnatyh}
13673 @emph{No horizontal tabs.}
13675 Horizontal tab characters are not permitted in the source text.
13676 Together with the b (no blanks at end of line) check, this
13677 enforces a canonical form for the use of blanks to separate
13678 source tokens.
13679 @end table
13681 @geindex -gnatyi (gcc)
13684 @table @asis
13686 @item @code{-gnatyi}
13688 @emph{Check if-then layout.}
13690 The keyword @code{then} must appear either on the same
13691 line as corresponding @code{if}, or on a line on its own, lined
13692 up under the @code{if}.
13693 @end table
13695 @geindex -gnatyI (gcc)
13698 @table @asis
13700 @item @code{-gnatyI}
13702 @emph{check mode IN keywords.}
13704 Mode @code{in} (the default mode) is not
13705 allowed to be given explicitly. @code{in out} is fine,
13706 but not @code{in} on its own.
13707 @end table
13709 @geindex -gnatyk (gcc)
13712 @table @asis
13714 @item @code{-gnatyk}
13716 @emph{Check keyword casing.}
13718 All keywords must be in lower case (with the exception of keywords
13719 such as @code{digits} used as attribute names to which this check
13720 does not apply). A single error is reported for each line breaking
13721 this rule even if multiple casing issues exist on a same line.
13722 @end table
13724 @geindex -gnatyl (gcc)
13727 @table @asis
13729 @item @code{-gnatyl}
13731 @emph{Check layout.}
13733 Layout of statement and declaration constructs must follow the
13734 recommendations in the Ada Reference Manual, as indicated by the
13735 form of the syntax rules. For example an @code{else} keyword must
13736 be lined up with the corresponding @code{if} keyword.
13738 There are two respects in which the style rule enforced by this check
13739 option are more liberal than those in the Ada Reference Manual. First
13740 in the case of record declarations, it is permissible to put the
13741 @code{record} keyword on the same line as the @code{type} keyword, and
13742 then the @code{end} in @code{end record} must line up under @code{type}.
13743 This is also permitted when the type declaration is split on two lines.
13744 For example, any of the following three layouts is acceptable:
13746 @example
13747 type q is record
13748    a : integer;
13749    b : integer;
13750 end record;
13752 type q is
13753    record
13754       a : integer;
13755       b : integer;
13756    end record;
13758 type q is
13759    record
13760       a : integer;
13761       b : integer;
13762 end record;
13763 @end example
13765 Second, in the case of a block statement, a permitted alternative
13766 is to put the block label on the same line as the @code{declare} or
13767 @code{begin} keyword, and then line the @code{end} keyword up under
13768 the block label. For example both the following are permitted:
13770 @example
13771 Block : declare
13772    A : Integer := 3;
13773 begin
13774    Proc (A, A);
13775 end Block;
13777 Block :
13778    declare
13779       A : Integer := 3;
13780    begin
13781       Proc (A, A);
13782    end Block;
13783 @end example
13785 The same alternative format is allowed for loops. For example, both of
13786 the following are permitted:
13788 @example
13789 Clear : while J < 10 loop
13790    A (J) := 0;
13791 end loop Clear;
13793 Clear :
13794    while J < 10 loop
13795       A (J) := 0;
13796    end loop Clear;
13797 @end example
13798 @end table
13800 @geindex -gnatyLnnn (gcc)
13803 @table @asis
13805 @item @code{-gnatyL}
13807 @emph{Set maximum nesting level.}
13809 The maximum level of nesting of constructs (including subprograms, loops,
13810 blocks, packages, and conditionals) may not exceed the given value
13811 @emph{nnn}. A value of zero disconnects this style check.
13812 @end table
13814 @geindex -gnatym (gcc)
13817 @table @asis
13819 @item @code{-gnatym}
13821 @emph{Check maximum line length.}
13823 The length of source lines must not exceed 79 characters, including
13824 any trailing blanks. The value of 79 allows convenient display on an
13825 80 character wide device or window, allowing for possible special
13826 treatment of 80 character lines. Note that this count is of
13827 characters in the source text. This means that a tab character counts
13828 as one character in this count and a wide character sequence counts as
13829 a single character (however many bytes are needed in the encoding).
13830 @end table
13832 @geindex -gnatyMnnn (gcc)
13835 @table @asis
13837 @item @code{-gnatyM}
13839 @emph{Set maximum line length.}
13841 The length of lines must not exceed the
13842 given value @emph{nnn}. The maximum value that can be specified is 32767.
13843 If neither style option for setting the line length is used, then the
13844 default is 255. This also controls the maximum length of lexical elements,
13845 where the only restriction is that they must fit on a single line.
13846 @end table
13848 @geindex -gnatyn (gcc)
13851 @table @asis
13853 @item @code{-gnatyn}
13855 @emph{Check casing of entities in Standard.}
13857 Any identifier from Standard must be cased
13858 to match the presentation in the Ada Reference Manual (for example,
13859 @code{Integer} and @code{ASCII.NUL}).
13860 @end table
13862 @geindex -gnatyN (gcc)
13865 @table @asis
13867 @item @code{-gnatyN}
13869 @emph{Turn off all style checks.}
13871 All style check options are turned off.
13872 @end table
13874 @geindex -gnatyo (gcc)
13877 @table @asis
13879 @item @code{-gnatyo}
13881 @emph{Check order of subprogram bodies.}
13883 All subprogram bodies in a given scope
13884 (e.g., a package body) must be in alphabetical order. The ordering
13885 rule uses normal Ada rules for comparing strings, ignoring casing
13886 of letters, except that if there is a trailing numeric suffix, then
13887 the value of this suffix is used in the ordering (e.g., Junk2 comes
13888 before Junk10).
13889 @end table
13891 @geindex -gnatyO (gcc)
13894 @table @asis
13896 @item @code{-gnatyO}
13898 @emph{Check that overriding subprograms are explicitly marked as such.}
13900 This applies to all subprograms of a derived type that override a primitive
13901 operation of the type, for both tagged and untagged types. In particular,
13902 the declaration of a primitive operation of a type extension that overrides
13903 an inherited operation must carry an overriding indicator. Another case is
13904 the declaration of a function that overrides a predefined operator (such
13905 as an equality operator).
13906 @end table
13908 @geindex -gnatyp (gcc)
13911 @table @asis
13913 @item @code{-gnatyp}
13915 @emph{Check pragma casing.}
13917 Pragma names must be written in mixed case, that is, the
13918 initial letter and any letter following an underscore must be uppercase.
13919 All other letters must be lowercase. An exception is that SPARK_Mode is
13920 allowed as an alternative for Spark_Mode.
13921 @end table
13923 @geindex -gnatyr (gcc)
13926 @table @asis
13928 @item @code{-gnatyr}
13930 @emph{Check references.}
13932 All identifier references must be cased in the same way as the
13933 corresponding declaration. No specific casing style is imposed on
13934 identifiers. The only requirement is for consistency of references
13935 with declarations.
13936 @end table
13938 @geindex -gnatys (gcc)
13941 @table @asis
13943 @item @code{-gnatys}
13945 @emph{Check separate specs.}
13947 Separate declarations (‘specs’) are required for subprograms (a
13948 body is not allowed to serve as its own declaration). The only
13949 exception is that parameterless library level procedures are
13950 not required to have a separate declaration. This exception covers
13951 the most frequent form of main program procedures.
13952 @end table
13954 @geindex -gnatyS (gcc)
13957 @table @asis
13959 @item @code{-gnatyS}
13961 @emph{Check no statements after then/else.}
13963 No statements are allowed
13964 on the same line as a @code{then} or @code{else} keyword following the
13965 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
13966 affected, and a special exception allows a pragma to appear after @code{else}.
13967 @end table
13969 @geindex -gnatyt (gcc)
13972 @table @asis
13974 @item @code{-gnatyt}
13976 @emph{Check token spacing.}
13978 The following token spacing rules are enforced:
13981 @itemize *
13983 @item 
13984 The keywords @code{abs} and @code{not} must be followed by a space.
13986 @item 
13987 The token @code{=>} must be surrounded by spaces.
13989 @item 
13990 The token @code{<>} must be preceded by a space or a left parenthesis.
13992 @item 
13993 Binary operators other than @code{**} must be surrounded by spaces.
13994 There is no restriction on the layout of the @code{**} binary operator.
13996 @item 
13997 Colon must be surrounded by spaces.
13999 @item 
14000 Colon-equal (assignment, initialization) must be surrounded by spaces.
14002 @item 
14003 Comma must be the first non-blank character on the line, or be
14004 immediately preceded by a non-blank character, and must be followed
14005 by a space.
14007 @item 
14008 If the token preceding a left parenthesis ends with a letter or digit, then
14009 a space must separate the two tokens.
14011 @item 
14012 If the token following a right parenthesis starts with a letter or digit, then
14013 a space must separate the two tokens.
14015 @item 
14016 A right parenthesis must either be the first non-blank character on
14017 a line, or it must be preceded by a non-blank character.
14019 @item 
14020 A semicolon must not be preceded by a space, and must not be followed by
14021 a non-blank character.
14023 @item 
14024 A unary plus or minus may not be followed by a space.
14026 @item 
14027 A vertical bar must be surrounded by spaces.
14028 @end itemize
14030 Exactly one blank (and no other white space) must appear between
14031 a @code{not} token and a following @code{in} token.
14032 @end table
14034 @geindex -gnatyu (gcc)
14037 @table @asis
14039 @item @code{-gnatyu}
14041 @emph{Check unnecessary blank lines.}
14043 Unnecessary blank lines are not allowed. A blank line is considered
14044 unnecessary if it appears at the end of the file, or if more than
14045 one blank line occurs in sequence.
14046 @end table
14048 @geindex -gnatyx (gcc)
14051 @table @asis
14053 @item @code{-gnatyx}
14055 @emph{Check extra parentheses.}
14057 Unnecessary extra levels of parentheses (C-style) are not allowed
14058 around conditions (or selection expressions) in @code{if}, @code{while},
14059 @code{case}, and @code{exit} statements, as well as part of ranges.
14060 @end table
14062 @geindex -gnatyy (gcc)
14065 @table @asis
14067 @item @code{-gnatyy}
14069 @emph{Set all standard style check options.}
14071 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
14072 options enabled with the exception of @code{-gnatyB}, @code{-gnatyd},
14073 @code{-gnatyI}, @code{-gnatyLnnn}, @code{-gnatyo}, @code{-gnatyO},
14074 @code{-gnatyS}, @code{-gnatyu}, and @code{-gnatyx}.
14075 @end table
14077 @geindex -gnatyz (gcc)
14080 @table @asis
14082 @item @code{-gnatyz}
14084 @emph{Check extra parentheses (operator precedence).}
14086 Extra levels of parentheses that are not required by operator precedence
14087 rules are flagged. See also @code{-gnatyx}.
14088 @end table
14090 @geindex -gnaty- (gcc)
14093 @table @asis
14095 @item @code{-gnaty-}
14097 @emph{Remove style check options.}
14099 This causes any subsequent options in the string to act as canceling the
14100 corresponding style check option. To cancel maximum nesting level control,
14101 use the @code{L} parameter without any integer value after that, because any
14102 digit following @emph{-} in the parameter string of the @code{-gnaty}
14103 option will be treated as canceling the indentation check. The same is true
14104 for the @code{M} parameter. @code{y} and @code{N} parameters are not
14105 allowed after @emph{-}.
14106 @end table
14108 @geindex -gnaty+ (gcc)
14111 @table @asis
14113 @item @code{-gnaty+}
14115 @emph{Enable style check options.}
14117 This causes any subsequent options in the string to enable the corresponding
14118 style check option. That is, it cancels the effect of a previous -,
14119 if any.
14120 @end table
14122 @c end of switch description (leave this comment to ease automatic parsing for
14124 @c GNAT Studio)
14126 In the above rules, appearing in column one is always permitted, that is,
14127 counts as meeting either a requirement for a required preceding space,
14128 or as meeting a requirement for no preceding space.
14130 Appearing at the end of a line is also always permitted, that is, counts
14131 as meeting either a requirement for a following space, or as meeting
14132 a requirement for no following space.
14134 If any of these style rules is violated, a message is generated giving
14135 details on the violation. The initial characters of such messages are
14136 always ‘@cite{(style)}’. Note that these messages are treated as warning
14137 messages, so they normally do not prevent the generation of an object
14138 file. The @code{-gnatwe} switch can be used to treat warning messages,
14139 including style messages, as fatal errors.
14141 The switch @code{-gnaty} on its own (that is not
14142 followed by any letters or digits) is equivalent
14143 to the use of @code{-gnatyy} as described above, that is all
14144 built-in standard style check options are enabled.
14146 The switch @code{-gnatyN} clears any previously set style checks.
14148 @node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
14149 @anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{f7}@anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{ec}
14150 @subsection Run-Time Checks
14153 @geindex Division by zero
14155 @geindex Access before elaboration
14157 @geindex Checks
14158 @geindex division by zero
14160 @geindex Checks
14161 @geindex access before elaboration
14163 @geindex Checks
14164 @geindex stack overflow checking
14166 By default, the following checks are suppressed: stack overflow
14167 checks, and checks for access before elaboration on subprogram
14168 calls. All other checks, including overflow checks, range checks and
14169 array bounds checks, are turned on by default. The following @code{gcc}
14170 switches refine this default behavior.
14172 @geindex -gnatp (gcc)
14175 @table @asis
14177 @item @code{-gnatp}
14179 @geindex Suppressing checks
14181 @geindex Checks
14182 @geindex suppressing
14184 This switch causes the unit to be compiled
14185 as though @code{pragma Suppress (All_checks)}
14186 had been present in the source. Validity checks are also eliminated (in
14187 other words @code{-gnatp} also implies @code{-gnatVn}.
14188 Use this switch to improve the performance
14189 of the code at the expense of safety in the presence of invalid data or
14190 program bugs.
14192 Note that when checks are suppressed, the compiler is allowed, but not
14193 required, to omit the checking code. If the run-time cost of the
14194 checking code is zero or near-zero, the compiler will generate it even
14195 if checks are suppressed. In particular, if the compiler can prove
14196 that a certain check will necessarily fail, it will generate code to
14197 do an unconditional ‘raise’, even if checks are suppressed. The
14198 compiler warns in this case. Another case in which checks may not be
14199 eliminated is when they are embedded in certain run-time routines such
14200 as math library routines.
14202 Of course, run-time checks are omitted whenever the compiler can prove
14203 that they will not fail, whether or not checks are suppressed.
14205 Note that if you suppress a check that would have failed, program
14206 execution is erroneous, which means the behavior is totally
14207 unpredictable. The program might crash, or print wrong answers, or
14208 do anything else. It might even do exactly what you wanted it to do
14209 (and then it might start failing mysteriously next week or next
14210 year). The compiler will generate code based on the assumption that
14211 the condition being checked is true, which can result in erroneous
14212 execution if that assumption is wrong.
14214 The checks subject to suppression include all the checks defined by the Ada
14215 standard, the additional implementation defined checks @code{Alignment_Check},
14216 @code{Duplicated_Tag_Check}, @code{Predicate_Check}, @code{Container_Checks}, @code{Tampering_Check},
14217 and @code{Validity_Check}, as well as any checks introduced using @code{pragma Check_Name}.
14218 Note that @code{Atomic_Synchronization} is not automatically suppressed by use of this option.
14220 If the code depends on certain checks being active, you can use
14221 pragma @code{Unsuppress} either as a configuration pragma or as
14222 a local pragma to make sure that a specified check is performed
14223 even if @code{gnatp} is specified.
14225 The @code{-gnatp} switch has no effect if a subsequent
14226 @code{-gnat-p} switch appears.
14227 @end table
14229 @geindex -gnat-p (gcc)
14231 @geindex Suppressing checks
14233 @geindex Checks
14234 @geindex suppressing
14236 @geindex Suppress
14239 @table @asis
14241 @item @code{-gnat-p}
14243 This switch cancels the effect of a previous @code{gnatp} switch.
14244 @end table
14246 @geindex -gnato?? (gcc)
14248 @geindex Overflow checks
14250 @geindex Overflow mode
14252 @geindex Check
14253 @geindex overflow
14256 @table @asis
14258 @item @code{-gnato??}
14260 This switch controls the mode used for computing intermediate
14261 arithmetic integer operations, and also enables overflow checking.
14262 For a full description of overflow mode and checking control, see
14263 the ‘Overflow Check Handling in GNAT’ appendix in this
14264 User’s Guide.
14266 Overflow checks are always enabled by this switch. The argument
14267 controls the mode, using the codes
14270 @table @asis
14272 @item @emph{1 = STRICT}
14274 In STRICT mode, intermediate operations are always done using the
14275 base type, and overflow checking ensures that the result is within
14276 the base type range.
14278 @item @emph{2 = MINIMIZED}
14280 In MINIMIZED mode, overflows in intermediate operations are avoided
14281 where possible by using a larger integer type for the computation
14282 (typically @code{Long_Long_Integer}). Overflow checking ensures that
14283 the result fits in this larger integer type.
14285 @item @emph{3 = ELIMINATED}
14287 In ELIMINATED mode, overflows in intermediate operations are avoided
14288 by using multi-precision arithmetic. In this case, overflow checking
14289 has no effect on intermediate operations (since overflow is impossible).
14290 @end table
14292 If two digits are present after @code{-gnato} then the first digit
14293 sets the mode for expressions outside assertions, and the second digit
14294 sets the mode for expressions within assertions. Here assertions is used
14295 in the technical sense (which includes for example precondition and
14296 postcondition expressions).
14298 If one digit is present, the corresponding mode is applicable to both
14299 expressions within and outside assertion expressions.
14301 If no digits are present, the default is to enable overflow checks
14302 and set STRICT mode for both kinds of expressions. This is compatible
14303 with the use of @code{-gnato} in previous versions of GNAT.
14305 @geindex Machine_Overflows
14307 Note that the @code{-gnato??} switch does not affect the code generated
14308 for any floating-point operations; it applies only to integer semantics.
14309 For floating-point, GNAT has the @code{Machine_Overflows}
14310 attribute set to @code{False} and the normal mode of operation is to
14311 generate IEEE NaN and infinite values on overflow or invalid operations
14312 (such as dividing 0.0 by 0.0).
14314 The reason that we distinguish overflow checking from other kinds of
14315 range constraint checking is that a failure of an overflow check, unlike
14316 for example the failure of a range check, can result in an incorrect
14317 value, but cannot cause random memory destruction (like an out of range
14318 subscript), or a wild jump (from an out of range case value). Overflow
14319 checking is also quite expensive in time and space, since in general it
14320 requires the use of double length arithmetic.
14322 Note again that the default is @code{-gnato11} (equivalent to @code{-gnato1}),
14323 so overflow checking is performed in STRICT mode by default.
14324 @end table
14326 @geindex -gnatE (gcc)
14328 @geindex Elaboration checks
14330 @geindex Check
14331 @geindex elaboration
14334 @table @asis
14336 @item @code{-gnatE}
14338 Enables dynamic checks for access-before-elaboration
14339 on subprogram calls and generic instantiations.
14340 Note that @code{-gnatE} is not necessary for safety, because in the
14341 default mode, GNAT ensures statically that the checks would not fail.
14342 For full details of the effect and use of this switch,
14343 @ref{c9,,Compiling with gcc}.
14344 @end table
14346 @geindex -fstack-check (gcc)
14348 @geindex Stack Overflow Checking
14350 @geindex Checks
14351 @geindex stack overflow checking
14354 @table @asis
14356 @item @code{-fstack-check}
14358 Activates stack overflow checking. For full details of the effect and use of
14359 this switch see @ref{e7,,Stack Overflow Checking}.
14360 @end table
14362 @geindex Unsuppress
14364 The setting of these switches only controls the default setting of the
14365 checks. You may modify them using either @code{Suppress} (to remove
14366 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
14367 the program source.
14369 @node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
14370 @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}
14371 @subsection Using @code{gcc} for Syntax Checking
14374 @geindex -gnats (gcc)
14377 @table @asis
14379 @item @code{-gnats}
14381 The @code{s} stands for ‘syntax’.
14383 Run GNAT in syntax checking only mode. For
14384 example, the command
14386 @example
14387 $ gcc -c -gnats x.adb
14388 @end example
14390 compiles file @code{x.adb} in syntax-check-only mode. You can check a
14391 series of files in a single command
14392 , and can use wildcards to specify such a group of files.
14393 Note that you must specify the @code{-c} (compile
14394 only) flag in addition to the @code{-gnats} flag.
14396 You may use other switches in conjunction with @code{-gnats}. In
14397 particular, @code{-gnatl} and @code{-gnatv} are useful to control the
14398 format of any generated error messages.
14400 When the source file is empty or contains only empty lines and/or comments,
14401 the output is a warning:
14403 @example
14404 $ gcc -c -gnats -x ada toto.txt
14405 toto.txt:1:01: warning: empty file, contains no compilation units
14407 @end example
14409 Otherwise, the output is simply the error messages, if any. No object file or
14410 ALI file is generated by a syntax-only compilation. Also, no units other
14411 than the one specified are accessed. For example, if a unit @code{X}
14412 @emph{with}s a unit @code{Y}, compiling unit @code{X} in syntax
14413 check only mode does not access the source file containing unit
14414 @code{Y}.
14416 @geindex Multiple units
14417 @geindex syntax checking
14419 Normally, GNAT allows only a single unit in a source file. However, this
14420 restriction does not apply in syntax-check-only mode, and it is possible
14421 to check a file containing multiple compilation units concatenated
14422 together. This is primarily used by the @code{gnatchop} utility
14423 (@ref{1d,,Renaming Files with gnatchop}).
14424 @end table
14426 @node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
14427 @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}
14428 @subsection Using @code{gcc} for Semantic Checking
14431 @geindex -gnatc (gcc)
14434 @table @asis
14436 @item @code{-gnatc}
14438 The @code{c} stands for ‘check’.
14439 Causes the compiler to operate in semantic check mode,
14440 with full checking for all illegalities specified in the
14441 Ada Reference Manual, but without generation of any object code
14442 (no object file is generated).
14444 Because dependent files must be accessed, you must follow the GNAT
14445 semantic restrictions on file structuring to operate in this mode:
14448 @itemize *
14450 @item 
14451 The needed source files must be accessible
14452 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
14454 @item 
14455 Each file must contain only one compilation unit.
14457 @item 
14458 The file name and unit name must match (@ref{3b,,File Naming Rules}).
14459 @end itemize
14461 The output consists of error messages as appropriate. No object file is
14462 generated. An @code{ALI} file is generated for use in the context of
14463 cross-reference tools, but this file is marked as not being suitable
14464 for binding (since no object file is generated).
14465 The checking corresponds exactly to the notion of
14466 legality in the Ada Reference Manual.
14468 Any unit can be compiled in semantics-checking-only mode, including
14469 units that would not normally be compiled (subunits,
14470 and specifications where a separate body is present).
14471 @end table
14473 @node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
14474 @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}
14475 @subsection Compiling Different Versions of Ada
14478 The switches described in this section allow you to explicitly specify
14479 the version of the Ada language that your programs are written in.
14480 The default mode is Ada 2012,
14481 but you can also specify Ada 95, Ada 2005 mode, or
14482 indicate Ada 83 compatibility mode.
14484 @geindex Compatibility with Ada 83
14486 @geindex -gnat83 (gcc)
14488 @geindex ACVC
14489 @geindex Ada 83 tests
14491 @geindex Ada 83 mode
14494 @table @asis
14496 @item @code{-gnat83} (Ada 83 Compatibility Mode)
14498 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
14499 specifies that the program is to be compiled in Ada 83 mode. With
14500 @code{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
14501 semantics where this can be done easily.
14502 It is not possible to guarantee this switch does a perfect
14503 job; some subtle tests, such as are
14504 found in earlier ACVC tests (and that have been removed from the ACATS suite
14505 for Ada 95), might not compile correctly.
14506 Nevertheless, this switch may be useful in some circumstances, for example
14507 where, due to contractual reasons, existing code needs to be maintained
14508 using only Ada 83 features.
14510 With few exceptions (most notably the need to use @code{<>} on
14511 unconstrained 
14512 @geindex Generic formal parameters
14513 generic formal parameters,
14514 the use of the new Ada 95 / Ada 2005
14515 reserved words, and the use of packages
14516 with optional bodies), it is not necessary to specify the
14517 @code{-gnat83} switch when compiling Ada 83 programs, because, with rare
14518 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
14519 a correct Ada 83 program is usually also a correct program
14520 in these later versions of the language standard. For further information
14521 please refer to the @emph{Compatibility and Porting Guide} chapter in the
14522 @cite{GNAT Reference Manual}.
14523 @end table
14525 @geindex -gnat95 (gcc)
14527 @geindex Ada 95 mode
14530 @table @asis
14532 @item @code{-gnat95} (Ada 95 mode)
14534 This switch directs the compiler to implement the Ada 95 version of the
14535 language.
14536 Since Ada 95 is almost completely upwards
14537 compatible with Ada 83, Ada 83 programs may generally be compiled using
14538 this switch (see the description of the @code{-gnat83} switch for further
14539 information about Ada 83 mode).
14540 If an Ada 2005 program is compiled in Ada 95 mode,
14541 uses of the new Ada 2005 features will cause error
14542 messages or warnings.
14544 This switch also can be used to cancel the effect of a previous
14545 @code{-gnat83}, @code{-gnat05/2005}, or @code{-gnat12/2012}
14546 switch earlier in the command line.
14547 @end table
14549 @geindex -gnat05 (gcc)
14551 @geindex -gnat2005 (gcc)
14553 @geindex Ada 2005 mode
14556 @table @asis
14558 @item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
14560 This switch directs the compiler to implement the Ada 2005 version of the
14561 language, as documented in the official Ada standards document.
14562 Since Ada 2005 is almost completely upwards
14563 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
14564 may generally be compiled using this switch (see the description of the
14565 @code{-gnat83} and @code{-gnat95} switches for further
14566 information).
14567 @end table
14569 @geindex -gnat12 (gcc)
14571 @geindex -gnat2012 (gcc)
14573 @geindex Ada 2012 mode
14576 @table @asis
14578 @item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
14580 This switch directs the compiler to implement the Ada 2012 version of the
14581 language (also the default).
14582 Since Ada 2012 is almost completely upwards
14583 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
14584 Ada 83 and Ada 95 programs
14585 may generally be compiled using this switch (see the description of the
14586 @code{-gnat83}, @code{-gnat95}, and @code{-gnat05/2005} switches
14587 for further information).
14588 @end table
14590 @geindex -gnat2022 (gcc)
14592 @geindex Ada 2022 mode
14595 @table @asis
14597 @item @code{-gnat2022} (Ada 2022 mode)
14599 This switch directs the compiler to implement the Ada 2022 version of the
14600 language.
14601 @end table
14603 @geindex -gnatX0 (gcc)
14605 @geindex Ada language extensions
14607 @geindex GNAT extensions
14610 @table @asis
14612 @item @code{-gnatX0} (Enable GNAT Extensions)
14614 This switch directs the compiler to implement the latest version of the
14615 language (currently Ada 2022) and also to enable certain GNAT implementation
14616 extensions that are not part of any Ada standard. For a full list of these
14617 extensions, see the GNAT reference manual, @code{Pragma Extensions_Allowed}.
14618 @end table
14620 @geindex -gnatX (gcc)
14622 @geindex Ada language extensions
14624 @geindex GNAT extensions
14627 @table @asis
14629 @item @code{-gnatX} (Enable core GNAT Extensions)
14631 This switch is similar to -gnatX0 except that only some, not all, of the
14632 GNAT-defined language extensions are enabled. For a list of the
14633 extensions enabled by this switch, see the GNAT reference manual
14634 @code{Pragma Extensions_Allowed} and the description of that pragma’s
14635 “On” (as opposed to “All”) argument.
14636 @end table
14638 @node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14639 @anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{31}@anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{fd}
14640 @subsection Character Set Control
14643 @geindex -gnati (gcc)
14646 @table @asis
14648 @item @code{-gnati@emph{c}}
14650 Normally GNAT recognizes the Latin-1 character set in source program
14651 identifiers, as described in the Ada Reference Manual.
14652 This switch causes
14653 GNAT to recognize alternate character sets in identifiers. @code{c} is a
14654 single character  indicating the character set, as follows:
14657 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14658 @item
14660 @emph{1}
14662 @tab
14664 ISO 8859-1 (Latin-1) identifiers
14666 @item
14668 @emph{2}
14670 @tab
14672 ISO 8859-2 (Latin-2) letters allowed in identifiers
14674 @item
14676 @emph{3}
14678 @tab
14680 ISO 8859-3 (Latin-3) letters allowed in identifiers
14682 @item
14684 @emph{4}
14686 @tab
14688 ISO 8859-4 (Latin-4) letters allowed in identifiers
14690 @item
14692 @emph{5}
14694 @tab
14696 ISO 8859-5 (Cyrillic) letters allowed in identifiers
14698 @item
14700 @emph{9}
14702 @tab
14704 ISO 8859-15 (Latin-9) letters allowed in identifiers
14706 @item
14708 @emph{p}
14710 @tab
14712 IBM PC letters (code page 437) allowed in identifiers
14714 @item
14716 @emph{8}
14718 @tab
14720 IBM PC letters (code page 850) allowed in identifiers
14722 @item
14724 @emph{f}
14726 @tab
14728 Full upper-half codes allowed in identifiers
14730 @item
14732 @emph{n}
14734 @tab
14736 No upper-half codes allowed in identifiers
14738 @item
14740 @emph{w}
14742 @tab
14744 Wide-character codes (that is, codes greater than 255)
14745 allowed in identifiers
14747 @end multitable
14750 See @ref{23,,Foreign Language Representation} for full details on the
14751 implementation of these character sets.
14752 @end table
14754 @geindex -gnatW (gcc)
14757 @table @asis
14759 @item @code{-gnatW@emph{e}}
14761 Specify the method of encoding for wide characters.
14762 @code{e} is one of the following:
14765 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14766 @item
14768 @emph{h}
14770 @tab
14772 Hex encoding (brackets coding also recognized)
14774 @item
14776 @emph{u}
14778 @tab
14780 Upper half encoding (brackets encoding also recognized)
14782 @item
14784 @emph{s}
14786 @tab
14788 Shift/JIS encoding (brackets encoding also recognized)
14790 @item
14792 @emph{e}
14794 @tab
14796 EUC encoding (brackets encoding also recognized)
14798 @item
14800 @emph{8}
14802 @tab
14804 UTF-8 encoding (brackets encoding also recognized)
14806 @item
14808 @emph{b}
14810 @tab
14812 Brackets encoding only (default value)
14814 @end multitable
14817 For full details on these encoding
14818 methods see @ref{37,,Wide_Character Encodings}.
14819 Note that brackets coding is always accepted, even if one of the other
14820 options is specified, so for example @code{-gnatW8} specifies that both
14821 brackets and UTF-8 encodings will be recognized. The units that are
14822 with’ed directly or indirectly will be scanned using the specified
14823 representation scheme, and so if one of the non-brackets scheme is
14824 used, it must be used consistently throughout the program. However,
14825 since brackets encoding is always recognized, it may be conveniently
14826 used in standard libraries, allowing these libraries to be used with
14827 any of the available coding schemes.
14829 Note that brackets encoding only applies to program text. Within comments,
14830 brackets are considered to be normal graphic characters, and bracket sequences
14831 are never recognized as wide characters.
14833 If no @code{-gnatW?} parameter is present, then the default
14834 representation is normally Brackets encoding only. However, if the
14835 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14836 byte order mark or BOM for UTF-8), then these three characters are
14837 skipped and the default representation for the file is set to UTF-8.
14839 Note that the wide character representation that is specified (explicitly
14840 or by default) for the main program also acts as the default encoding used
14841 for Wide_Text_IO files if not specifically overridden by a WCEM form
14842 parameter.
14843 @end table
14845 When no @code{-gnatW?} is specified, then characters (other than wide
14846 characters represented using brackets notation) are treated as 8-bit
14847 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14848 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14849 characters in the range 16#00#..16#1F# are not accepted in program text
14850 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14851 in program text, but allowed and ignored in comments. Note in particular
14852 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14853 as an end of line in this default mode. If your source program contains
14854 instances of the NEL character used as a line terminator,
14855 you must use UTF-8 encoding for the whole
14856 source program. In default mode, all lines must be ended by a standard
14857 end of line sequence (CR, CR/LF, or LF).
14859 Note that the convention of simply accepting all upper half characters in
14860 comments means that programs that use standard ASCII for program text, but
14861 UTF-8 encoding for comments are accepted in default mode, providing that the
14862 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14863 This is a common mode for many programs with foreign language comments.
14865 @node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14866 @anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{fe}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{ff}
14867 @subsection File Naming Control
14870 @geindex -gnatk (gcc)
14873 @table @asis
14875 @item @code{-gnatk@emph{n}}
14877 Activates file name ‘krunching’. @code{n}, a decimal integer in the range
14878 1-999, indicates the maximum allowable length of a file name (not
14879 including the @code{.ads} or @code{.adb} extension). The default is not
14880 to enable file name krunching.
14882 For the source file naming rules, @ref{3b,,File Naming Rules}.
14883 @end table
14885 @node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14886 @anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{100}@anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{101}
14887 @subsection Subprogram Inlining Control
14890 @geindex -gnatn (gcc)
14893 @table @asis
14895 @item @code{-gnatn[12]}
14897 The @code{n} here is intended to suggest the first syllable of the word ‘inline’.
14898 GNAT recognizes and processes @code{Inline} pragmas. However, for inlining to
14899 actually occur, optimization must be enabled and, by default, inlining of
14900 subprograms across units is not performed. If you want to additionally
14901 enable inlining of subprograms specified by pragma @code{Inline} across units,
14902 you must also specify this switch.
14904 In the absence of this switch, GNAT does not attempt inlining across units
14905 and does not access the bodies of subprograms for which @code{pragma Inline} is
14906 specified if they are not in the current unit.
14908 You can optionally specify the inlining level: 1 for moderate inlining across
14909 units, which is a good compromise between compilation times and performances
14910 at run time, or 2 for full inlining across units, which may bring about
14911 longer compilation times. If no inlining level is specified, the compiler will
14912 pick it based on the optimization level: 1 for @code{-O1}, @code{-O2} or
14913 @code{-Os} and 2 for @code{-O3}.
14915 If you specify this switch the compiler will access these bodies,
14916 creating an extra source dependency for the resulting object file, and
14917 where possible, the call will be inlined.
14918 For further details on when inlining is possible
14919 see @ref{102,,Inlining of Subprograms}.
14920 @end table
14922 @geindex -gnatN (gcc)
14925 @table @asis
14927 @item @code{-gnatN}
14929 This switch activates front-end inlining which also
14930 generates additional dependencies.
14932 When using a gcc-based back end, then the use of
14933 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
14934 Historically front end inlining was more extensive than the gcc back end
14935 inlining, but that is no longer the case.
14936 @end table
14938 @node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14939 @anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{103}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{104}
14940 @subsection Auxiliary Output Control
14943 @geindex -gnatu (gcc)
14946 @table @asis
14948 @item @code{-gnatu}
14950 Print a list of units required by this compilation on @code{stdout}.
14951 The listing includes all units on which the unit being compiled depends
14952 either directly or indirectly.
14953 @end table
14955 @geindex -pass-exit-codes (gcc)
14958 @table @asis
14960 @item @code{-pass-exit-codes}
14962 If this switch is not used, the exit code returned by @code{gcc} when
14963 compiling multiple files indicates whether all source files have
14964 been successfully used to generate object files or not.
14966 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
14967 exit status and allows an integrated development environment to better
14968 react to a compilation failure. Those exit status are:
14971 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14972 @item
14974 @emph{5}
14976 @tab
14978 There was an error in at least one source file.
14980 @item
14982 @emph{3}
14984 @tab
14986 At least one source file did not generate an object file.
14988 @item
14990 @emph{2}
14992 @tab
14994 The compiler died unexpectedly (internal error for example).
14996 @item
14998 @emph{0}
15000 @tab
15002 An object file has been generated for every source file.
15004 @end multitable
15006 @end table
15008 @node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
15009 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{105}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{106}
15010 @subsection Debugging Control
15013 @quotation
15015 @geindex Debugging options
15016 @end quotation
15018 @geindex -gnatd (gcc)
15021 @table @asis
15023 @item @code{-gnatd@emph{x}}
15025 Activate internal debugging switches. @code{x} is a letter or digit, or
15026 string of letters or digits, which specifies the type of debugging
15027 outputs desired. Normally these are used only for internal development
15028 or system debugging purposes. You can find full documentation for these
15029 switches in the body of the @code{Debug} unit in the compiler source
15030 file @code{debug.adb}.
15031 @end table
15033 @geindex -gnatG (gcc)
15036 @table @asis
15038 @item @code{-gnatG[=@emph{nn}]}
15040 This switch causes the compiler to generate auxiliary output containing
15041 a pseudo-source listing of the generated expanded code. Like most Ada
15042 compilers, GNAT works by first transforming the high level Ada code into
15043 lower level constructs. For example, tasking operations are transformed
15044 into calls to the tasking run-time routines. A unique capability of GNAT
15045 is to list this expanded code in a form very close to normal Ada source.
15046 This is very useful in understanding the implications of various Ada
15047 usage on the efficiency of the generated code. There are many cases in
15048 Ada (e.g., the use of controlled types), where simple Ada statements can
15049 generate a lot of run-time code. By using @code{-gnatG} you can identify
15050 these cases, and consider whether it may be desirable to modify the coding
15051 approach to improve efficiency.
15053 The optional parameter @code{nn} if present after -gnatG specifies an
15054 alternative maximum line length that overrides the normal default of 72.
15055 This value is in the range 40-999999, values less than 40 being silently
15056 reset to 40. The equal sign is optional.
15058 The format of the output is very similar to standard Ada source, and is
15059 easily understood by an Ada programmer. The following special syntactic
15060 additions correspond to low level features used in the generated code that
15061 do not have any exact analogies in pure Ada source form. The following
15062 is a partial list of these special constructions. See the spec
15063 of package @code{Sprint} in file @code{sprint.ads} for a full list.
15065 @geindex -gnatL (gcc)
15067 If the switch @code{-gnatL} is used in conjunction with
15068 @code{-gnatG}, then the original source lines are interspersed
15069 in the expanded source (as comment lines with the original line number).
15072 @table @asis
15074 @item @code{new @emph{xxx} [storage_pool = @emph{yyy}]}
15076 Shows the storage pool being used for an allocator.
15078 @item @code{at end @emph{procedure-name};}
15080 Shows the finalization (cleanup) procedure for a scope.
15082 @item @code{(if @emph{expr} then @emph{expr} else @emph{expr})}
15084 Conditional expression equivalent to the @code{x?y:z} construction in C.
15086 @item @code{@emph{target}^(@emph{source})}
15088 A conversion with floating-point truncation instead of rounding.
15090 @item @code{@emph{target}?(@emph{source})}
15092 A conversion that bypasses normal Ada semantic checking. In particular
15093 enumeration types and fixed-point types are treated simply as integers.
15095 @item @code{@emph{target}?^(@emph{source})}
15097 Combines the above two cases.
15098 @end table
15100 @code{@emph{x} #/ @emph{y}}
15102 @code{@emph{x} #mod @emph{y}}
15104 @code{@emph{x} # @emph{y}}
15107 @table @asis
15109 @item @code{@emph{x} #rem @emph{y}}
15111 A division or multiplication of fixed-point values which are treated as
15112 integers without any kind of scaling.
15114 @item @code{free @emph{expr} [storage_pool = @emph{xxx}]}
15116 Shows the storage pool associated with a @code{free} statement.
15118 @item @code{[subtype or type declaration]}
15120 Used to list an equivalent declaration for an internally generated
15121 type that is referenced elsewhere in the listing.
15123 @item @code{freeze @emph{type-name} [@emph{actions}]}
15125 Shows the point at which @code{type-name} is frozen, with possible
15126 associated actions to be performed at the freeze point.
15128 @item @code{reference @emph{itype}}
15130 Reference (and hence definition) to internal type @code{itype}.
15132 @item @code{@emph{function-name}! (@emph{arg}, @emph{arg}, @emph{arg})}
15134 Intrinsic function call.
15136 @item @code{@emph{label-name} : label}
15138 Declaration of label @code{labelname}.
15140 @item @code{#$ @emph{subprogram-name}}
15142 An implicit call to a run-time support routine
15143 (to meet the requirement of H.3.1(9) in a
15144 convenient manner).
15146 @item @code{@emph{expr} && @emph{expr} && @emph{expr} ... && @emph{expr}}
15148 A multiple concatenation (same effect as @code{expr} & @code{expr} &
15149 @code{expr}, but handled more efficiently).
15151 @item @code{[constraint_error]}
15153 Raise the @code{Constraint_Error} exception.
15155 @item @code{@emph{expression}'reference}
15157 A pointer to the result of evaluating @{expression@}.
15159 @item @code{@emph{target-type}!(@emph{source-expression})}
15161 An unchecked conversion of @code{source-expression} to @code{target-type}.
15163 @item @code{[@emph{numerator}/@emph{denominator}]}
15165 Used to represent internal real literals (that) have no exact
15166 representation in base 2-16 (for example, the result of compile time
15167 evaluation of the expression 1.0/27.0).
15168 @end table
15169 @end table
15171 @geindex -gnatD (gcc)
15174 @table @asis
15176 @item @code{-gnatD[=nn]}
15178 When used in conjunction with @code{-gnatG}, this switch causes
15179 the expanded source, as described above for
15180 @code{-gnatG} to be written to files with names
15181 @code{xxx.dg}, where @code{xxx} is the normal file name,
15182 instead of to the standard output file. For
15183 example, if the source file name is @code{hello.adb}, then a file
15184 @code{hello.adb.dg} will be written.  The debugging
15185 information generated by the @code{gcc} @code{-g} switch
15186 will refer to the generated @code{xxx.dg} file. This allows
15187 you to do source level debugging using the generated code which is
15188 sometimes useful for complex code, for example to find out exactly
15189 which part of a complex construction raised an exception. This switch
15190 also suppresses generation of cross-reference information (see
15191 @code{-gnatx}) since otherwise the cross-reference information
15192 would refer to the @code{.dg} file, which would cause
15193 confusion since this is not the original source file.
15195 Note that @code{-gnatD} actually implies @code{-gnatG}
15196 automatically, so it is not necessary to give both options.
15197 In other words @code{-gnatD} is equivalent to @code{-gnatDG}).
15199 @geindex -gnatL (gcc)
15201 If the switch @code{-gnatL} is used in conjunction with
15202 @code{-gnatDG}, then the original source lines are interspersed
15203 in the expanded source (as comment lines with the original line number).
15205 The optional parameter @code{nn} if present after -gnatD specifies an
15206 alternative maximum line length that overrides the normal default of 72.
15207 This value is in the range 40-999999, values less than 40 being silently
15208 reset to 40. The equal sign is optional.
15209 @end table
15211 @geindex -gnatr (gcc)
15213 @geindex pragma Restrictions
15216 @table @asis
15218 @item @code{-gnatr}
15220 This switch causes pragma Restrictions to be treated as Restriction_Warnings
15221 so that violation of restrictions causes warnings rather than illegalities.
15222 This is useful during the development process when new restrictions are added
15223 or investigated. The switch also causes pragma Profile to be treated as
15224 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
15225 restriction warnings rather than restrictions.
15226 @end table
15228 @geindex -gnatR (gcc)
15231 @table @asis
15233 @item @code{-gnatR[0|1|2|3|4][e][j][m][s]}
15235 This switch controls output from the compiler of a listing showing
15236 representation information for declared types, objects and subprograms.
15237 For @code{-gnatR0}, no information is output (equivalent to omitting
15238 the @code{-gnatR} switch). For @code{-gnatR1} (which is the default,
15239 so @code{-gnatR} with no parameter has the same effect), size and
15240 alignment information is listed for declared array and record types.
15242 For @code{-gnatR2}, size and alignment information is listed for all
15243 declared types and objects. The @code{Linker_Section} is also listed for any
15244 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
15245 latter case occurs for objects of a type for which a @code{Linker_Section}
15246 is set).
15248 For @code{-gnatR3}, symbolic expressions for values that are computed
15249 at run time for records are included. These symbolic expressions have
15250 a mostly obvious format with #n being used to represent the value of the
15251 n’th discriminant. See source files @code{repinfo.ads/adb} in the
15252 GNAT sources for full details on the format of @code{-gnatR3} output.
15254 For @code{-gnatR4}, information for relevant compiler-generated types
15255 is also listed, i.e. when they are structurally part of other declared
15256 types and objects.
15258 If the switch is followed by an @code{e} (e.g. @code{-gnatR2e}), then
15259 extended representation information for record sub-components of records
15260 is included.
15262 If the switch is followed by an @code{m} (e.g. @code{-gnatRm}), then
15263 subprogram conventions and parameter passing mechanisms for all the
15264 subprograms are included.
15266 If the switch is followed by a @code{j} (e.g., @code{-gnatRj}), then
15267 the output is in the JSON data interchange format specified by the
15268 ECMA-404 standard. The semantic description of this JSON output is
15269 available in the specification of the Repinfo unit present in the
15270 compiler sources.
15272 If the switch is followed by an @code{s} (e.g., @code{-gnatR3s}), then
15273 the output is to a file with the name @code{file.rep} where @code{file} is
15274 the name of the corresponding source file, except if @code{j} is also
15275 specified, in which case the file name is @code{file.json}.
15277 Note that it is possible for record components to have zero size. In
15278 this case, the component clause uses an obvious extension of permitted
15279 Ada syntax, for example @code{at 0 range 0 .. -1}.
15280 @end table
15282 @geindex -gnatS (gcc)
15285 @table @asis
15287 @item @code{-gnatS}
15289 The use of the switch @code{-gnatS} for an
15290 Ada compilation will cause the compiler to output a
15291 representation of package Standard in a form very
15292 close to standard Ada. It is not quite possible to
15293 do this entirely in standard Ada (since new
15294 numeric base types cannot be created in standard
15295 Ada), but the output is easily
15296 readable to any Ada programmer, and is useful to
15297 determine the characteristics of target dependent
15298 types in package Standard.
15299 @end table
15301 @geindex -gnatx (gcc)
15304 @table @asis
15306 @item @code{-gnatx}
15308 Normally the compiler generates full cross-referencing information in
15309 the @code{ALI} file. This information is used by a number of tools.
15310 The @code{-gnatx} switch suppresses this information. This saves some space
15311 and may slightly speed up compilation, but means that tools depending
15312 on this information cannot be used.
15313 @end table
15315 @geindex -fgnat-encodings (gcc)
15318 @table @asis
15320 @item @code{-fgnat-encodings=[all|gdb|minimal]}
15322 This switch controls the balance between GNAT encodings and standard DWARF
15323 emitted in the debug information.
15325 Historically, old debug formats like stabs were not powerful enough to
15326 express some Ada types (for instance, variant records or fixed-point types).
15327 To work around this, GNAT introduced proprietary encodings that embed the
15328 missing information (“GNAT encodings”).
15330 Recent versions of the DWARF debug information format are now able to
15331 correctly describe most of these Ada constructs (“standard DWARF”). As
15332 third-party tools started to use this format, GNAT has been enhanced to
15333 generate it. However, most tools (including GDB) are still relying on GNAT
15334 encodings.
15336 To support all tools, GNAT needs to be versatile about the balance between
15337 generation of GNAT encodings and standard DWARF. This is what
15338 @code{-fgnat-encodings} is about.
15341 @itemize *
15343 @item 
15344 @code{=all}: Emit all GNAT encodings, and then emit as much standard DWARF as
15345 possible so it does not conflict with GNAT encodings.
15347 @item 
15348 @code{=gdb}: Emit as much standard DWARF as possible as long as the current
15349 GDB handles it. Emit GNAT encodings for the rest.
15351 @item 
15352 @code{=minimal}: Emit as much standard DWARF as possible and emit GNAT
15353 encodings for the rest.
15354 @end itemize
15355 @end table
15357 @node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
15358 @anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{107}@anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{108}
15359 @subsection Exception Handling Control
15362 GNAT uses two methods for handling exceptions at run time. The
15363 @code{setjmp/longjmp} method saves the context when entering
15364 a frame with an exception handler. Then when an exception is
15365 raised, the context can be restored immediately, without the
15366 need for tracing stack frames. This method provides very fast
15367 exception propagation, but introduces significant overhead for
15368 the use of exception handlers, even if no exception is raised.
15370 The other approach is called ‘zero cost’ exception handling.
15371 With this method, the compiler builds static tables to describe
15372 the exception ranges. No dynamic code is required when entering
15373 a frame containing an exception handler. When an exception is
15374 raised, the tables are used to control a back trace of the
15375 subprogram invocation stack to locate the required exception
15376 handler. This method has considerably poorer performance for
15377 the propagation of exceptions, but there is no overhead for
15378 exception handlers if no exception is raised. Note that in this
15379 mode and in the context of mixed Ada and C/C++ programming,
15380 to propagate an exception through a C/C++ code, the C/C++ code
15381 must be compiled with the @code{-funwind-tables} GCC’s
15382 option.
15384 The following switches may be used to control which of the
15385 two exception handling methods is used.
15387 @geindex --RTS=sjlj (gnatmake)
15390 @table @asis
15392 @item @code{--RTS=sjlj}
15394 This switch causes the setjmp/longjmp run-time (when available) to be used
15395 for exception handling. If the default
15396 mechanism for the target is zero cost exceptions, then
15397 this switch can be used to modify this default, and must be
15398 used for all units in the partition.
15399 This option is rarely used. One case in which it may be
15400 advantageous is if you have an application where exception
15401 raising is common and the overall performance of the
15402 application is improved by favoring exception propagation.
15403 @end table
15405 @geindex --RTS=zcx (gnatmake)
15407 @geindex Zero Cost Exceptions
15410 @table @asis
15412 @item @code{--RTS=zcx}
15414 This switch causes the zero cost approach to be used
15415 for exception handling. If this is the default mechanism for the
15416 target (see below), then this switch is unneeded. If the default
15417 mechanism for the target is setjmp/longjmp exceptions, then
15418 this switch can be used to modify this default, and must be
15419 used for all units in the partition.
15420 This option can only be used if the zero cost approach
15421 is available for the target in use, otherwise it will generate an error.
15422 @end table
15424 The same option @code{--RTS} must be used both for @code{gcc}
15425 and @code{gnatbind}. Passing this option to @code{gnatmake}
15426 (@ref{d0,,Switches for gnatmake}) will ensure the required consistency
15427 through the compilation and binding steps.
15429 @node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
15430 @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}
15431 @subsection Units to Sources Mapping Files
15434 @geindex -gnatem (gcc)
15437 @table @asis
15439 @item @code{-gnatem=@emph{path}}
15441 A mapping file is a way to communicate to the compiler two mappings:
15442 from unit names to file names (without any directory information) and from
15443 file names to path names (with full directory information). These mappings
15444 are used by the compiler to short-circuit the path search.
15446 The use of mapping files is not required for correct operation of the
15447 compiler, but mapping files can improve efficiency, particularly when
15448 sources are read over a slow network connection. In normal operation,
15449 you need not be concerned with the format or use of mapping files,
15450 and the @code{-gnatem} switch is not a switch that you would use
15451 explicitly. It is intended primarily for use by automatic tools such as
15452 @code{gnatmake} running under the project file facility. The
15453 description here of the format of mapping files is provided
15454 for completeness and for possible use by other tools.
15456 A mapping file is a sequence of sets of three lines. In each set, the
15457 first line is the unit name, in lower case, with @code{%s} appended
15458 for specs and @code{%b} appended for bodies; the second line is the
15459 file name; and the third line is the path name.
15461 Example:
15463 @example
15464 main%b
15465 main.2.ada
15466 /gnat/project1/sources/main.2.ada
15467 @end example
15469 When the switch @code{-gnatem} is specified, the compiler will
15470 create in memory the two mappings from the specified file. If there is
15471 any problem (nonexistent file, truncated file or duplicate entries),
15472 no mapping will be created.
15474 Several @code{-gnatem} switches may be specified; however, only the
15475 last one on the command line will be taken into account.
15477 When using a project file, @code{gnatmake} creates a temporary
15478 mapping file and communicates it to the compiler using this switch.
15479 @end table
15481 @node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
15482 @anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{10a}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{10b}
15483 @subsection Code Generation Control
15486 The GCC technology provides a wide range of target dependent
15487 @code{-m} switches for controlling
15488 details of code generation with respect to different versions of
15489 architectures. This includes variations in instruction sets (e.g.,
15490 different members of the power pc family), and different requirements
15491 for optimal arrangement of instructions (e.g., different members of
15492 the x86 family). The list of available @code{-m} switches may be
15493 found in the GCC documentation.
15495 Use of these @code{-m} switches may in some cases result in improved
15496 code performance.
15498 The GNAT technology is tested and qualified without any
15499 @code{-m} switches,
15500 so generally the most reliable approach is to avoid the use of these
15501 switches. However, we generally expect most of these switches to work
15502 successfully with GNAT, and many customers have reported successful
15503 use of these options.
15505 Our general advice is to avoid the use of @code{-m} switches unless
15506 special needs lead to requirements in this area. In particular,
15507 there is no point in using @code{-m} switches to improve performance
15508 unless you actually see a performance improvement.
15510 @node Linker Switches,Binding with gnatbind,Compiler Switches,Building Executable Programs with GNAT
15511 @anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{10c}@anchor{gnat_ugn/building_executable_programs_with_gnat linker-switches}@anchor{10d}
15512 @section Linker Switches
15515 Linker switches can be specified after @code{-largs} builder switch.
15517 @geindex -fuse-ld=name
15520 @table @asis
15522 @item @code{-fuse-ld=@emph{name}}
15524 Linker to be used. The default is @code{bfd} for @code{ld.bfd}; @code{gold}
15525 (for @code{ld.gold}) and @code{mold} (for @code{ld.mold}) are more
15526 recent and faster alternatives, but only available on GNU/Linux
15527 platforms.
15528 @end table
15530 @node Binding with gnatbind,Linking with gnatlink,Linker Switches,Building Executable Programs with GNAT
15531 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{ca}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{10e}
15532 @section Binding with @code{gnatbind}
15535 @geindex gnatbind
15537 This chapter describes the GNAT binder, @code{gnatbind}, which is used
15538 to bind compiled GNAT objects.
15540 The @code{gnatbind} program performs four separate functions:
15543 @itemize *
15545 @item 
15546 Checks that a program is consistent, in accordance with the rules in
15547 Chapter 10 of the Ada Reference Manual. In particular, error
15548 messages are generated if a program uses inconsistent versions of a
15549 given unit.
15551 @item 
15552 Checks that an acceptable order of elaboration exists for the program
15553 and issues an error message if it cannot find an order of elaboration
15554 that satisfies the rules in Chapter 10 of the Ada Language Manual.
15556 @item 
15557 Generates a main program incorporating the given elaboration order.
15558 This program is a small Ada package (body and spec) that
15559 must be subsequently compiled
15560 using the GNAT compiler. The necessary compilation step is usually
15561 performed automatically by @code{gnatlink}. The two most important
15562 functions of this program
15563 are to call the elaboration routines of units in an appropriate order
15564 and to call the main program.
15566 @item 
15567 Determines the set of object files required by the given main program.
15568 This information is output in the forms of comments in the generated program,
15569 to be read by the @code{gnatlink} utility used to link the Ada application.
15570 @end itemize
15572 @menu
15573 * Running gnatbind:: 
15574 * Switches for gnatbind:: 
15575 * Command-Line Access:: 
15576 * Search Paths for gnatbind:: 
15577 * Examples of gnatbind Usage:: 
15579 @end menu
15581 @node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
15582 @anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{10f}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{110}
15583 @subsection Running @code{gnatbind}
15586 The form of the @code{gnatbind} command is
15588 @example
15589 $ gnatbind [ switches ] mainprog[.ali] [ switches ]
15590 @end example
15592 where @code{mainprog.adb} is the Ada file containing the main program
15593 unit body. @code{gnatbind} constructs an Ada
15594 package in two files whose names are
15595 @code{b~mainprog.ads}, and @code{b~mainprog.adb}.
15596 For example, if given the
15597 parameter @code{hello.ali}, for a main program contained in file
15598 @code{hello.adb}, the binder output files would be @code{b~hello.ads}
15599 and @code{b~hello.adb}.
15601 When doing consistency checking, the binder takes into consideration
15602 any source files it can locate. For example, if the binder determines
15603 that the given main program requires the package @code{Pack}, whose
15604 @code{.ALI}
15605 file is @code{pack.ali} and whose corresponding source spec file is
15606 @code{pack.ads}, it attempts to locate the source file @code{pack.ads}
15607 (using the same search path conventions as previously described for the
15608 @code{gcc} command). If it can locate this source file, it checks that
15609 the time stamps
15610 or source checksums of the source and its references to in @code{ALI} files
15611 match. In other words, any @code{ALI} files that mentions this spec must have
15612 resulted from compiling this version of the source file (or in the case
15613 where the source checksums match, a version close enough that the
15614 difference does not matter).
15616 @geindex Source files
15617 @geindex use by binder
15619 The effect of this consistency checking, which includes source files, is
15620 that the binder ensures that the program is consistent with the latest
15621 version of the source files that can be located at bind time. Editing a
15622 source file without compiling files that depend on the source file cause
15623 error messages to be generated by the binder.
15625 For example, suppose you have a main program @code{hello.adb} and a
15626 package @code{P}, from file @code{p.ads} and you perform the following
15627 steps:
15630 @itemize *
15632 @item 
15633 Enter @code{gcc -c hello.adb} to compile the main program.
15635 @item 
15636 Enter @code{gcc -c p.ads} to compile package @code{P}.
15638 @item 
15639 Edit file @code{p.ads}.
15641 @item 
15642 Enter @code{gnatbind hello}.
15643 @end itemize
15645 At this point, the file @code{p.ali} contains an out-of-date time stamp
15646 because the file @code{p.ads} has been edited. The attempt at binding
15647 fails, and the binder generates the following error messages:
15649 @example
15650 error: "hello.adb" must be recompiled ("p.ads" has been modified)
15651 error: "p.ads" has been modified and must be recompiled
15652 @end example
15654 Now both files must be recompiled as indicated, and then the bind can
15655 succeed, generating a main program. You need not normally be concerned
15656 with the contents of this file, but for reference purposes a sample
15657 binder output file is given in @ref{e,,Example of Binder Output File}.
15659 In most normal usage, the default mode of @code{gnatbind} which is to
15660 generate the main package in Ada, as described in the previous section.
15661 In particular, this means that any Ada programmer can read and understand
15662 the generated main program. It can also be debugged just like any other
15663 Ada code provided the @code{-g} switch is used for
15664 @code{gnatbind} and @code{gnatlink}.
15666 @node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
15667 @anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{111}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{112}
15668 @subsection Switches for @code{gnatbind}
15671 The following switches are available with @code{gnatbind}; details will
15672 be presented in subsequent sections.
15674 @geindex --version (gnatbind)
15677 @table @asis
15679 @item @code{--version}
15681 Display Copyright and version, then exit disregarding all other options.
15682 @end table
15684 @geindex --help (gnatbind)
15687 @table @asis
15689 @item @code{--help}
15691 If @code{--version} was not used, display usage, then exit disregarding
15692 all other options.
15693 @end table
15695 @geindex -a (gnatbind)
15698 @table @asis
15700 @item @code{-a}
15702 Indicates that, if supported by the platform, the adainit procedure should
15703 be treated as an initialisation routine by the linker (a constructor). This
15704 is intended to be used by the Project Manager to automatically initialize
15705 shared Stand-Alone Libraries.
15706 @end table
15708 @geindex -aO (gnatbind)
15711 @table @asis
15713 @item @code{-aO}
15715 Specify directory to be searched for ALI files.
15716 @end table
15718 @geindex -aI (gnatbind)
15721 @table @asis
15723 @item @code{-aI}
15725 Specify directory to be searched for source file.
15726 @end table
15728 @geindex -A (gnatbind)
15731 @table @asis
15733 @item @code{-A[=@emph{filename}]}
15735 Output ALI list (to standard output or to the named file).
15736 @end table
15738 @geindex -b (gnatbind)
15741 @table @asis
15743 @item @code{-b}
15745 Generate brief messages to @code{stderr} even if verbose mode set.
15746 @end table
15748 @geindex -c (gnatbind)
15751 @table @asis
15753 @item @code{-c}
15755 Check only, no generation of binder output file.
15756 @end table
15758 @geindex -dnn[k|m] (gnatbind)
15761 @table @asis
15763 @item @code{-d@emph{nn}[k|m]}
15765 This switch can be used to change the default task stack size value
15766 to a specified size @code{nn}, which is expressed in bytes by default, or
15767 in kilobytes when suffixed with @code{k} or in megabytes when suffixed
15768 with @code{m}.
15769 In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15770 in effect, to completing all task specs with
15772 @example
15773 pragma Storage_Size (nn);
15774 @end example
15776 When they do not already have such a pragma.
15777 @end table
15779 @geindex -D (gnatbind)
15782 @table @asis
15784 @item @code{-D@emph{nn}[k|m]}
15786 Set the default secondary stack size to @code{nn}. The suffix indicates whether
15787 the size is in bytes (no suffix), kilobytes (@code{k} suffix) or megabytes
15788 (@code{m} suffix).
15790 The secondary stack holds objects of unconstrained types that are returned by
15791 functions, for example unconstrained Strings. The size of the secondary stack
15792 can be dynamic or fixed depending on the target.
15794 For most targets, the secondary stack grows on demand and is implemented as
15795 a chain of blocks in the heap. In this case, the default secondary stack size
15796 determines the initial size of the secondary stack for each task and the
15797 smallest amount the secondary stack can grow by.
15799 For Light, Light-Tasking, and Embedded run-times the size of the secondary
15800 stack is fixed. This switch can be used to change the default size of these
15801 stacks. The default secondary stack size can be overridden on a per-task
15802 basis if individual tasks have different secondary stack requirements. This
15803 is achieved through the Secondary_Stack_Size aspect, which takes the size of
15804 the secondary stack in bytes.
15805 @end table
15807 @geindex -e (gnatbind)
15810 @table @asis
15812 @item @code{-e}
15814 Output complete list of elaboration-order dependencies.
15815 @end table
15817 @geindex -Ea (gnatbind)
15820 @table @asis
15822 @item @code{-Ea}
15824 Store tracebacks in exception occurrences when the target supports it.
15825 The “a” is for “address”; tracebacks will contain hexadecimal addresses,
15826 unless symbolic tracebacks are enabled.
15828 See also the packages @code{GNAT.Traceback} and
15829 @code{GNAT.Traceback.Symbolic} for more information.
15830 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
15831 @code{gcc} option.
15832 @end table
15834 @geindex -Es (gnatbind)
15837 @table @asis
15839 @item @code{-Es}
15841 Store tracebacks in exception occurrences when the target supports it.
15842 The “s” is for “symbolic”; symbolic tracebacks are enabled.
15843 @end table
15845 @geindex -E (gnatbind)
15848 @table @asis
15850 @item @code{-E}
15852 Currently the same as @code{-Ea}.
15853 @end table
15855 @geindex -f (gnatbind)
15858 @table @asis
15860 @item @code{-f@emph{elab-order}}
15862 Force elaboration order. For further details see @ref{113,,Elaboration Control}
15863 and @ref{f,,Elaboration Order Handling in GNAT}.
15864 @end table
15866 @geindex -F (gnatbind)
15869 @table @asis
15871 @item @code{-F}
15873 Force the checks of elaboration flags. @code{gnatbind} does not normally
15874 generate checks of elaboration flags for the main executable, except when
15875 a Stand-Alone Library is used. However, there are cases when this cannot be
15876 detected by gnatbind. An example is importing an interface of a Stand-Alone
15877 Library through a pragma Import and only specifying through a linker switch
15878 this Stand-Alone Library. This switch is used to guarantee that elaboration
15879 flag checks are generated.
15880 @end table
15882 @geindex -h (gnatbind)
15885 @table @asis
15887 @item @code{-h}
15889 Output usage (help) information.
15890 @end table
15892 @geindex -H (gnatbind)
15895 @table @asis
15897 @item @code{-H}
15899 Legacy elaboration order model enabled. For further details see
15900 @ref{f,,Elaboration Order Handling in GNAT}.
15901 @end table
15903 @geindex -H32 (gnatbind)
15906 @table @asis
15908 @item @code{-H32}
15910 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
15911 For further details see @ref{114,,Dynamic Allocation Control}.
15912 @end table
15914 @geindex -H64 (gnatbind)
15916 @geindex __gnat_malloc
15919 @table @asis
15921 @item @code{-H64}
15923 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
15924 For further details see @ref{114,,Dynamic Allocation Control}.
15926 @geindex -I (gnatbind)
15928 @item @code{-I}
15930 Specify directory to be searched for source and ALI files.
15932 @geindex -I- (gnatbind)
15934 @item @code{-I-}
15936 Do not look for sources in the current directory where @code{gnatbind} was
15937 invoked, and do not look for ALI files in the directory containing the
15938 ALI file named in the @code{gnatbind} command line.
15940 @geindex -k (gnatbind)
15942 @item @code{-k}
15944 Disable checking of elaboration flags. When using @code{-n}
15945 either explicitly or implicitly, @code{-F} is also implied,
15946 unless @code{-k} is used. This switch should be used with care
15947 and you should ensure manually that elaboration routines are not called
15948 twice unintentionally.
15950 @geindex -K (gnatbind)
15952 @item @code{-K}
15954 Give list of linker options specified for link.
15956 @geindex -l (gnatbind)
15958 @item @code{-l}
15960 Output chosen elaboration order.
15962 @geindex -L (gnatbind)
15964 @item @code{-L@emph{xxx}}
15966 Bind the units for library building. In this case the @code{adainit} and
15967 @code{adafinal} procedures (@ref{7e,,Binding with Non-Ada Main Programs})
15968 are renamed to @code{@emph{xxx}init} and
15969 @code{@emph{xxx}final}.
15970 Implies -n.
15971 (@ref{2a,,GNAT and Libraries}, for more details.)
15973 @geindex -M (gnatbind)
15975 @item @code{-M@emph{xyz}}
15977 Rename generated main program from main to xyz. This option is
15978 supported on cross environments only.
15980 @geindex -m (gnatbind)
15982 @item @code{-m@emph{n}}
15984 Limit number of detected errors or warnings to @code{n}, where @code{n} is
15985 in the range 1..999999. The default value if no switch is
15986 given is 9999. If the number of warnings reaches this limit, then a
15987 message is output and further warnings are suppressed, the bind
15988 continues in this case. If the number of errors reaches this
15989 limit, then a message is output and the bind is abandoned.
15990 A value of zero means that no limit is enforced. The equal
15991 sign is optional.
15993 @geindex -minimal (gnatbind)
15995 @item @code{-minimal}
15997 Generate a binder file suitable for space-constrained applications. When
15998 active, binder-generated objects not required for program operation are no
15999 longer generated. @strong{Warning:} this option comes with the following
16000 limitations:
16003 @itemize *
16005 @item 
16006 Starting the program’s execution in the debugger will cause it to
16007 stop at the start of the @code{main} function instead of the main subprogram.
16008 This can be worked around by manually inserting a breakpoint on that
16009 subprogram and resuming the program’s execution until reaching that breakpoint.
16011 @item 
16012 Programs using GNAT.Compiler_Version will not link.
16013 @end itemize
16015 @geindex -n (gnatbind)
16017 @item @code{-n}
16019 No main program.
16021 @geindex -nostdinc (gnatbind)
16023 @item @code{-nostdinc}
16025 Do not look for sources in the system default directory.
16027 @geindex -nostdlib (gnatbind)
16029 @item @code{-nostdlib}
16031 Do not look for library files in the system default directory.
16033 @geindex --RTS (gnatbind)
16035 @item @code{--RTS=@emph{rts-path}}
16037 Specifies the default location of the run-time library. Same meaning as the
16038 equivalent @code{gnatmake} flag (@ref{d0,,Switches for gnatmake}).
16040 @geindex -o (gnatbind)
16042 @item @code{-o @emph{file}}
16044 Name the output file @code{file} (default is @code{b~`xxx}.adb`).
16045 Note that if this option is used, then linking must be done manually,
16046 gnatlink cannot be used.
16048 @geindex -O (gnatbind)
16050 @item @code{-O[=@emph{filename}]}
16052 Output object list (to standard output or to the named file).
16054 @geindex -p (gnatbind)
16056 @item @code{-p}
16058 Pessimistic (worst-case) elaboration order.
16060 @geindex -P (gnatbind)
16062 @item @code{-P}
16064 Generate binder file suitable for CodePeer.
16065 @end table
16067 @geindex -Q (gnatbind)
16070 @table @asis
16072 @item @code{-Q@emph{nnn}}
16074 Generate @code{nnn} additional default-sized secondary stacks.
16076 Tasks declared at the library level that use default-size secondary stacks
16077 have their secondary stacks allocated from a pool of stacks generated by
16078 gnatbind. This allows the default secondary stack size to be quickly changed
16079 by rebinding the application.
16081 While the binder sizes this pool to match the number of such tasks defined in
16082 the application, the pool size may need to be increased with the @code{-Q}
16083 switch to accommodate foreign threads registered with the Light run-time. For
16084 more information, please see the @emph{The Primary and Secondary Stack} chapter in
16085 the @emph{GNAT User’s Guide Supplement for Cross Platforms}.
16087 @geindex -R (gnatbind)
16089 @item @code{-R}
16091 Output closure source list, which includes all non-run-time units that are
16092 included in the bind.
16094 @geindex -Ra (gnatbind)
16096 @item @code{-Ra}
16098 Like @code{-R} but the list includes run-time units.
16100 @geindex -s (gnatbind)
16102 @item @code{-s}
16104 Require all source files to be present.
16106 @geindex -S (gnatbind)
16108 @item @code{-S@emph{xxx}}
16110 Specifies the value to be used when detecting uninitialized scalar
16111 objects with pragma Initialize_Scalars.
16112 The @code{xxx} string specified with the switch is one of:
16115 @itemize *
16117 @item 
16118 @code{in} for an invalid value.
16120 If zero is invalid for the discrete type in question,
16121 then the scalar value is set to all zero bits.
16122 For signed discrete types, the largest possible negative value of
16123 the underlying scalar is set (i.e. a one bit followed by all zero bits).
16124 For unsigned discrete types, the underlying scalar value is set to all
16125 one bits. For floating-point types, a NaN value is set
16126 (see body of package System.Scalar_Values for exact values).
16128 @item 
16129 @code{lo} for low value.
16131 If zero is invalid for the discrete type in question,
16132 then the scalar value is set to all zero bits.
16133 For signed discrete types, the largest possible negative value of
16134 the underlying scalar is set (i.e. a one bit followed by all zero bits).
16135 For unsigned discrete types, the underlying scalar value is set to all
16136 zero bits. For floating-point, a small value is set
16137 (see body of package System.Scalar_Values for exact values).
16139 @item 
16140 @code{hi} for high value.
16142 If zero is invalid for the discrete type in question,
16143 then the scalar value is set to all one bits.
16144 For signed discrete types, the largest possible positive value of
16145 the underlying scalar is set (i.e. a zero bit followed by all one bits).
16146 For unsigned discrete types, the underlying scalar value is set to all
16147 one bits. For floating-point, a large value is set
16148 (see body of package System.Scalar_Values for exact values).
16150 @item 
16151 @code{xx} for hex value (two hex digits).
16153 The underlying scalar is set to a value consisting of repeated bytes, whose
16154 value corresponds to the given value. For example if @code{BF} is given,
16155 then a 32-bit scalar value will be set to the bit pattern @code{16#BFBFBFBF#}.
16156 @end itemize
16158 @geindex GNAT_INIT_SCALARS
16160 In addition, you can specify @code{-Sev} to indicate that the value is
16161 to be set at run time. In this case, the program will look for an environment
16162 variable of the form @code{GNAT_INIT_SCALARS=@emph{yy}}, where @code{yy} is one
16163 of @code{in/lo/hi/@emph{xx}} with the same meanings as above.
16164 If no environment variable is found, or if it does not have a valid value,
16165 then the default is @code{in} (invalid values).
16166 @end table
16168 @geindex -static (gnatbind)
16171 @table @asis
16173 @item @code{-static}
16175 Link against a static GNAT run-time.
16177 @geindex -shared (gnatbind)
16179 @item @code{-shared}
16181 Link against a shared GNAT run-time when available.
16183 @geindex -t (gnatbind)
16185 @item @code{-t}
16187 Tolerate time stamp and other consistency errors.
16189 @geindex -T (gnatbind)
16191 @item @code{-T@emph{n}}
16193 Set the time slice value to @code{n} milliseconds. If the system supports
16194 the specification of a specific time slice value, then the indicated value
16195 is used. If the system does not support specific time slice values, but
16196 does support some general notion of round-robin scheduling, then any
16197 nonzero value will activate round-robin scheduling.
16199 A value of zero is treated specially. It turns off time
16200 slicing, and in addition, indicates to the tasking run-time that the
16201 semantics should match as closely as possible the Annex D
16202 requirements of the Ada RM, and in particular sets the default
16203 scheduling policy to @code{FIFO_Within_Priorities}.
16205 @geindex -u (gnatbind)
16207 @item @code{-u@emph{n}}
16209 Enable dynamic stack usage, with @code{n} results stored and displayed
16210 at program termination. A result is generated when a task
16211 terminates. Results that can’t be stored are displayed on the fly, at
16212 task termination. This option is currently not supported on Itanium
16213 platforms. (See @ref{115,,Dynamic Stack Usage Analysis} for details.)
16215 @geindex -v (gnatbind)
16217 @item @code{-v}
16219 Verbose mode. Write error messages, header, summary output to
16220 @code{stdout}.
16222 @geindex -V (gnatbind)
16224 @item @code{-V@emph{key}=@emph{value}}
16226 Store the given association of @code{key} to @code{value} in the bind environment.
16227 Values stored this way can be retrieved at run time using
16228 @code{GNAT.Bind_Environment}.
16230 @geindex -w (gnatbind)
16232 @item @code{-w@emph{x}}
16234 Warning mode; @code{x} = s/e for suppress/treat as error.
16236 @geindex -Wx (gnatbind)
16238 @item @code{-Wx@emph{e}}
16240 Override default wide character encoding for standard Text_IO files.
16242 @geindex -x (gnatbind)
16244 @item @code{-x}
16246 Exclude source files (check object consistency only).
16248 @geindex -xdr (gnatbind)
16250 @item @code{-xdr}
16252 Use the target-independent XDR protocol for stream oriented attributes
16253 instead of the default implementation which is based on direct binary
16254 representations and is therefore target-and endianness-dependent.
16255 However it does not support 128-bit integer types and the exception
16256 @code{Ada.IO_Exceptions.Device_Error} is raised if any attempt is made
16257 at streaming 128-bit integer types with it.
16259 @geindex -Xnnn (gnatbind)
16261 @item @code{-X@emph{nnn}}
16263 Set default exit status value, normally 0 for POSIX compliance.
16265 @geindex -y (gnatbind)
16267 @item @code{-y}
16269 Enable leap seconds support in @code{Ada.Calendar} and its children.
16271 @geindex -z (gnatbind)
16273 @item @code{-z}
16275 No main subprogram.
16276 @end table
16278 You may obtain this listing of switches by running @code{gnatbind} with
16279 no arguments.
16281 @menu
16282 * Consistency-Checking Modes:: 
16283 * Binder Error Message Control:: 
16284 * Elaboration Control:: 
16285 * Output Control:: 
16286 * Dynamic Allocation Control:: 
16287 * Binding with Non-Ada Main Programs:: 
16288 * Binding Programs with No Main Subprogram:: 
16290 @end menu
16292 @node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
16293 @anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{116}@anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{117}
16294 @subsubsection Consistency-Checking Modes
16297 As described earlier, by default @code{gnatbind} checks
16298 that object files are consistent with one another and are consistent
16299 with any source files it can locate. The following switches control binder
16300 access to sources.
16302 @quotation
16304 @geindex -s (gnatbind)
16305 @end quotation
16308 @table @asis
16310 @item @code{-s}
16312 Require source files to be present. In this mode, the binder must be
16313 able to locate all source files that are referenced, in order to check
16314 their consistency. In normal mode, if a source file cannot be located it
16315 is simply ignored. If you specify this switch, a missing source
16316 file is an error.
16318 @geindex -Wx (gnatbind)
16320 @item @code{-Wx@emph{e}}
16322 Override default wide character encoding for standard Text_IO files.
16323 Normally the default wide character encoding method used for standard
16324 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
16325 the main source input (see description of switch
16326 @code{-gnatWx} for the compiler). The
16327 use of this switch for the binder (which has the same set of
16328 possible arguments) overrides this default as specified.
16330 @geindex -x (gnatbind)
16332 @item @code{-x}
16334 Exclude source files. In this mode, the binder only checks that ALI
16335 files are consistent with one another. Source files are not accessed.
16336 The binder runs faster in this mode, and there is still a guarantee that
16337 the resulting program is self-consistent.
16338 If a source file has been edited since it was last compiled, and you
16339 specify this switch, the binder will not detect that the object
16340 file is out of date with respect to the source file. Note that this is the
16341 mode that is automatically used by @code{gnatmake} because in this
16342 case the checking against sources has already been performed by
16343 @code{gnatmake} in the course of compilation (i.e., before binding).
16344 @end table
16346 @node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
16347 @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}
16348 @subsubsection Binder Error Message Control
16351 The following switches provide control over the generation of error
16352 messages from the binder:
16354 @quotation
16356 @geindex -v (gnatbind)
16357 @end quotation
16360 @table @asis
16362 @item @code{-v}
16364 Verbose mode. In the normal mode, brief error messages are generated to
16365 @code{stderr}. If this switch is present, a header is written
16366 to @code{stdout} and any error messages are directed to @code{stdout}.
16367 All that is written to @code{stderr} is a brief summary message.
16369 @geindex -b (gnatbind)
16371 @item @code{-b}
16373 Generate brief error messages to @code{stderr} even if verbose mode is
16374 specified. This is relevant only when used with the
16375 @code{-v} switch.
16377 @geindex -m (gnatbind)
16379 @item @code{-m@emph{n}}
16381 Limits the number of error messages to @code{n}, a decimal integer in the
16382 range 1-999. The binder terminates immediately if this limit is reached.
16384 @geindex -M (gnatbind)
16386 @item @code{-M@emph{xxx}}
16388 Renames the generated main program from @code{main} to @code{xxx}.
16389 This is useful in the case of some cross-building environments, where
16390 the actual main program is separate from the one generated
16391 by @code{gnatbind}.
16393 @geindex -ws (gnatbind)
16395 @geindex Warnings
16397 @item @code{-ws}
16399 Suppress all warning messages.
16401 @geindex -we (gnatbind)
16403 @item @code{-we}
16405 Treat any warning messages as fatal errors.
16407 @geindex -t (gnatbind)
16409 @geindex Time stamp checks
16410 @geindex in binder
16412 @geindex Binder consistency checks
16414 @geindex Consistency checks
16415 @geindex in binder
16417 @item @code{-t}
16419 The binder performs a number of consistency checks including:
16422 @itemize *
16424 @item 
16425 Check that time stamps of a given source unit are consistent
16427 @item 
16428 Check that checksums of a given source unit are consistent
16430 @item 
16431 Check that consistent versions of @code{GNAT} were used for compilation
16433 @item 
16434 Check consistency of configuration pragmas as required
16435 @end itemize
16437 Normally failure of such checks, in accordance with the consistency
16438 requirements of the Ada Reference Manual, causes error messages to be
16439 generated which abort the binder and prevent the output of a binder
16440 file and subsequent link to obtain an executable.
16442 The @code{-t} switch converts these error messages
16443 into warnings, so that
16444 binding and linking can continue to completion even in the presence of such
16445 errors. The result may be a failed link (due to missing symbols), or a
16446 non-functional executable which has undefined semantics.
16448 @cartouche
16449 @quotation Note 
16450 This means that @code{-t} should be used only in unusual situations,
16451 with extreme care.
16452 @end quotation
16453 @end cartouche
16454 @end table
16456 @node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
16457 @anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{113}@anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{11a}
16458 @subsubsection Elaboration Control
16461 The following switches provide additional control over the elaboration
16462 order. For further details see @ref{f,,Elaboration Order Handling in GNAT}.
16464 @geindex -f (gnatbind)
16467 @table @asis
16469 @item @code{-f@emph{elab-order}}
16471 Force elaboration order.
16473 @code{elab-order} should be the name of a “forced elaboration order file”, that
16474 is, a text file containing library item names, one per line. A name of the
16475 form “some.unit%s” or “some.unit (spec)” denotes the spec of Some.Unit. A
16476 name of the form “some.unit%b” or “some.unit (body)” denotes the body of
16477 Some.Unit. Each pair of lines is taken to mean that there is an elaboration
16478 dependence of the second line on the first. For example, if the file
16479 contains:
16481 @example
16482 this (spec)
16483 this (body)
16484 that (spec)
16485 that (body)
16486 @end example
16488 then the spec of This will be elaborated before the body of This, and the
16489 body of This will be elaborated before the spec of That, and the spec of That
16490 will be elaborated before the body of That. The first and last of these three
16491 dependences are already required by Ada rules, so this file is really just
16492 forcing the body of This to be elaborated before the spec of That.
16494 The given order must be consistent with Ada rules, or else @code{gnatbind} will
16495 give elaboration cycle errors. For example, if you say x (body) should be
16496 elaborated before x (spec), there will be a cycle, because Ada rules require
16497 x (spec) to be elaborated before x (body); you can’t have the spec and body
16498 both elaborated before each other.
16500 If you later add “with That;” to the body of This, there will be a cycle, in
16501 which case you should erase either “this (body)” or “that (spec)” from the
16502 above forced elaboration order file.
16504 Blank lines and Ada-style comments are ignored. Unit names that do not exist
16505 in the program are ignored. Units in the GNAT predefined library are also
16506 ignored.
16507 @end table
16509 @geindex -p (gnatbind)
16512 @table @asis
16514 @item @code{-p}
16516 Pessimistic elaboration order
16518 This switch is only applicable to the pre-20.x legacy elaboration models.
16519 The post-20.x elaboration model uses a more informed approach of ordering
16520 the units.
16522 Normally the binder attempts to choose an elaboration order that is likely to
16523 minimize the likelihood of an elaboration order error resulting in raising a
16524 @code{Program_Error} exception. This switch reverses the action of the binder,
16525 and requests that it deliberately choose an order that is likely to maximize
16526 the likelihood of an elaboration error. This is useful in ensuring
16527 portability and avoiding dependence on accidental fortuitous elaboration
16528 ordering.
16530 Normally it only makes sense to use the @code{-p} switch if dynamic
16531 elaboration checking is used (@code{-gnatE} switch used for compilation).
16532 This is because in the default static elaboration mode, all necessary
16533 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
16534 These implicit pragmas are still respected by the binder in @code{-p}
16535 mode, so a safe elaboration order is assured.
16537 Note that @code{-p} is not intended for production use; it is more for
16538 debugging/experimental use.
16539 @end table
16541 @node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
16542 @anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{11b}@anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{11c}
16543 @subsubsection Output Control
16546 The following switches allow additional control over the output
16547 generated by the binder.
16549 @quotation
16551 @geindex -c (gnatbind)
16552 @end quotation
16555 @table @asis
16557 @item @code{-c}
16559 Check only. Do not generate the binder output file. In this mode the
16560 binder performs all error checks but does not generate an output file.
16562 @geindex -e (gnatbind)
16564 @item @code{-e}
16566 Output complete list of elaboration-order dependencies, showing the
16567 reason for each dependency. This output can be rather extensive but may
16568 be useful in diagnosing problems with elaboration order. The output is
16569 written to @code{stdout}.
16571 @geindex -h (gnatbind)
16573 @item @code{-h}
16575 Output usage information. The output is written to @code{stdout}.
16577 @geindex -K (gnatbind)
16579 @item @code{-K}
16581 Output linker options to @code{stdout}. Includes library search paths,
16582 contents of pragmas Ident and Linker_Options, and libraries added
16583 by @code{gnatbind}.
16585 @geindex -l (gnatbind)
16587 @item @code{-l}
16589 Output chosen elaboration order. The output is written to @code{stdout}.
16591 @geindex -O (gnatbind)
16593 @item @code{-O}
16595 Output full names of all the object files that must be linked to provide
16596 the Ada component of the program. The output is written to @code{stdout}.
16597 This list includes the files explicitly supplied and referenced by the user
16598 as well as implicitly referenced run-time unit files. The latter are
16599 omitted if the corresponding units reside in shared libraries. The
16600 directory names for the run-time units depend on the system configuration.
16602 @geindex -o (gnatbind)
16604 @item @code{-o @emph{file}}
16606 Set name of output file to @code{file} instead of the normal
16607 @code{b~`mainprog}.adb` default. Note that @code{file} denote the Ada
16608 binder generated body filename.
16609 Note that if this option is used, then linking must be done manually.
16610 It is not possible to use gnatlink in this case, since it cannot locate
16611 the binder file.
16613 @geindex -r (gnatbind)
16615 @item @code{-r}
16617 Generate list of @code{pragma Restrictions} that could be applied to
16618 the current unit. This is useful for code audit purposes, and also may
16619 be used to improve code generation in some cases.
16620 @end table
16622 @node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
16623 @anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{114}@anchor{gnat_ugn/building_executable_programs_with_gnat id39}@anchor{11d}
16624 @subsubsection Dynamic Allocation Control
16627 The heap control switches – @code{-H32} and @code{-H64} –
16628 determine whether dynamic allocation uses 32-bit or 64-bit memory.
16629 They only affect compiler-generated allocations via @code{__gnat_malloc};
16630 explicit calls to @code{malloc} and related functions from the C
16631 run-time library are unaffected.
16634 @table @asis
16636 @item @code{-H32}
16638 Allocate memory on 32-bit heap
16640 @item @code{-H64}
16642 Allocate memory on 64-bit heap.  This is the default
16643 unless explicitly overridden by a @code{'Size} clause on the access type.
16644 @end table
16646 These switches are only effective on VMS platforms.
16648 @node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
16649 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-non-ada-main-programs}@anchor{7e}@anchor{gnat_ugn/building_executable_programs_with_gnat id40}@anchor{11e}
16650 @subsubsection Binding with Non-Ada Main Programs
16653 The description so far has assumed that the main
16654 program is in Ada, and that the task of the binder is to generate a
16655 corresponding function @code{main} that invokes this Ada main
16656 program. GNAT also supports the building of executable programs where
16657 the main program is not in Ada, but some of the called routines are
16658 written in Ada and compiled using GNAT (@ref{2c,,Mixed Language Programming}).
16659 The following switch is used in this situation:
16661 @quotation
16663 @geindex -n (gnatbind)
16664 @end quotation
16667 @table @asis
16669 @item @code{-n}
16671 No main program. The main program is not in Ada.
16672 @end table
16674 In this case, most of the functions of the binder are still required,
16675 but instead of generating a main program, the binder generates a file
16676 containing the following callable routines:
16678 @quotation
16680 @geindex adainit
16683 @table @asis
16685 @item @code{adainit}
16687 You must call this routine to initialize the Ada part of the program by
16688 calling the necessary elaboration routines. A call to @code{adainit} is
16689 required before the first call to an Ada subprogram.
16691 Note that it is assumed that the basic execution environment must be setup
16692 to be appropriate for Ada execution at the point where the first Ada
16693 subprogram is called. In particular, if the Ada code will do any
16694 floating-point operations, then the FPU must be setup in an appropriate
16695 manner. For the case of the x86, for example, full precision mode is
16696 required. The procedure GNAT.Float_Control.Reset may be used to ensure
16697 that the FPU is in the right state.
16698 @end table
16700 @geindex adafinal
16703 @table @asis
16705 @item @code{adafinal}
16707 You must call this routine to perform any library-level finalization
16708 required by the Ada subprograms. A call to @code{adafinal} is required
16709 after the last call to an Ada subprogram, and before the program
16710 terminates.
16711 @end table
16712 @end quotation
16714 @geindex -n (gnatbind)
16716 @geindex Binder
16717 @geindex multiple input files
16719 If the @code{-n} switch
16720 is given, more than one ALI file may appear on
16721 the command line for @code{gnatbind}. The normal @code{closure}
16722 calculation is performed for each of the specified units. Calculating
16723 the closure means finding out the set of units involved by tracing
16724 @emph{with} references. The reason it is necessary to be able to
16725 specify more than one ALI file is that a given program may invoke two or
16726 more quite separate groups of Ada units.
16728 The binder takes the name of its output file from the last specified ALI
16729 file, unless overridden by the use of the @code{-o file}.
16731 @geindex -o (gnatbind)
16733 The output is an Ada unit in source form that can be compiled with GNAT.
16734 This compilation occurs automatically as part of the @code{gnatlink}
16735 processing.
16737 Currently the GNAT run-time requires a FPU using 80 bits mode
16738 precision. Under targets where this is not the default it is required to
16739 call GNAT.Float_Control.Reset before using floating point numbers (this
16740 include float computation, float input and output) in the Ada code. A
16741 side effect is that this could be the wrong mode for the foreign code
16742 where floating point computation could be broken after this call.
16744 @node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
16745 @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}
16746 @subsubsection Binding Programs with No Main Subprogram
16749 It is possible to have an Ada program which does not have a main
16750 subprogram. This program will call the elaboration routines of all the
16751 packages, then the finalization routines.
16753 The following switch is used to bind programs organized in this manner:
16755 @quotation
16757 @geindex -z (gnatbind)
16758 @end quotation
16761 @table @asis
16763 @item @code{-z}
16765 Normally the binder checks that the unit name given on the command line
16766 corresponds to a suitable main subprogram. When this switch is used,
16767 a list of ALI files can be given, and the execution of the program
16768 consists of elaboration of these units in an appropriate order. Note
16769 that the default wide character encoding method for standard Text_IO
16770 files is always set to Brackets if this switch is set (you can use
16771 the binder switch
16772 @code{-Wx} to override this default).
16773 @end table
16775 @node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
16776 @anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{121}@anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{122}
16777 @subsection Command-Line Access
16780 The package @code{Ada.Command_Line} provides access to the command-line
16781 arguments and program name. In order for this interface to operate
16782 correctly, the two variables
16784 @example
16785 int gnat_argc;
16786 char **gnat_argv;
16787 @end example
16789 @geindex gnat_argv
16791 @geindex gnat_argc
16793 are declared in one of the GNAT library routines. These variables must
16794 be set from the actual @code{argc} and @code{argv} values passed to the
16795 main program. With no @emph{n} present, @code{gnatbind}
16796 generates the C main program to automatically set these variables.
16797 If the @emph{n} switch is used, there is no automatic way to
16798 set these variables. If they are not set, the procedures in
16799 @code{Ada.Command_Line} will not be available, and any attempt to use
16800 them will raise @code{Constraint_Error}. If command line access is
16801 required, your main program must set @code{gnat_argc} and
16802 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
16805 @node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
16806 @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}
16807 @subsection Search Paths for @code{gnatbind}
16810 The binder takes the name of an ALI file as its argument and needs to
16811 locate source files as well as other ALI files to verify object consistency.
16813 For source files, it follows exactly the same search rules as @code{gcc}
16814 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
16815 directories searched are:
16818 @itemize *
16820 @item 
16821 The directory containing the ALI file named in the command line, unless
16822 the switch @code{-I-} is specified.
16824 @item 
16825 All directories specified by @code{-I}
16826 switches on the @code{gnatbind}
16827 command line, in the order given.
16829 @geindex ADA_PRJ_OBJECTS_FILE
16831 @item 
16832 Each of the directories listed in the text file whose name is given
16833 by the 
16834 @geindex ADA_PRJ_OBJECTS_FILE
16835 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16836 @code{ADA_PRJ_OBJECTS_FILE} environment variable.
16838 @geindex ADA_PRJ_OBJECTS_FILE
16839 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16840 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
16841 driver when project files are used. It should not normally be set
16842 by other means.
16844 @geindex ADA_OBJECTS_PATH
16846 @item 
16847 Each of the directories listed in the value of the
16848 @geindex ADA_OBJECTS_PATH
16849 @geindex environment variable; ADA_OBJECTS_PATH
16850 @code{ADA_OBJECTS_PATH} environment variable.
16851 Construct this value
16852 exactly as the 
16853 @geindex PATH
16854 @geindex environment variable; PATH
16855 @code{PATH} environment variable: a list of directory
16856 names separated by colons (semicolons when working with the NT version
16857 of GNAT).
16859 @item 
16860 The content of the @code{ada_object_path} file which is part of the GNAT
16861 installation tree and is used to store standard libraries such as the
16862 GNAT Run-Time Library (RTL) unless the switch @code{-nostdlib} is
16863 specified. See @ref{72,,Installing a library}
16864 @end itemize
16866 @geindex -I (gnatbind)
16868 @geindex -aI (gnatbind)
16870 @geindex -aO (gnatbind)
16872 In the binder the switch @code{-I}
16873 is used to specify both source and
16874 library file paths. Use @code{-aI}
16875 instead if you want to specify
16876 source paths only, and @code{-aO}
16877 if you want to specify library paths
16878 only. This means that for the binder
16879 @code{-I@emph{dir}} is equivalent to
16880 @code{-aI@emph{dir}}
16881 @code{-aO`@emph{dir}}.
16882 The binder generates the bind file (a C language source file) in the
16883 current working directory.
16885 @geindex Ada
16887 @geindex System
16889 @geindex Interfaces
16891 @geindex GNAT
16893 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
16894 children make up the GNAT Run-Time Library, together with the package
16895 GNAT and its children, which contain a set of useful additional
16896 library functions provided by GNAT. The sources for these units are
16897 needed by the compiler and are kept together in one directory. The ALI
16898 files and object files generated by compiling the RTL are needed by the
16899 binder and the linker and are kept together in one directory, typically
16900 different from the directory containing the sources. In a normal
16901 installation, you need not specify these directory names when compiling
16902 or binding. Either the environment variables or the built-in defaults
16903 cause these files to be found.
16905 Besides simplifying access to the RTL, a major use of search paths is
16906 in compiling sources from multiple directories. This can make
16907 development environments much more flexible.
16909 @node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16910 @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}
16911 @subsection Examples of @code{gnatbind} Usage
16914 Here are some examples of @code{gnatbind} invocations:
16916 @quotation
16918 @example
16919 gnatbind hello
16920 @end example
16922 The main program @code{Hello} (source program in @code{hello.adb}) is
16923 bound using the standard switch settings. The generated main program is
16924 @code{b~hello.adb}. This is the normal, default use of the binder.
16926 @example
16927 gnatbind hello -o mainprog.adb
16928 @end example
16930 The main program @code{Hello} (source program in @code{hello.adb}) is
16931 bound using the standard switch settings. The generated main program is
16932 @code{mainprog.adb} with the associated spec in
16933 @code{mainprog.ads}. Note that you must specify the body here not the
16934 spec. Note that if this option is used, then linking must be done manually,
16935 since gnatlink will not be able to find the generated file.
16936 @end quotation
16938 @node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16939 @anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{126}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{cb}
16940 @section Linking with @code{gnatlink}
16943 @geindex gnatlink
16945 This chapter discusses @code{gnatlink}, a tool that links
16946 an Ada program and builds an executable file. This utility
16947 invokes the system linker (via the @code{gcc} command)
16948 with a correct list of object files and library references.
16949 @code{gnatlink} automatically determines the list of files and
16950 references for the Ada part of a program. It uses the binder file
16951 generated by the @code{gnatbind} to determine this list.
16953 @menu
16954 * Running gnatlink:: 
16955 * Switches for gnatlink:: 
16957 @end menu
16959 @node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16960 @anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{127}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{128}
16961 @subsection Running @code{gnatlink}
16964 The form of the @code{gnatlink} command is
16966 @example
16967 $ gnatlink [ switches ] mainprog [.ali]
16968            [ non-Ada objects ] [ linker options ]
16969 @end example
16971 The arguments of @code{gnatlink} (switches, main @code{ALI} file,
16972 non-Ada objects
16973 or linker options) may be in any order, provided that no non-Ada object may
16974 be mistaken for a main @code{ALI} file.
16975 Any file name @code{F} without the @code{.ali}
16976 extension will be taken as the main @code{ALI} file if a file exists
16977 whose name is the concatenation of @code{F} and @code{.ali}.
16979 @code{mainprog.ali} references the ALI file of the main program.
16980 The @code{.ali} extension of this file can be omitted. From this
16981 reference, @code{gnatlink} locates the corresponding binder file
16982 @code{b~mainprog.adb} and, using the information in this file along
16983 with the list of non-Ada objects and linker options, constructs a
16984 linker command file to create the executable.
16986 The arguments other than the @code{gnatlink} switches and the main
16987 @code{ALI} file are passed to the linker uninterpreted.
16988 They typically include the names of
16989 object files for units written in other languages than Ada and any library
16990 references required to resolve references in any of these foreign language
16991 units, or in @code{Import} pragmas in any Ada units.
16993 @code{linker options} is an optional list of linker specific
16994 switches.
16995 The default linker called by gnatlink is @code{gcc} which in
16996 turn calls the appropriate system linker.
16998 One useful option for the linker is @code{-s}: it reduces the size of the
16999 executable by removing all symbol table and relocation information from the
17000 executable.
17002 Standard options for the linker such as @code{-lmy_lib} or
17003 @code{-Ldir} can be added as is.
17004 For options that are not recognized by
17005 @code{gcc} as linker options, use the @code{gcc} switches
17006 @code{-Xlinker} or @code{-Wl,}.
17008 Refer to the GCC documentation for
17009 details.
17011 Here is an example showing how to generate a linker map:
17013 @example
17014 $ gnatlink my_prog -Wl,-Map,MAPFILE
17015 @end example
17017 Using @code{linker options} it is possible to set the program stack and
17018 heap size.
17019 See @ref{129,,Setting Stack Size from gnatlink} and
17020 @ref{12a,,Setting Heap Size from gnatlink}.
17022 @code{gnatlink} determines the list of objects required by the Ada
17023 program and prepends them to the list of objects passed to the linker.
17024 @code{gnatlink} also gathers any arguments set by the use of
17025 @code{pragma Linker_Options} and adds them to the list of arguments
17026 presented to the linker.
17028 @node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
17029 @anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{12b}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{12c}
17030 @subsection Switches for @code{gnatlink}
17033 The following switches are available with the @code{gnatlink} utility:
17035 @geindex --version (gnatlink)
17038 @table @asis
17040 @item @code{--version}
17042 Display Copyright and version, then exit disregarding all other options.
17043 @end table
17045 @geindex --help (gnatlink)
17048 @table @asis
17050 @item @code{--help}
17052 If @code{--version} was not used, display usage, then exit disregarding
17053 all other options.
17054 @end table
17056 @geindex Command line length
17058 @geindex -f (gnatlink)
17061 @table @asis
17063 @item @code{-f}
17065 On some targets, the command line length is limited, and @code{gnatlink}
17066 will generate a separate file for the linker if the list of object files
17067 is too long.
17068 The @code{-f} switch forces this file
17069 to be generated even if
17070 the limit is not exceeded. This is useful in some cases to deal with
17071 special situations where the command line length is exceeded.
17072 @end table
17074 @geindex Debugging information
17075 @geindex including
17077 @geindex -g (gnatlink)
17080 @table @asis
17082 @item @code{-g}
17084 The option to include debugging information causes the Ada bind file (in
17085 other words, @code{b~mainprog.adb}) to be compiled with @code{-g}.
17086 In addition, the binder does not delete the @code{b~mainprog.adb},
17087 @code{b~mainprog.o} and @code{b~mainprog.ali} files.
17088 Without @code{-g}, the binder removes these files by default.
17089 @end table
17091 @geindex -n (gnatlink)
17094 @table @asis
17096 @item @code{-n}
17098 Do not compile the file generated by the binder. This may be used when
17099 a link is rerun with different options, but there is no need to recompile
17100 the binder file.
17101 @end table
17103 @geindex -v (gnatlink)
17106 @table @asis
17108 @item @code{-v}
17110 Verbose mode. Causes additional information to be output, including a full
17111 list of the included object files.
17112 This switch option is most useful when you want
17113 to see what set of object files are being used in the link step.
17114 @end table
17116 @geindex -v -v (gnatlink)
17119 @table @asis
17121 @item @code{-v -v}
17123 Very verbose mode. Requests that the compiler operate in verbose mode when
17124 it compiles the binder file, and that the system linker run in verbose mode.
17125 @end table
17127 @geindex -o (gnatlink)
17130 @table @asis
17132 @item @code{-o @emph{exec-name}}
17134 @code{exec-name} specifies an alternate name for the generated
17135 executable program. If this switch is omitted, the executable has the same
17136 name as the main unit. For example, @code{gnatlink try.ali} creates
17137 an executable called @code{try}.
17138 @end table
17140 @geindex -B (gnatlink)
17143 @table @asis
17145 @item @code{-B@emph{dir}}
17147 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
17148 from @code{dir} instead of the default location. Only use this switch
17149 when multiple versions of the GNAT compiler are available.
17150 See the @code{Directory Options} section in @cite{The_GNU_Compiler_Collection}
17151 for further details. You would normally use the @code{-b} or
17152 @code{-V} switch instead.
17153 @end table
17155 @geindex -M (gnatlink)
17158 @table @asis
17160 @item @code{-M}
17162 When linking an executable, create a map file. The name of the map file
17163 has the same name as the executable with extension “.map”.
17164 @end table
17166 @geindex -M= (gnatlink)
17169 @table @asis
17171 @item @code{-M=@emph{mapfile}}
17173 When linking an executable, create a map file. The name of the map file is
17174 @code{mapfile}.
17175 @end table
17177 @geindex --GCC=compiler_name (gnatlink)
17180 @table @asis
17182 @item @code{--GCC=@emph{compiler_name}}
17184 Program used for compiling the binder file. The default is
17185 @code{gcc}. You need to use quotes around @code{compiler_name} if
17186 @code{compiler_name} contains spaces or other separator characters.
17187 As an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to
17188 use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
17189 inserted after your command name. Thus in the above example the compiler
17190 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
17191 A limitation of this syntax is that the name and path name of the executable
17192 itself must not include any embedded spaces. If the compiler executable is
17193 different from the default one (gcc or <prefix>-gcc), then the back-end
17194 switches in the ALI file are not used to compile the binder generated source.
17195 For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
17196 switches will be used for @code{--GCC="gcc -gnatv"}. If several
17197 @code{--GCC=compiler_name} are used, only the last @code{compiler_name}
17198 is taken into account. However, all the additional switches are also taken
17199 into account. Thus,
17200 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
17201 @code{--GCC="bar -x -y -z -t"}.
17202 @end table
17204 @geindex --LINK= (gnatlink)
17207 @table @asis
17209 @item @code{--LINK=@emph{name}}
17211 @code{name} is the name of the linker to be invoked. This is especially
17212 useful in mixed language programs since languages such as C++ require
17213 their own linker to be used. When this switch is omitted, the default
17214 name for the linker is @code{gcc}. When this switch is used, the
17215 specified linker is called instead of @code{gcc} with exactly the same
17216 parameters that would have been passed to @code{gcc} so if the desired
17217 linker requires different parameters it is necessary to use a wrapper
17218 script that massages the parameters before invoking the real linker. It
17219 may be useful to control the exact invocation by using the verbose
17220 switch.
17221 @end table
17223 @node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
17224 @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}
17225 @section Using the GNU @code{make} Utility
17228 @geindex make (GNU)
17229 @geindex GNU make
17231 This chapter offers some examples of makefiles that solve specific
17232 problems. It does not explain how to write a makefile, nor does it try to replace the
17233 @code{gnatmake} utility (@ref{c8,,Building with gnatmake}).
17235 All the examples in this section are specific to the GNU version of
17236 make. Although @code{make} is a standard utility, and the basic language
17237 is the same, these examples use some advanced features found only in
17238 @code{GNU make}.
17240 @menu
17241 * Using gnatmake in a Makefile:: 
17242 * Automatically Creating a List of Directories:: 
17243 * Generating the Command Line Switches:: 
17244 * Overcoming Command Line Length Limits:: 
17246 @end menu
17248 @node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
17249 @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}
17250 @subsection Using gnatmake in a Makefile
17253 @c index makefile (GNU make)
17255 Complex project organizations can be handled in a very powerful way by
17256 using GNU make combined with gnatmake. For instance, here is a Makefile
17257 which allows you to build each subsystem of a big project into a separate
17258 shared library. Such a makefile allows you to significantly reduce the link
17259 time of very big applications while maintaining full coherence at
17260 each step of the build process.
17262 The list of dependencies are handled automatically by
17263 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
17264 the appropriate directories.
17266 Note that you should also read the example on how to automatically
17267 create the list of directories
17268 (@ref{130,,Automatically Creating a List of Directories})
17269 which might help you in case your project has a lot of subdirectories.
17271 @example
17272 ## This Makefile is intended to be used with the following directory
17273 ## configuration:
17274 ##  - The sources are split into a series of csc (computer software components)
17275 ##    Each of these csc is put in its own directory.
17276 ##    Their name are referenced by the directory names.
17277 ##    They will be compiled into shared library (although this would also work
17278 ##    with static libraries)
17279 ##  - The main program (and possibly other packages that do not belong to any
17280 ##    csc) is put in the top level directory (where the Makefile is).
17281 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17282 ##                    \\_ second_csc (sources) __ lib (will contain the library)
17283 ##                    \\_ ...
17284 ## Although this Makefile is build for shared library, it is easy to modify
17285 ## to build partial link objects instead (modify the lines with -shared and
17286 ## gnatlink below)
17288 ## With this makefile, you can change any file in the system or add any new
17289 ## file, and everything will be recompiled correctly (only the relevant shared
17290 ## objects will be recompiled, and the main program will be re-linked).
17292 # The list of computer software component for your project. This might be
17293 # generated automatically.
17294 CSC_LIST=aa bb cc
17296 # Name of the main program (no extension)
17297 MAIN=main
17299 # If we need to build objects with -fPIC, uncomment the following line
17300 #NEED_FPIC=-fPIC
17302 # The following variable should give the directory containing libgnat.so
17303 # You can get this directory through 'gnatls -v'. This is usually the last
17304 # directory in the Object_Path.
17305 GLIB=...
17307 # The directories for the libraries
17308 # (This macro expands the list of CSC to the list of shared libraries, you
17309 # could simply use the expanded form:
17310 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17311 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17313 $@{MAIN@}: objects $@{LIB_DIR@}
17314     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17315     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17317 objects::
17318     # recompile the sources
17319     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17321 # Note: In a future version of GNAT, the following commands will be simplified
17322 # by a new tool, gnatmlib
17323 $@{LIB_DIR@}:
17324     mkdir -p $@{dir $@@ @}
17325     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17326     cd $@{dir $@@ @} && cp -f ../*.ali .
17328 # The dependencies for the modules
17329 # Note that we have to force the expansion of *.o, since in some cases
17330 # make won't be able to do it itself.
17331 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17332 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17333 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17335 # Make sure all of the shared libraries are in the path before starting the
17336 # program
17337 run::
17338     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17340 clean::
17341     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17342     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17343     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17344     $@{RM@} *.o *.ali $@{MAIN@}
17345 @end example
17347 @node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
17348 @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}
17349 @subsection Automatically Creating a List of Directories
17352 In most makefiles, you will have to specify a list of directories, and
17353 store it in a variable. For small projects, it is often easier to
17354 specify each of them by hand, since you then have full control over what
17355 is the proper order for these directories, which ones should be
17356 included.
17358 However, in larger projects, which might involve hundreds of
17359 subdirectories, it might be more convenient to generate this list
17360 automatically.
17362 The example below presents two methods. The first one, although less
17363 general, gives you more control over the list. It involves wildcard
17364 characters, that are automatically expanded by @code{make}. Its
17365 shortcoming is that you need to explicitly specify some of the
17366 organization of your project, such as for instance the directory tree
17367 depth, whether some directories are found in a separate tree, etc.
17369 The second method is the most general one. It requires an external
17370 program, called @code{find}, which is standard on all Unix systems. All
17371 the directories found under a given root directory will be added to the
17372 list.
17374 @example
17375 # The examples below are based on the following directory hierarchy:
17376 # All the directories can contain any number of files
17377 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17378 #                       ->  ab
17379 #                       ->  ac
17380 #                ->  b  ->  ba  ->  baa
17381 #                       ->  bb
17382 #                       ->  bc
17383 # This Makefile creates a variable called DIRS, that can be reused any time
17384 # you need this list (see the other examples in this section)
17386 # The root of your project's directory hierarchy
17387 ROOT_DIRECTORY=.
17389 ####
17390 # First method: specify explicitly the list of directories
17391 # This allows you to specify any subset of all the directories you need.
17392 ####
17394 DIRS := a/aa/ a/ab/ b/ba/
17396 ####
17397 # Second method: use wildcards
17398 # Note that the argument(s) to wildcard below should end with a '/'.
17399 # Since wildcards also return file names, we have to filter them out
17400 # to avoid duplicate directory names.
17401 # We thus use make's `@w{`}dir`@w{`} and `@w{`}sort`@w{`} functions.
17402 # It sets DIRs to the following value (note that the directories aaa and baa
17403 # are not given, unless you change the arguments to wildcard).
17404 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17405 ####
17407 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17408                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17410 ####
17411 # Third method: use an external program
17412 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17413 # This is the most complete command: it sets DIRs to the following value:
17414 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17415 ####
17417 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17418 @end example
17420 @node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
17421 @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}
17422 @subsection Generating the Command Line Switches
17425 Once you have created the list of directories as explained in the
17426 previous section (@ref{130,,Automatically Creating a List of Directories}),
17427 you can easily generate the command line arguments to pass to gnatmake.
17429 For the sake of completeness, this example assumes that the source path
17430 is not the same as the object path, and that you have two separate lists
17431 of directories.
17433 @example
17434 # see "Automatically creating a list of directories" to create
17435 # these variables
17436 SOURCE_DIRS=
17437 OBJECT_DIRS=
17439 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17440 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17442 all:
17443         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17444 @end example
17446 @node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
17447 @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}
17448 @subsection Overcoming Command Line Length Limits
17451 One problem that might be encountered on big projects is that many
17452 operating systems limit the length of the command line. It is thus hard to give
17453 gnatmake the list of source and object directories.
17455 This example shows how you can set up environment variables, which will
17456 make @code{gnatmake} behave exactly as if the directories had been
17457 specified on the command line, but have a much higher length limit (or
17458 even none on most systems).
17460 It assumes that you have created a list of directories in your Makefile,
17461 using one of the methods presented in
17462 @ref{130,,Automatically Creating a List of Directories}.
17463 For the sake of completeness, we assume that the object
17464 path (where the ALI files are found) is different from the sources patch.
17466 Note a small trick in the Makefile below: for efficiency reasons, we
17467 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17468 expanded immediately by @code{make}. This way we overcome the standard
17469 make behavior which is to expand the variables only when they are
17470 actually used.
17472 On Windows, if you are using the standard Windows command shell, you must
17473 replace colons with semicolons in the assignments to these variables.
17475 @example
17476 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17477 # This is the same thing as putting the -I arguments on the command line.
17478 # (the equivalent of using -aI on the command line would be to define
17479 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17480 # You can of course have different values for these variables.
17482 # Note also that we need to keep the previous values of these variables, since
17483 # they might have been set before running 'make' to specify where the GNAT
17484 # library is installed.
17486 # see "Automatically creating a list of directories" to create these
17487 # variables
17488 SOURCE_DIRS=
17489 OBJECT_DIRS=
17491 empty:=
17492 space:=$@{empty@} $@{empty@}
17493 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17494 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17495 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17496 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17497 export ADA_INCLUDE_PATH
17498 export ADA_OBJECTS_PATH
17500 all:
17501         gnatmake main_unit
17502 @end example
17504 @node GNAT Utility Programs,GNAT and Program Execution,Building Executable Programs with GNAT,Top
17505 @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}
17506 @chapter GNAT Utility Programs
17509 This chapter describes a number of utility programs:
17513 @itemize *
17515 @item 
17516 @ref{138,,The File Cleanup Utility gnatclean}
17518 @item 
17519 @ref{139,,The GNAT Library Browser gnatls}
17520 @end itemize
17522 Other GNAT utilities are described elsewhere in this manual:
17525 @itemize *
17527 @item 
17528 @ref{42,,Handling Arbitrary File Naming Conventions with gnatname}
17530 @item 
17531 @ref{4c,,File Name Krunching with gnatkr}
17533 @item 
17534 @ref{1d,,Renaming Files with gnatchop}
17536 @item 
17537 @ref{90,,Preprocessing with gnatprep}
17538 @end itemize
17540 @menu
17541 * The File Cleanup Utility gnatclean:: 
17542 * The GNAT Library Browser gnatls:: 
17544 @end menu
17546 @node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
17547 @anchor{gnat_ugn/gnat_utility_programs id2}@anchor{13a}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{138}
17548 @section The File Cleanup Utility @code{gnatclean}
17551 @geindex File cleanup tool
17553 @geindex gnatclean
17555 @code{gnatclean} is a tool that allows the deletion of files produced by the
17556 compiler, binder and linker, including ALI files, object files, tree files,
17557 expanded source files, library files, interface copy source files, binder
17558 generated files and executable files.
17560 @menu
17561 * Running gnatclean:: 
17562 * Switches for gnatclean:: 
17564 @end menu
17566 @node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
17567 @anchor{gnat_ugn/gnat_utility_programs id3}@anchor{13b}@anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{13c}
17568 @subsection Running @code{gnatclean}
17571 The @code{gnatclean} command has the form:
17573 @quotation
17575 @example
17576 $ gnatclean switches names
17577 @end example
17578 @end quotation
17580 where @code{names} is a list of source file names. Suffixes @code{.ads} and
17581 @code{adb} may be omitted. If a project file is specified using switch
17582 @code{-P}, then @code{names} may be completely omitted.
17584 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17585 if switch @code{-c} is not specified, by the binder and
17586 the linker. In informative-only mode, specified by switch
17587 @code{-n}, the list of files that would have been deleted in
17588 normal mode is listed, but no file is actually deleted.
17590 @node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
17591 @anchor{gnat_ugn/gnat_utility_programs id4}@anchor{13d}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{13e}
17592 @subsection Switches for @code{gnatclean}
17595 @code{gnatclean} recognizes the following switches:
17597 @geindex --version (gnatclean)
17600 @table @asis
17602 @item @code{--version}
17604 Display copyright and version, then exit disregarding all other options.
17605 @end table
17607 @geindex --help (gnatclean)
17610 @table @asis
17612 @item @code{--help}
17614 If @code{--version} was not used, display usage, then exit disregarding
17615 all other options.
17617 @item @code{--subdirs=@emph{subdir}}
17619 Actual object directory of each project file is the subdirectory subdir of the
17620 object directory specified or defaulted in the project file.
17622 @item @code{--unchecked-shared-lib-imports}
17624 By default, shared library projects are not allowed to import static library
17625 projects. When this switch is used on the command line, this restriction is
17626 relaxed.
17627 @end table
17629 @geindex -c (gnatclean)
17632 @table @asis
17634 @item @code{-c}
17636 Only attempt to delete the files produced by the compiler, not those produced
17637 by the binder or the linker. The files that are not to be deleted are library
17638 files, interface copy files, binder generated files and executable files.
17639 @end table
17641 @geindex -D (gnatclean)
17644 @table @asis
17646 @item @code{-D @emph{dir}}
17648 Indicate that ALI and object files should normally be found in directory @code{dir}.
17649 @end table
17651 @geindex -F (gnatclean)
17654 @table @asis
17656 @item @code{-F}
17658 When using project files, if some errors or warnings are detected during
17659 parsing and verbose mode is not in effect (no use of switch
17660 -v), then error lines start with the full path name of the project
17661 file, rather than its simple file name.
17662 @end table
17664 @geindex -h (gnatclean)
17667 @table @asis
17669 @item @code{-h}
17671 Output a message explaining the usage of @code{gnatclean}.
17672 @end table
17674 @geindex -n (gnatclean)
17677 @table @asis
17679 @item @code{-n}
17681 Informative-only mode. Do not delete any files. Output the list of the files
17682 that would have been deleted if this switch was not specified.
17683 @end table
17685 @geindex -P (gnatclean)
17688 @table @asis
17690 @item @code{-P@emph{project}}
17692 Use project file @code{project}. Only one such switch can be used.
17693 When cleaning a project file, the files produced by the compilation of the
17694 immediate sources or inherited sources of the project files are to be
17695 deleted. This is not depending on the presence or not of executable names
17696 on the command line.
17697 @end table
17699 @geindex -q (gnatclean)
17702 @table @asis
17704 @item @code{-q}
17706 Quiet output. If there are no errors, do not output anything, except in
17707 verbose mode (switch -v) or in informative-only mode
17708 (switch -n).
17709 @end table
17711 @geindex -r (gnatclean)
17714 @table @asis
17716 @item @code{-r}
17718 When a project file is specified (using switch -P),
17719 clean all imported and extended project files, recursively. If this switch
17720 is not specified, only the files related to the main project file are to be
17721 deleted. This switch has no effect if no project file is specified.
17722 @end table
17724 @geindex -v (gnatclean)
17727 @table @asis
17729 @item @code{-v}
17731 Verbose mode.
17732 @end table
17734 @geindex -vP (gnatclean)
17737 @table @asis
17739 @item @code{-vP@emph{x}}
17741 Indicates the verbosity of the parsing of GNAT project files.
17742 @ref{d1,,Switches Related to Project Files}.
17743 @end table
17745 @geindex -X (gnatclean)
17748 @table @asis
17750 @item @code{-X@emph{name}=@emph{value}}
17752 Indicates that external variable @code{name} has the value @code{value}.
17753 The Project Manager will use this value for occurrences of
17754 @code{external(name)} when parsing the project file.
17755 See @ref{d1,,Switches Related to Project Files}.
17756 @end table
17758 @geindex -aO (gnatclean)
17761 @table @asis
17763 @item @code{-aO@emph{dir}}
17765 When searching for ALI and object files, look in directory @code{dir}.
17766 @end table
17768 @geindex -I (gnatclean)
17771 @table @asis
17773 @item @code{-I@emph{dir}}
17775 Equivalent to @code{-aO@emph{dir}}.
17776 @end table
17778 @geindex -I- (gnatclean)
17780 @geindex Source files
17781 @geindex suppressing search
17784 @table @asis
17786 @item @code{-I-}
17788 Do not look for ALI or object files in the directory
17789 where @code{gnatclean} was invoked.
17790 @end table
17792 @node The GNAT Library Browser gnatls,,The File Cleanup Utility gnatclean,GNAT Utility Programs
17793 @anchor{gnat_ugn/gnat_utility_programs id5}@anchor{13f}@anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{139}
17794 @section The GNAT Library Browser @code{gnatls}
17797 @geindex Library browser
17799 @geindex gnatls
17801 @code{gnatls} is a tool that outputs information about compiled
17802 units. It gives the relationship between objects, unit names and source
17803 files. It can also be used to check the source dependencies of a unit
17804 as well as various characteristics.
17806 @menu
17807 * Running gnatls:: 
17808 * Switches for gnatls:: 
17809 * Example of gnatls Usage:: 
17811 @end menu
17813 @node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
17814 @anchor{gnat_ugn/gnat_utility_programs id6}@anchor{140}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{141}
17815 @subsection Running @code{gnatls}
17818 The @code{gnatls} command has the form
17820 @quotation
17822 @example
17823 $ gnatls switches object_or_ali_file
17824 @end example
17825 @end quotation
17827 The main argument is the list of object or @code{ali} files
17828 (see @ref{28,,The Ada Library Information Files})
17829 for which information is requested.
17831 In normal mode, without additional option, @code{gnatls} produces a
17832 four-column listing. Each line represents information for a specific
17833 object. The first column gives the full path of the object, the second
17834 column gives the name of the principal unit in this object, the third
17835 column gives the status of the source and the fourth column gives the
17836 full path of the source representing this unit.
17837 Here is a simple example of use:
17839 @quotation
17841 @example
17842 $ gnatls *.o
17843 ./demo1.o            demo1            DIF demo1.adb
17844 ./demo2.o            demo2             OK demo2.adb
17845 ./hello.o            h1                OK hello.adb
17846 ./instr-child.o      instr.child      MOK instr-child.adb
17847 ./instr.o            instr             OK instr.adb
17848 ./tef.o              tef              DIF tef.adb
17849 ./text_io_example.o  text_io_example   OK text_io_example.adb
17850 ./tgef.o             tgef             DIF tgef.adb
17851 @end example
17852 @end quotation
17854 The first line can be interpreted as follows: the main unit which is
17855 contained in
17856 object file @code{demo1.o} is demo1, whose main source is in
17857 @code{demo1.adb}. Furthermore, the version of the source used for the
17858 compilation of demo1 has been modified (DIF). Each source file has a status
17859 qualifier which can be:
17862 @table @asis
17864 @item @emph{OK (unchanged)}
17866 The version of the source file used for the compilation of the
17867 specified unit corresponds exactly to the actual source file.
17869 @item @emph{MOK (slightly modified)}
17871 The version of the source file used for the compilation of the
17872 specified unit differs from the actual source file but not enough to
17873 require recompilation. If you use gnatmake with the option
17874 @code{-m} (minimal recompilation), a file marked
17875 MOK will not be recompiled.
17877 @item @emph{DIF (modified)}
17879 No version of the source found on the path corresponds to the source
17880 used to build this object.
17882 @item @emph{??? (file not found)}
17884 No source file was found for this unit.
17886 @item @emph{HID (hidden,  unchanged version not first on PATH)}
17888 The version of the source that corresponds exactly to the source used
17889 for compilation has been found on the path but it is hidden by another
17890 version of the same source that has been modified.
17891 @end table
17893 @node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
17894 @anchor{gnat_ugn/gnat_utility_programs id7}@anchor{142}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{143}
17895 @subsection Switches for @code{gnatls}
17898 @code{gnatls} recognizes the following switches:
17900 @geindex --version (gnatls)
17903 @table @asis
17905 @item @code{--version}
17907 Display copyright and version, then exit disregarding all other options.
17908 @end table
17910 @geindex --help (gnatls)
17913 @table @asis
17915 @item @code{--help}
17917 If @code{--version} was not used, display usage, then exit disregarding
17918 all other options.
17919 @end table
17921 @geindex -a (gnatls)
17924 @table @asis
17926 @item @code{-a}
17928 Consider all units, including those of the predefined Ada library.
17929 Especially useful with @code{-d}.
17930 @end table
17932 @geindex -d (gnatls)
17935 @table @asis
17937 @item @code{-d}
17939 List sources from which specified units depend on.
17940 @end table
17942 @geindex -h (gnatls)
17945 @table @asis
17947 @item @code{-h}
17949 Output the list of options.
17950 @end table
17952 @geindex -o (gnatls)
17955 @table @asis
17957 @item @code{-o}
17959 Only output information about object files.
17960 @end table
17962 @geindex -s (gnatls)
17965 @table @asis
17967 @item @code{-s}
17969 Only output information about source files.
17970 @end table
17972 @geindex -u (gnatls)
17975 @table @asis
17977 @item @code{-u}
17979 Only output information about compilation units.
17980 @end table
17982 @geindex -files (gnatls)
17985 @table @asis
17987 @item @code{-files=@emph{file}}
17989 Take as arguments the files listed in text file @code{file}.
17990 Text file @code{file} may contain empty lines that are ignored.
17991 Each nonempty line should contain the name of an existing file.
17992 Several such switches may be specified simultaneously.
17993 @end table
17995 @geindex -aO (gnatls)
17997 @geindex -aI (gnatls)
17999 @geindex -I (gnatls)
18001 @geindex -I- (gnatls)
18004 @table @asis
18006 @item @code{-aO@emph{dir}}, @code{-aI@emph{dir}}, @code{-I@emph{dir}}, @code{-I-}, @code{-nostdinc}
18008 Source path manipulation. Same meaning as the equivalent @code{gnatmake}
18009 flags (@ref{d0,,Switches for gnatmake}).
18010 @end table
18012 @geindex -aP (gnatls)
18015 @table @asis
18017 @item @code{-aP@emph{dir}}
18019 Add @code{dir} at the beginning of the project search dir.
18020 @end table
18022 @geindex --RTS (gnatls)
18025 @table @asis
18027 @item @code{--RTS=@emph{rts-path}}
18029 Specifies the default location of the runtime library. Same meaning as the
18030 equivalent @code{gnatmake} flag (@ref{d0,,Switches for gnatmake}).
18031 @end table
18033 @geindex -v (gnatls)
18036 @table @asis
18038 @item @code{-v}
18040 Verbose mode. Output the complete source, object and project paths. Do not use
18041 the default column layout but instead use long format giving as much as
18042 information possible on each requested units, including special
18043 characteristics such as:
18046 @itemize *
18048 @item 
18049 @emph{Preelaborable}: The unit is preelaborable in the Ada sense.
18051 @item 
18052 @emph{No_Elab_Code}:  No elaboration code has been produced by the compiler for this unit.
18054 @item 
18055 @emph{Pure}: The unit is pure in the Ada sense.
18057 @item 
18058 @emph{Elaborate_Body}: The unit contains a pragma Elaborate_Body.
18060 @item 
18061 @emph{Remote_Types}: The unit contains a pragma Remote_Types.
18063 @item 
18064 @emph{Shared_Passive}: The unit contains a pragma Shared_Passive.
18066 @item 
18067 @emph{Predefined}: This unit is part of the predefined environment and cannot be modified
18068 by the user.
18070 @item 
18071 @emph{Remote_Call_Interface}: The unit contains a pragma Remote_Call_Interface.
18072 @end itemize
18073 @end table
18075 @node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
18076 @anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{144}@anchor{gnat_ugn/gnat_utility_programs id8}@anchor{145}
18077 @subsection Example of @code{gnatls} Usage
18080 Example of using the verbose switch. Note how the source and
18081 object paths are affected by the -I switch.
18083 @quotation
18085 @example
18086 $ gnatls -v -I.. demo1.o
18088 GNATLS 5.03w (20041123-34)
18089 Copyright 1997-2004 Free Software Foundation, Inc.
18091 Source Search Path:
18092    <Current_Directory>
18093    ../
18094    /home/comar/local/adainclude/
18096 Object Search Path:
18097    <Current_Directory>
18098    ../
18099    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18101 Project Search Path:
18102    <Current_Directory>
18103    /home/comar/local/lib/gnat/
18105 ./demo1.o
18106    Unit =>
18107      Name   => demo1
18108      Kind   => subprogram body
18109      Flags  => No_Elab_Code
18110      Source => demo1.adb    modified
18111 @end example
18112 @end quotation
18114 The following is an example of use of the dependency list.
18115 Note the use of the -s switch
18116 which gives a straight list of source files. This can be useful for
18117 building specialized scripts.
18119 @quotation
18121 @example
18122 $ gnatls -d demo2.o
18123 ./demo2.o   demo2        OK demo2.adb
18124                          OK gen_list.ads
18125                          OK gen_list.adb
18126                          OK instr.ads
18127                          OK instr-child.ads
18129 $ gnatls -d -s -a demo1.o
18130 demo1.adb
18131 /home/comar/local/adainclude/ada.ads
18132 /home/comar/local/adainclude/a-finali.ads
18133 /home/comar/local/adainclude/a-filico.ads
18134 /home/comar/local/adainclude/a-stream.ads
18135 /home/comar/local/adainclude/a-tags.ads
18136 gen_list.ads
18137 gen_list.adb
18138 /home/comar/local/adainclude/gnat.ads
18139 /home/comar/local/adainclude/g-io.ads
18140 instr.ads
18141 /home/comar/local/adainclude/system.ads
18142 /home/comar/local/adainclude/s-exctab.ads
18143 /home/comar/local/adainclude/s-finimp.ads
18144 /home/comar/local/adainclude/s-finroo.ads
18145 /home/comar/local/adainclude/s-secsta.ads
18146 /home/comar/local/adainclude/s-stalib.ads
18147 /home/comar/local/adainclude/s-stoele.ads
18148 /home/comar/local/adainclude/s-stratt.ads
18149 /home/comar/local/adainclude/s-tasoli.ads
18150 /home/comar/local/adainclude/s-unstyp.ads
18151 /home/comar/local/adainclude/unchconv.ads
18152 @end example
18153 @end quotation
18159 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
18161 @node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
18162 @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}
18163 @chapter GNAT and Program Execution
18166 This chapter covers several topics:
18169 @itemize *
18171 @item 
18172 @ref{148,,Running and Debugging Ada Programs}
18174 @item 
18175 @ref{149,,Profiling}
18177 @item 
18178 @ref{14a,,Improving Performance}
18180 @item 
18181 @ref{14b,,Overflow Check Handling in GNAT}
18183 @item 
18184 @ref{14c,,Performing Dimensionality Analysis in GNAT}
18186 @item 
18187 @ref{14d,,Stack Related Facilities}
18189 @item 
18190 @ref{14e,,Memory Management Issues}
18191 @end itemize
18193 @menu
18194 * Running and Debugging Ada Programs:: 
18195 * Profiling:: 
18196 * Improving Performance:: 
18197 * Overflow Check Handling in GNAT:: 
18198 * Performing Dimensionality Analysis in GNAT:: 
18199 * Stack Related Facilities:: 
18200 * Memory Management Issues:: 
18202 @end menu
18204 @node Running and Debugging Ada Programs,Profiling,,GNAT and Program Execution
18205 @anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{148}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{14f}
18206 @section Running and Debugging Ada Programs
18209 @geindex Debugging
18211 This section discusses how to debug Ada programs.
18213 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18216 @itemize *
18218 @item 
18219 The illegality may be a violation of the static semantics of Ada. In
18220 that case GNAT diagnoses the constructs in the program that are illegal.
18221 It is then a straightforward matter for the user to modify those parts of
18222 the program.
18224 @item 
18225 The illegality may be a violation of the dynamic semantics of Ada. In
18226 that case the program compiles and executes, but may generate incorrect
18227 results, or may terminate abnormally with some exception.
18229 @item 
18230 When presented with a program that contains convoluted errors, GNAT
18231 itself may terminate abnormally without providing full diagnostics on
18232 the incorrect user program.
18233 @end itemize
18235 @geindex Debugger
18237 @geindex gdb
18239 @menu
18240 * The GNAT Debugger GDB:: 
18241 * Running GDB:: 
18242 * Introduction to GDB Commands:: 
18243 * Using Ada Expressions:: 
18244 * Calling User-Defined Subprograms:: 
18245 * Using the next Command in a Function:: 
18246 * Stopping When Ada Exceptions Are Raised:: 
18247 * Ada Tasks:: 
18248 * Debugging Generic Units:: 
18249 * Remote Debugging with gdbserver:: 
18250 * GNAT Abnormal Termination or Failure to Terminate:: 
18251 * Naming Conventions for GNAT Source Files:: 
18252 * Getting Internal Debugging Information:: 
18253 * Stack Traceback:: 
18254 * Pretty-Printers for the GNAT runtime:: 
18256 @end menu
18258 @node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
18259 @anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{150}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{151}
18260 @subsection The GNAT Debugger GDB
18263 @code{GDB} is a general purpose, platform-independent debugger that
18264 can be used to debug mixed-language programs compiled with @code{gcc},
18265 and in particular is capable of debugging Ada programs compiled with
18266 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18267 complex Ada data structures.
18269 See @cite{Debugging with GDB},
18270 for full details on the usage of @code{GDB}, including a section on
18271 its usage on programs. This manual should be consulted for full
18272 details. The section that follows is a brief introduction to the
18273 philosophy and use of @code{GDB}.
18275 When GNAT programs are compiled, the compiler optionally writes debugging
18276 information into the generated object file, including information on
18277 line numbers, and on declared types and variables. This information is
18278 separate from the generated code. It makes the object files considerably
18279 larger, but it does not add to the size of the actual executable that
18280 will be loaded into memory, and has no impact on run-time performance. The
18281 generation of debug information is triggered by the use of the
18282 @code{-g} switch in the @code{gcc} or @code{gnatmake} command
18283 used to carry out the compilations. It is important to emphasize that
18284 the use of these options does not change the generated code.
18286 The debugging information is written in standard system formats that
18287 are used by many tools, including debuggers and profilers. The format
18288 of the information is typically designed to describe C types and
18289 semantics, but GNAT implements a translation scheme which allows full
18290 details about Ada types and variables to be encoded into these
18291 standard C formats. Details of this encoding scheme may be found in
18292 the file exp_dbug.ads in the GNAT source distribution. However, the
18293 details of this encoding are, in general, of no interest to a user,
18294 since @code{GDB} automatically performs the necessary decoding.
18296 When a program is bound and linked, the debugging information is
18297 collected from the object files, and stored in the executable image of
18298 the program. Again, this process significantly increases the size of
18299 the generated executable file, but it does not increase the size of
18300 the executable program itself. Furthermore, if this program is run in
18301 the normal manner, it runs exactly as if the debug information were
18302 not present, and takes no more actual memory.
18304 However, if the program is run under control of @code{GDB}, the
18305 debugger is activated.  The image of the program is loaded, at which
18306 point it is ready to run.  If a run command is given, then the program
18307 will run exactly as it would have if @code{GDB} were not present. This
18308 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18309 entirely non-intrusive until a breakpoint is encountered.  If no
18310 breakpoint is ever hit, the program will run exactly as it would if no
18311 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18312 the debugging information and can respond to user commands to inspect
18313 variables, and more generally to report on the state of execution.
18315 @node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
18316 @anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{152}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{153}
18317 @subsection Running GDB
18320 This section describes how to initiate the debugger.
18322 The debugger can be launched from a @code{GNAT Studio} menu or
18323 directly from the command line. The description below covers the latter use.
18324 All the commands shown can be used in the @code{GNAT Studio} debug console window,
18325 but there are usually more GUI-based ways to achieve the same effect.
18327 The command to run @code{GDB} is
18329 @quotation
18331 @example
18332 $ gdb program
18333 @end example
18334 @end quotation
18336 where @code{program} is the name of the executable file. This
18337 activates the debugger and results in a prompt for debugger commands.
18338 The simplest command is simply @code{run}, which causes the program to run
18339 exactly as if the debugger were not present. The following section
18340 describes some of the additional commands that can be given to @code{GDB}.
18342 @node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
18343 @anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{154}@anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{155}
18344 @subsection Introduction to GDB Commands
18347 @code{GDB} contains a large repertoire of commands.
18348 See @cite{Debugging with GDB} for extensive documentation on the use
18349 of these commands, together with examples of their use. Furthermore,
18350 the command @emph{help} invoked from within GDB activates a simple help
18351 facility which summarizes the available commands and their options.
18352 In this section we summarize a few of the most commonly
18353 used commands to give an idea of what @code{GDB} is about. You should create
18354 a simple program with debugging information and experiment with the use of
18355 these @code{GDB} commands on the program as you read through the
18356 following section.
18359 @itemize *
18361 @item 
18363 @table @asis
18365 @item @code{set args @emph{arguments}}
18367 The @emph{arguments} list above is a list of arguments to be passed to
18368 the program on a subsequent run command, just as though the arguments
18369 had been entered on a normal invocation of the program. The @code{set args}
18370 command is not needed if the program does not require arguments.
18371 @end table
18373 @item 
18375 @table @asis
18377 @item @code{run}
18379 The @code{run} command causes execution of the program to start from
18380 the beginning. If the program is already running, that is to say if
18381 you are currently positioned at a breakpoint, then a prompt will ask
18382 for confirmation that you want to abandon the current execution and
18383 restart.
18384 @end table
18386 @item 
18388 @table @asis
18390 @item @code{breakpoint @emph{location}}
18392 The breakpoint command sets a breakpoint, that is to say a point at which
18393 execution will halt and @code{GDB} will await further
18394 commands. @emph{location} is
18395 either a line number within a file, given in the format @code{file:linenumber},
18396 or it is the name of a subprogram. If you request that a breakpoint be set on
18397 a subprogram that is overloaded, a prompt will ask you to specify on which of
18398 those subprograms you want to breakpoint. You can also
18399 specify that all of them should be breakpointed. If the program is run
18400 and execution encounters the breakpoint, then the program
18401 stops and @code{GDB} signals that the breakpoint was encountered by
18402 printing the line of code before which the program is halted.
18403 @end table
18405 @item 
18407 @table @asis
18409 @item @code{catch exception @emph{name}}
18411 This command causes the program execution to stop whenever exception
18412 @code{name} is raised.  If @code{name} is omitted, then the execution is
18413 suspended when any exception is raised.
18414 @end table
18416 @item 
18418 @table @asis
18420 @item @code{print @emph{expression}}
18422 This will print the value of the given expression. Most simple
18423 Ada expression formats are properly handled by @code{GDB}, so the expression
18424 can contain function calls, variables, operators, and attribute references.
18425 @end table
18427 @item 
18429 @table @asis
18431 @item @code{continue}
18433 Continues execution following a breakpoint, until the next breakpoint or the
18434 termination of the program.
18435 @end table
18437 @item 
18439 @table @asis
18441 @item @code{step}
18443 Executes a single line after a breakpoint. If the next statement
18444 is a subprogram call, execution continues into (the first statement of)
18445 the called subprogram.
18446 @end table
18448 @item 
18450 @table @asis
18452 @item @code{next}
18454 Executes a single line. If this line is a subprogram call, executes and
18455 returns from the call.
18456 @end table
18458 @item 
18460 @table @asis
18462 @item @code{list}
18464 Lists a few lines around the current source location. In practice, it
18465 is usually more convenient to have a separate edit window open with the
18466 relevant source file displayed. Successive applications of this command
18467 print subsequent lines. The command can be given an argument which is a
18468 line number, in which case it displays a few lines around the specified one.
18469 @end table
18471 @item 
18473 @table @asis
18475 @item @code{backtrace}
18477 Displays a backtrace of the call chain. This command is typically
18478 used after a breakpoint has occurred, to examine the sequence of calls that
18479 leads to the current breakpoint. The display includes one line for each
18480 activation record (frame) corresponding to an active subprogram.
18481 @end table
18483 @item 
18485 @table @asis
18487 @item @code{up}
18489 At a breakpoint, @code{GDB} can display the values of variables local
18490 to the current frame. The command @code{up} can be used to
18491 examine the contents of other active frames, by moving the focus up
18492 the stack, that is to say from callee to caller, one frame at a time.
18493 @end table
18495 @item 
18497 @table @asis
18499 @item @code{down}
18501 Moves the focus of @code{GDB} down from the frame currently being
18502 examined to the frame of its callee (the reverse of the previous command),
18503 @end table
18505 @item 
18507 @table @asis
18509 @item @code{frame @emph{n}}
18511 Inspect the frame with the given number. The value 0 denotes the frame
18512 of the current breakpoint, that is to say the top of the call stack.
18513 @end table
18515 @item 
18517 @table @asis
18519 @item @code{kill}
18521 Kills the child process in which the program is running under GDB.
18522 This may be useful for several purposes:
18525 @itemize *
18527 @item 
18528 It allows you to recompile and relink your program, since on many systems
18529 you cannot regenerate an executable file while it is running in a process.
18531 @item 
18532 You can run your program outside the debugger, on systems that do not
18533 permit executing a program outside GDB while breakpoints are set
18534 within GDB.
18536 @item 
18537 It allows you to debug a core dump rather than a running process.
18538 @end itemize
18539 @end table
18540 @end itemize
18542 The above list is a very short introduction to the commands that
18543 @code{GDB} provides. Important additional capabilities, including conditional
18544 breakpoints, the ability to execute command sequences on a breakpoint,
18545 the ability to debug at the machine instruction level and many other
18546 features are described in detail in @cite{Debugging with GDB}.
18547 Note that most commands can be abbreviated
18548 (for example, c for continue, bt for backtrace).
18550 @node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
18551 @anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{156}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{157}
18552 @subsection Using Ada Expressions
18555 @geindex Ada expressions (in gdb)
18557 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18558 extensions. The philosophy behind the design of this subset is
18560 @quotation
18563 @itemize *
18565 @item 
18566 That @code{GDB} should provide basic literals and access to operations for
18567 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18568 leaving more sophisticated computations to subprograms written into the
18569 program (which therefore may be called from @code{GDB}).
18571 @item 
18572 That type safety and strict adherence to Ada language restrictions
18573 are not particularly relevant in a debugging context.
18575 @item 
18576 That brevity is important to the @code{GDB} user.
18577 @end itemize
18578 @end quotation
18580 Thus, for brevity, the debugger acts as if there were
18581 implicit @code{with} and @code{use} clauses in effect for all user-written
18582 packages, thus making it unnecessary to fully qualify most names with
18583 their packages, regardless of context. Where this causes ambiguity,
18584 @code{GDB} asks the user’s intent.
18586 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
18588 @node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
18589 @anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{158}@anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{159}
18590 @subsection Calling User-Defined Subprograms
18593 An important capability of @code{GDB} is the ability to call user-defined
18594 subprograms while debugging. This is achieved simply by entering
18595 a subprogram call statement in the form:
18597 @quotation
18599 @example
18600 call subprogram-name (parameters)
18601 @end example
18602 @end quotation
18604 The keyword @code{call} can be omitted in the normal case where the
18605 @code{subprogram-name} does not coincide with any of the predefined
18606 @code{GDB} commands.
18608 The effect is to invoke the given subprogram, passing it the
18609 list of parameters that is supplied. The parameters can be expressions and
18610 can include variables from the program being debugged. The
18611 subprogram must be defined
18612 at the library level within your program, and @code{GDB} will call the
18613 subprogram within the environment of your program execution (which
18614 means that the subprogram is free to access or even modify variables
18615 within your program).
18617 The most important use of this facility is in allowing the inclusion of
18618 debugging routines that are tailored to particular data structures
18619 in your program. Such debugging routines can be written to provide a suitably
18620 high-level description of an abstract type, rather than a low-level dump
18621 of its physical layout. After all, the standard
18622 @code{GDB print} command only knows the physical layout of your
18623 types, not their abstract meaning. Debugging routines can provide information
18624 at the desired semantic level and are thus enormously useful.
18626 For example, when debugging GNAT itself, it is crucial to have access to
18627 the contents of the tree nodes used to represent the program internally.
18628 But tree nodes are represented simply by an integer value (which in turn
18629 is an index into a table of nodes).
18630 Using the @code{print} command on a tree node would simply print this integer
18631 value, which is not very useful. But the PN routine (defined in file
18632 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18633 a useful high level representation of the tree node, which includes the
18634 syntactic category of the node, its position in the source, the integers
18635 that denote descendant nodes and parent node, as well as varied
18636 semantic information. To study this example in more detail, you might want to
18637 look at the body of the PN procedure in the stated file.
18639 Another useful application of this capability is to deal with situations of
18640 complex data which are not handled suitably by GDB. For example, if you specify
18641 Convention Fortran for a multi-dimensional array, GDB does not know that
18642 the ordering of array elements has been switched and will not properly
18643 address the array elements. In such a case, instead of trying to print the
18644 elements directly from GDB, you can write a callable procedure that prints
18645 the elements in the desired format.
18647 @node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
18648 @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}
18649 @subsection Using the @emph{next} Command in a Function
18652 When you use the @code{next} command in a function, the current source
18653 location will advance to the next statement as usual. A special case
18654 arises in the case of a @code{return} statement.
18656 Part of the code for a return statement is the ‘epilogue’ of the function.
18657 This is the code that returns to the caller. There is only one copy of
18658 this epilogue code, and it is typically associated with the last return
18659 statement in the function if there is more than one return. In some
18660 implementations, this epilogue is associated with the first statement
18661 of the function.
18663 The result is that if you use the @code{next} command from a return
18664 statement that is not the last return statement of the function you
18665 may see a strange apparent jump to the last return statement or to
18666 the start of the function. You should simply ignore this odd jump.
18667 The value returned is always that from the first return statement
18668 that was stepped through.
18670 @node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
18671 @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}
18672 @subsection Stopping When Ada Exceptions Are Raised
18675 @geindex Exceptions (in gdb)
18677 You can set catchpoints that stop the program execution when your program
18678 raises selected exceptions.
18681 @itemize *
18683 @item 
18685 @table @asis
18687 @item @code{catch exception}
18689 Set a catchpoint that stops execution whenever (any task in the) program
18690 raises any exception.
18691 @end table
18693 @item 
18695 @table @asis
18697 @item @code{catch exception @emph{name}}
18699 Set a catchpoint that stops execution whenever (any task in the) program
18700 raises the exception @emph{name}.
18701 @end table
18703 @item 
18705 @table @asis
18707 @item @code{catch exception unhandled}
18709 Set a catchpoint that stops executing whenever (any task in the) program
18710 raises an exception for which there is no handler.
18711 @end table
18713 @item 
18715 @table @asis
18717 @item @code{info exceptions}, @code{info exceptions @emph{regexp}}
18719 The @code{info exceptions} command permits the user to examine all defined
18720 exceptions within Ada programs. With a regular expression, @emph{regexp}, as
18721 argument, prints out only those exceptions whose name matches @emph{regexp}.
18722 @end table
18723 @end itemize
18725 @geindex Tasks (in gdb)
18727 @node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
18728 @anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{15e}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{15f}
18729 @subsection Ada Tasks
18732 @code{GDB} allows the following task-related commands:
18735 @itemize *
18737 @item 
18739 @table @asis
18741 @item @code{info tasks}
18743 This command shows a list of current Ada tasks, as in the following example:
18745 @example
18746 (gdb) info tasks
18747   ID       TID P-ID   Thread Pri State                 Name
18748    1   8088000   0   807e000  15 Child Activation Wait main_task
18749    2   80a4000   1   80ae000  15 Accept/Select Wait    b
18750    3   809a800   1   80a4800  15 Child Activation Wait a
18751 *  4   80ae800   3   80b8000  15 Running               c
18752 @end example
18754 In this listing, the asterisk before the first task indicates it to be the
18755 currently running task. The first column lists the task ID that is used
18756 to refer to tasks in the following commands.
18757 @end table
18758 @end itemize
18760 @geindex Breakpoints and tasks
18763 @itemize *
18765 @item 
18766 @code{break} @emph{linespec} @code{task} @emph{taskid}, @code{break} @emph{linespec} @code{task} @emph{taskid} @code{if} …
18768 @quotation
18770 These commands are like the @code{break ... thread ...}.
18771 @emph{linespec} specifies source lines.
18773 Use the qualifier @code{task @emph{taskid}} with a breakpoint command
18774 to specify that you only want @code{GDB} to stop the program when a
18775 particular Ada task reaches this breakpoint. @emph{taskid} is one of the
18776 numeric task identifiers assigned by @code{GDB}, shown in the first
18777 column of the @code{info tasks} display.
18779 If you do not specify @code{task @emph{taskid}} when you set a
18780 breakpoint, the breakpoint applies to @emph{all} tasks of your
18781 program.
18783 You can use the @code{task} qualifier on conditional breakpoints as
18784 well; in this case, place @code{task @emph{taskid}} before the
18785 breakpoint condition (before the @code{if}).
18786 @end quotation
18787 @end itemize
18789 @geindex Task switching (in gdb)
18792 @itemize *
18794 @item 
18795 @code{task @emph{taskno}}
18797 @quotation
18799 This command allows switching to the task referred by @emph{taskno}. In
18800 particular, this allows browsing of the backtrace of the specified
18801 task. It is advisable to switch back to the original task before
18802 continuing execution otherwise the scheduling of the program may be
18803 perturbed.
18804 @end quotation
18805 @end itemize
18807 For more detailed information on the tasking support,
18808 see @cite{Debugging with GDB}.
18810 @geindex Debugging Generic Units
18812 @geindex Generics
18814 @node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
18815 @anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{160}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{161}
18816 @subsection Debugging Generic Units
18819 GNAT always uses code expansion for generic instantiation. This means that
18820 each time an instantiation occurs, a complete copy of the original code is
18821 made, with appropriate substitutions of formals by actuals.
18823 It is not possible to refer to the original generic entities in
18824 @code{GDB}, but it is always possible to debug a particular instance of
18825 a generic, by using the appropriate expanded names. For example, if we have
18827 @quotation
18829 @example
18830 procedure g is
18832    generic package k is
18833       procedure kp (v1 : in out integer);
18834    end k;
18836    package body k is
18837       procedure kp (v1 : in out integer) is
18838       begin
18839          v1 := v1 + 1;
18840       end kp;
18841    end k;
18843    package k1 is new k;
18844    package k2 is new k;
18846    var : integer := 1;
18848 begin
18849    k1.kp (var);
18850    k2.kp (var);
18851    k1.kp (var);
18852    k2.kp (var);
18853 end;
18854 @end example
18855 @end quotation
18857 Then to break on a call to procedure kp in the k2 instance, simply
18858 use the command:
18860 @quotation
18862 @example
18863 (gdb) break g.k2.kp
18864 @end example
18865 @end quotation
18867 When the breakpoint occurs, you can step through the code of the
18868 instance in the normal manner and examine the values of local variables, as for
18869 other units.
18871 @geindex Remote Debugging with gdbserver
18873 @node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
18874 @anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{162}@anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{163}
18875 @subsection Remote Debugging with gdbserver
18878 On platforms where gdbserver is supported, it is possible to use this tool
18879 to debug your application remotely.  This can be useful in situations
18880 where the program needs to be run on a target host that is different
18881 from the host used for development, particularly when the target has
18882 a limited amount of resources (either CPU and/or memory).
18884 To do so, start your program using gdbserver on the target machine.
18885 gdbserver then automatically suspends the execution of your program
18886 at its entry point, waiting for a debugger to connect to it.  The
18887 following commands starts an application and tells gdbserver to
18888 wait for a connection with the debugger on localhost port 4444.
18890 @quotation
18892 @example
18893 $ gdbserver localhost:4444 program
18894 Process program created; pid = 5685
18895 Listening on port 4444
18896 @end example
18897 @end quotation
18899 Once gdbserver has started listening, we can tell the debugger to establish
18900 a connection with this gdbserver, and then start the same debugging session
18901 as if the program was being debugged on the same host, directly under
18902 the control of GDB.
18904 @quotation
18906 @example
18907 $ gdb program
18908 (gdb) target remote targethost:4444
18909 Remote debugging using targethost:4444
18910 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
18911 (gdb) b foo.adb:3
18912 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
18913 (gdb) continue
18914 Continuing.
18916 Breakpoint 1, foo () at foo.adb:4
18917 4       end foo;
18918 @end example
18919 @end quotation
18921 It is also possible to use gdbserver to attach to an already running
18922 program, in which case the execution of that program is simply suspended
18923 until the connection between the debugger and gdbserver is established.
18925 For more information on how to use gdbserver, see the @emph{Using the gdbserver Program}
18926 section in @cite{Debugging with GDB}.
18927 GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
18929 @geindex Abnormal Termination or Failure to Terminate
18931 @node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
18932 @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}
18933 @subsection GNAT Abnormal Termination or Failure to Terminate
18936 When presented with programs that contain serious errors in syntax
18937 or semantics,
18938 GNAT may on rare occasions  experience problems in operation, such
18939 as aborting with a
18940 segmentation fault or illegal memory access, raising an internal
18941 exception, terminating abnormally, or failing to terminate at all.
18942 In such cases, you can activate
18943 various features of GNAT that can help you pinpoint the construct in your
18944 program that is the likely source of the problem.
18946 The following strategies are presented in increasing order of
18947 difficulty, corresponding to your experience in using GNAT and your
18948 familiarity with compiler internals.
18951 @itemize *
18953 @item 
18954 Run @code{gcc} with the @code{-gnatf}. This first
18955 switch causes all errors on a given line to be reported. In its absence,
18956 only the first error on a line is displayed.
18958 The @code{-gnatdO} switch causes errors to be displayed as soon as they
18959 are encountered, rather than after compilation is terminated. If GNAT
18960 terminates prematurely or goes into an infinite loop, the last error
18961 message displayed may help to pinpoint the culprit.
18963 @item 
18964 Run @code{gcc} with the @code{-v} (verbose) switch. In this
18965 mode, @code{gcc} produces ongoing information about the progress of the
18966 compilation and provides the name of each procedure as code is
18967 generated. This switch allows you to find which Ada procedure was being
18968 compiled when it encountered a code generation problem.
18969 @end itemize
18971 @geindex -gnatdc switch
18974 @itemize *
18976 @item 
18977 Run @code{gcc} with the @code{-gnatdc} switch. This is a GNAT specific
18978 switch that does for the front-end what @code{-v} does
18979 for the back end. The system prints the name of each unit,
18980 either a compilation unit or nested unit, as it is being analyzed.
18982 @item 
18983 Finally, you can start
18984 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
18985 front-end of GNAT, and can be run independently (normally it is just
18986 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
18987 would on a C program (but @ref{151,,The GNAT Debugger GDB} for caveats). The
18988 @code{where} command is the first line of attack; the variable
18989 @code{lineno} (seen by @code{print lineno}), used by the second phase of
18990 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
18991 which the execution stopped, and @code{input_file name} indicates the name of
18992 the source file.
18993 @end itemize
18995 @node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
18996 @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}
18997 @subsection Naming Conventions for GNAT Source Files
19000 In order to examine the workings of the GNAT system, the following
19001 brief description of its organization may be helpful:
19004 @itemize *
19006 @item 
19007 Files with prefix @code{sc} contain the lexical scanner.
19009 @item 
19010 All files prefixed with @code{par} are components of the parser. The
19011 numbers correspond to chapters of the Ada Reference Manual. For example,
19012 parsing of select statements can be found in @code{par-ch9.adb}.
19014 @item 
19015 All files prefixed with @code{sem} perform semantic analysis. The
19016 numbers correspond to chapters of the Ada standard. For example, all
19017 issues involving context clauses can be found in @code{sem_ch10.adb}. In
19018 addition, some features of the language require sufficient special processing
19019 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19020 dynamic dispatching, etc.
19022 @item 
19023 All files prefixed with @code{exp} perform normalization and
19024 expansion of the intermediate representation (abstract syntax tree, or AST).
19025 these files use the same numbering scheme as the parser and semantics files.
19026 For example, the construction of record initialization procedures is done in
19027 @code{exp_ch3.adb}.
19029 @item 
19030 The files prefixed with @code{bind} implement the binder, which
19031 verifies the consistency of the compilation, determines an order of
19032 elaboration, and generates the bind file.
19034 @item 
19035 The files @code{atree.ads} and @code{atree.adb} detail the low-level
19036 data structures used by the front-end.
19038 @item 
19039 The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
19040 the abstract syntax tree as produced by the parser.
19042 @item 
19043 The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
19044 all entities, computed during semantic analysis.
19046 @item 
19047 Library management issues are dealt with in files with prefix
19048 @code{lib}.
19050 @geindex Annex A (in Ada Reference Manual)
19052 @item 
19053 Ada files with the prefix @code{a-} are children of @code{Ada}, as
19054 defined in Annex A.
19056 @geindex Annex B (in Ada reference Manual)
19058 @item 
19059 Files with prefix @code{i-} are children of @code{Interfaces}, as
19060 defined in Annex B.
19062 @geindex System (package in Ada Reference Manual)
19064 @item 
19065 Files with prefix @code{s-} are children of @code{System}. This includes
19066 both language-defined children and GNAT run-time routines.
19068 @geindex GNAT (package)
19070 @item 
19071 Files with prefix @code{g-} are children of @code{GNAT}. These are useful
19072 general-purpose packages, fully documented in their specs. All
19073 the other @code{.c} files are modifications of common @code{gcc} files.
19074 @end itemize
19076 @node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
19077 @anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{168}@anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{169}
19078 @subsection Getting Internal Debugging Information
19081 Most compilers have internal debugging switches and modes. GNAT
19082 does also, except GNAT internal debugging switches and modes are not
19083 secret. A summary and full description of all the compiler and binder
19084 debug flags are in the file @code{debug.adb}. You must obtain the
19085 sources of the compiler to see the full detailed effects of these flags.
19087 The switches that print the source of the program (reconstructed from
19088 the internal tree) are of general interest for user programs, as are the
19089 options to print
19090 the full internal tree, and the entity table (the symbol table
19091 information). The reconstructed source provides a readable version of the
19092 program after the front-end has completed analysis and  expansion,
19093 and is useful when studying the performance of specific constructs.
19094 For example, constraint checks are indicated, complex aggregates
19095 are replaced with loops and assignments, and tasking primitives
19096 are replaced with run-time calls.
19098 @geindex traceback
19100 @geindex stack traceback
19102 @geindex stack unwinding
19104 @node Stack Traceback,Pretty-Printers for the GNAT runtime,Getting Internal Debugging Information,Running and Debugging Ada Programs
19105 @anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{16a}@anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{16b}
19106 @subsection Stack Traceback
19109 Traceback is a mechanism to display the sequence of subprogram calls that
19110 leads to a specified execution point in a program. Often (but not always)
19111 the execution point is an instruction at which an exception has been raised.
19112 This mechanism is also known as @emph{stack unwinding} because it obtains
19113 its information by scanning the run-time stack and recovering the activation
19114 records of all active subprograms. Stack unwinding is one of the most
19115 important tools for program debugging.
19117 The first entry stored in traceback corresponds to the deepest calling level,
19118 that is to say the subprogram currently executing the instruction
19119 from which we want to obtain the traceback.
19121 Note that there is no runtime performance penalty when stack traceback
19122 is enabled, and no exception is raised during program execution.
19124 @geindex traceback
19125 @geindex non-symbolic
19127 @menu
19128 * Non-Symbolic Traceback:: 
19129 * Symbolic Traceback:: 
19131 @end menu
19133 @node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
19134 @anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{16c}@anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{16d}
19135 @subsubsection Non-Symbolic Traceback
19138 Note: this feature is not supported on all platforms. See
19139 @code{GNAT.Traceback} spec in @code{g-traceb.ads}
19140 for a complete list of supported platforms.
19142 @subsubheading Tracebacks From an Unhandled Exception
19145 A runtime non-symbolic traceback is a list of addresses of call instructions.
19146 To enable this feature you must use the @code{-E} @code{gnatbind} option. With
19147 this option a stack traceback is stored as part of exception information.
19149 You can translate this information using the @code{addr2line} tool, provided that
19150 the program is compiled with debugging options (see @ref{dd,,Compiler Switches})
19151 and linked at a fixed position with @code{-no-pie}.
19153 Here is a simple example with @code{gnatmake}:
19155 @quotation
19157 @example
19158 procedure STB is
19160    procedure P1 is
19161    begin
19162       raise Constraint_Error;
19163    end P1;
19165    procedure P2 is
19166    begin
19167       P1;
19168    end P2;
19170 begin
19171    P2;
19172 end STB;
19173 @end example
19175 @example
19176 $ gnatmake stb -g -bargs -E -largs -no-pie
19177 $ stb
19179 Execution of stb terminated by unhandled exception
19180 raised CONSTRAINT_ERROR : stb.adb:5 explicit raise
19181 Load address: 0x400000
19182 Call stack traceback locations:
19183 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19184 @end example
19185 @end quotation
19187 As we see the traceback lists a sequence of addresses for the unhandled
19188 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19189 guess that this exception come from procedure P1. To translate these
19190 addresses into the source lines where the calls appear, the @code{addr2line}
19191 tool needs to be invoked like this:
19193 @quotation
19195 @example
19196 $ addr2line -e stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19197    0x4011f1 0x77e892a4
19199 d:/stb/stb.adb:5
19200 d:/stb/stb.adb:10
19201 d:/stb/stb.adb:14
19202 d:/stb/b~stb.adb:197
19203 crtexe.c:?
19204 crtexe.c:?
19205 ??:0
19206 @end example
19207 @end quotation
19209 The @code{addr2line} tool has several other useful options:
19211 @quotation
19214 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
19215 @item
19217 @code{-a --addresses}
19219 @tab
19221 to show the addresses alongside the line numbers
19223 @item
19225 @code{-f --functions}
19227 @tab
19229 to get the function name corresponding to a location
19231 @item
19233 @code{-p --pretty-print}
19235 @tab
19237 to print all the information on a single line
19239 @item
19241 @code{--demangle=gnat}
19243 @tab
19245 to use the GNAT decoding mode for the function names
19247 @end multitable
19250 @example
19251 $ addr2line -e stb -a -f -p --demangle=gnat 0x401373 0x40138b
19252    0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19254 0x00401373: stb.p1 at d:/stb/stb.adb:5
19255 0x0040138B: stb.p2 at d:/stb/stb.adb:10
19256 0x0040139C: stb at d:/stb/stb.adb:14
19257 0x00401335: main at d:/stb/b~stb.adb:197
19258 0x004011c4: ?? at crtexe.c:?
19259 0x004011f1: ?? at crtexe.c:?
19260 0x77e892a4: ?? ??:0
19261 @end example
19262 @end quotation
19264 From this traceback we can see that the exception was raised in @code{stb.adb}
19265 at line 5, which was reached from a procedure call in @code{stb.adb} at line
19266 10, and so on. The @code{b~std.adb} is the binder file, which contains the
19267 call to the main program. @ref{110,,Running gnatbind}. The remaining entries are
19268 assorted runtime routines and the output will vary from platform to platform.
19270 It is also possible to use @code{GDB} with these traceback addresses to debug
19271 the program. For example, we can break at a given code location, as reported
19272 in the stack traceback:
19274 @example
19275 $ gdb -nw stb
19277 (gdb) break *0x401373
19278 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19279 @end example
19281 It is important to note that the stack traceback addresses do not change when
19282 debug information is included. This is particularly useful because it makes it
19283 possible to release software without debug information (to minimize object
19284 size), get a field report that includes a stack traceback whenever an internal
19285 bug occurs, and then be able to retrieve the sequence of calls with the same
19286 program compiled with debug information.
19288 However the @code{addr2line} tool does not work with Position-Independent Code
19289 (PIC), the historical example being Linux dynamic libraries and Windows DLLs,
19290 which nowadays encompasse Position-Independent Executables (PIE) on recent
19291 Linux and Windows versions.
19293 In order to translate addresses the source lines with Position-Independent
19294 Executables on recent Linux and Windows versions, in other words without
19295 using the switch @code{-no-pie} during linking, you need to use the
19296 @code{gnatsymbolize} tool with @code{--load} instead of the @code{addr2line}
19297 tool. The main difference is that you need to copy the Load Address output
19298 in the traceback ahead of the sequence of addresses. And the default mode
19299 of @code{gnatsymbolize} is equivalent to that of @code{addr2line} with the above
19300 switches, so none of them is needed:
19302 @example
19303 $ gnatmake stb -g -bargs -E
19304 $ stb
19306 Execution of stb terminated by unhandled exception
19307 raised CONSTRAINT_ERROR : stb.adb:5 explicit raise
19308 Load address: 0x400000
19309 Call stack traceback locations:
19310 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19312 $ gnatsymbolize --load stb 0x400000 0x401373 0x40138b 0x40139c 0x401335 \
19313    0x4011c4 0x4011f1 0x77e892a4
19315 0x00401373 Stb.P1 at stb.adb:5
19316 0x0040138B Stb.P2 at stb.adb:10
19317 0x0040139C Stb at stb.adb:14
19318 0x00401335 Main at b~stb.adb:197
19319 0x004011c4 __tmainCRTStartup at ???
19320 0x004011f1 mainCRTStartup at ???
19321 0x77e892a4 ??? at ???
19322 @end example
19324 @subsubheading Tracebacks From Exception Occurrences
19327 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
19328 The stack traceback is attached to the exception information string, and can
19329 be retrieved in an exception handler within the Ada program, by means of the
19330 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19332 @quotation
19334 @example
19335 with Ada.Text_IO;
19336 with Ada.Exceptions;
19338 procedure STB is
19340    use Ada;
19341    use Ada.Exceptions;
19343    procedure P1 is
19344       K : Positive := 1;
19345    begin
19346       K := K - 1;
19347    exception
19348       when E : others =>
19349          Text_IO.Put_Line (Exception_Information (E));
19350    end P1;
19352    procedure P2 is
19353    begin
19354       P1;
19355    end P2;
19357 begin
19358    P2;
19359 end STB;
19360 @end example
19362 @example
19363 $ gnatmake stb -g -bargs -E -largs -no-pie
19364 $ stb
19366 raised CONSTRAINT_ERROR : stb.adb:12 range check failed
19367 Load address: 0x400000
19368 Call stack traceback locations:
19369 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19370 @end example
19371 @end quotation
19373 @subsubheading Tracebacks From Anywhere in a Program
19376 It is also possible to retrieve a stack traceback from anywhere in a program.
19377 For this you need to use the @code{GNAT.Traceback} API. This package includes a
19378 procedure called @code{Call_Chain} that computes a complete stack traceback, as
19379 well as useful display procedures described below. It is not necessary to use
19380 the @code{-E} @code{gnatbind} option in this case, because the stack traceback
19381 mechanism is invoked explicitly.
19383 In the following example we compute a traceback at a specific location in the
19384 program, and we display it using @code{GNAT.Debug_Utilities.Image} to convert
19385 addresses to strings:
19387 @quotation
19389 @example
19390 with Ada.Text_IO;
19391 with GNAT.Traceback;
19392 with GNAT.Debug_Utilities;
19393 with System;
19395 procedure STB is
19397    use Ada;
19398    use Ada.Text_IO;
19399    use GNAT;
19400    use GNAT.Traceback;
19401    use System;
19403    LA : constant Address := Executable_Load_Address;
19405    procedure P1 is
19406       TB  : Tracebacks_Array (1 .. 10);
19407       --  We are asking for a maximum of 10 stack frames.
19408       Len : Natural;
19409       --  Len will receive the actual number of stack frames returned.
19410    begin
19411       Call_Chain (TB, Len);
19413       Put ("In STB.P1 : ");
19415       for K in 1 .. Len loop
19416          Put (Debug_Utilities.Image_C (TB (K)));
19417          Put (' ');
19418       end loop;
19420       New_Line;
19421    end P1;
19423    procedure P2 is
19424    begin
19425       P1;
19426    end P2;
19428 begin
19429    if LA /= Null_Address then
19430       Put_Line ("Load address: " & Debug_Utilities.Image_C (LA));
19431    end if;
19433    P2;
19434 end STB;
19435 @end example
19437 @example
19438 $ gnatmake stb -g
19439 $ stb
19441 Load address: 0x400000
19442 In STB.P1 : 0x40F1E4 0x4014F2 0x40170B 0x40171C 0x401461 0x4011C4 \
19443   0x4011F1 0x77E892A4
19444 @end example
19445 @end quotation
19447 You can then get further information by invoking the @code{addr2line} tool or
19448 the @code{gnatsymbolize} tool as described earlier (note that the hexadecimal
19449 addresses need to be specified in C format, with a leading ‘0x’).
19451 @geindex traceback
19452 @geindex symbolic
19454 @node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
19455 @anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{16e}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{16f}
19456 @subsubsection Symbolic Traceback
19459 A symbolic traceback is a stack traceback in which procedure names are
19460 associated with each code location.
19462 Note that this feature is not supported on all platforms. See
19463 @code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
19464 list of currently supported platforms.
19466 Note that the symbolic traceback requires that the program be compiled
19467 with debug information. If it is not compiled with debug information
19468 only the non-symbolic information will be valid.
19470 @subsubheading Tracebacks From Exception Occurrences
19473 Here is an example:
19475 @quotation
19477 @example
19478 with Ada.Text_IO;
19479 with GNAT.Traceback.Symbolic;
19481 procedure STB is
19483    procedure P1 is
19484    begin
19485       raise Constraint_Error;
19486    end P1;
19488    procedure P2 is
19489    begin
19490       P1;
19491    end P2;
19493    procedure P3 is
19494    begin
19495       P2;
19496    end P3;
19498 begin
19499    P3;
19500 exception
19501    when E : others =>
19502       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19503 end STB;
19504 @end example
19506 @example
19507 $ gnatmake -g stb -bargs -E
19508 $ stb
19510 0040149F in stb.p1 at stb.adb:8
19511 004014B7 in stb.p2 at stb.adb:13
19512 004014CF in stb.p3 at stb.adb:18
19513 004015DD in ada.stb at stb.adb:22
19514 00401461 in main at b~stb.adb:168
19515 004011C4 in __mingw_CRTStartup at crt1.c:200
19516 004011F1 in mainCRTStartup at crt1.c:222
19517 77E892A4 in ?? at ??:0
19518 @end example
19519 @end quotation
19521 @subsubheading Tracebacks From Anywhere in a Program
19524 It is possible to get a symbolic stack traceback
19525 from anywhere in a program, just as for non-symbolic tracebacks.
19526 The first step is to obtain a non-symbolic
19527 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19528 information. Here is an example:
19530 @quotation
19532 @example
19533 with Ada.Text_IO;
19534 with GNAT.Traceback;
19535 with GNAT.Traceback.Symbolic;
19537 procedure STB is
19539    use Ada;
19540    use GNAT.Traceback;
19541    use GNAT.Traceback.Symbolic;
19543    procedure P1 is
19544       TB  : Tracebacks_Array (1 .. 10);
19545       --  We are asking for a maximum of 10 stack frames.
19546       Len : Natural;
19547       --  Len will receive the actual number of stack frames returned.
19548    begin
19549       Call_Chain (TB, Len);
19550       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19551    end P1;
19553    procedure P2 is
19554    begin
19555       P1;
19556    end P2;
19558 begin
19559    P2;
19560 end STB;
19561 @end example
19562 @end quotation
19564 @subsubheading Automatic Symbolic Tracebacks
19567 Symbolic tracebacks may also be enabled by using the -Es switch to gnatbind (as
19568 in @code{gprbuild -g ... -bargs -Es}).
19569 This will cause the Exception_Information to contain a symbolic traceback,
19570 which will also be printed if an unhandled exception terminates the
19571 program.
19573 @node Pretty-Printers for the GNAT runtime,,Stack Traceback,Running and Debugging Ada Programs
19574 @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}
19575 @subsection Pretty-Printers for the GNAT runtime
19578 As discussed in @cite{Calling User-Defined Subprograms}, GDB’s
19579 @code{print} command only knows about the physical layout of program data
19580 structures and therefore normally displays only low-level dumps, which
19581 are often hard to understand.
19583 An example of this is when trying to display the contents of an Ada
19584 standard container, such as @code{Ada.Containers.Ordered_Maps.Map}:
19586 @quotation
19588 @example
19589 with Ada.Containers.Ordered_Maps;
19591 procedure PP is
19592    package Int_To_Nat is
19593       new Ada.Containers.Ordered_Maps (Integer, Natural);
19595    Map : Int_To_Nat.Map;
19596 begin
19597    Map.Insert (1, 10);
19598    Map.Insert (2, 20);
19599    Map.Insert (3, 30);
19601    Map.Clear; --  BREAK HERE
19602 end PP;
19603 @end example
19604 @end quotation
19606 When this program is built with debugging information and run under
19607 GDB up to the @code{Map.Clear} statement, trying to print @code{Map} will
19608 yield information that is only relevant to the developers of our standard
19609 containers:
19611 @quotation
19613 @example
19614 (gdb) print map
19615 $1 = (
19616   tree => (
19617     first => 0x64e010,
19618     last => 0x64e070,
19619     root => 0x64e040,
19620     length => 3,
19621     tc => (
19622       busy => 0,
19623       lock => 0
19624     )
19625   )
19627 @end example
19628 @end quotation
19630 Fortunately, GDB has a feature called pretty-printers@footnote{http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Introduction},
19631 which allows customizing how GDB displays data structures. The GDB
19632 shipped with GNAT embeds such pretty-printers for the most common
19633 containers in the standard library.  To enable them, either run the
19634 following command manually under GDB or add it to your @code{.gdbinit} file:
19636 @quotation
19638 @example
19639 python import gnatdbg; gnatdbg.setup()
19640 @end example
19641 @end quotation
19643 Once this is done, GDB’s @code{print} command will automatically use
19644 these pretty-printers when appropriate. Using the previous example:
19646 @quotation
19648 @example
19649 (gdb) print map
19650 $1 = pp.int_to_nat.map of length 3 = @{
19651   [1] = 10,
19652   [2] = 20,
19653   [3] = 30
19655 @end example
19656 @end quotation
19658 Pretty-printers are invoked each time GDB tries to display a value,
19659 including when displaying the arguments of a called subprogram (in
19660 GDB’s @code{backtrace} command) or when printing the value returned by a
19661 function (in GDB’s @code{finish} command).
19663 To display a value without involving pretty-printers, @code{print} can be
19664 invoked with its @code{/r} option:
19666 @quotation
19668 @example
19669 (gdb) print/r map
19670 $1 = (
19671   tree => (...
19672 @end example
19673 @end quotation
19675 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}
19676 for more information.
19678 @geindex Profiling
19680 @node Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
19681 @anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{172}@anchor{gnat_ugn/gnat_and_program_execution profiling}@anchor{149}
19682 @section Profiling
19685 This section describes how to use the @code{gprof} profiler tool on Ada programs.
19687 @geindex gprof
19689 @geindex Profiling
19691 @menu
19692 * Profiling an Ada Program with gprof:: 
19694 @end menu
19696 @node Profiling an Ada Program with gprof,,,Profiling
19697 @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}
19698 @subsection Profiling an Ada Program with gprof
19701 This section is not meant to be an exhaustive documentation of @code{gprof}.
19702 Full documentation for it can be found in the @cite{GNU Profiler User’s Guide}
19703 documentation that is part of this GNAT distribution.
19705 Profiling a program helps determine the parts of a program that are executed
19706 most often, and are therefore the most time-consuming.
19708 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
19709 better handle Ada programs and multitasking.
19710 It is currently supported on the following platforms
19713 @itemize *
19715 @item 
19716 Linux x86/x86_64
19718 @item 
19719 Windows x86/x86_64 (without PIE support)
19720 @end itemize
19722 In order to profile a program using @code{gprof}, several steps are needed:
19725 @enumerate 
19727 @item 
19728 Instrument the code, which requires a full recompilation of the project with the
19729 proper switches.
19731 @item 
19732 Execute the program under the analysis conditions, i.e. with the desired
19733 input.
19735 @item 
19736 Analyze the results using the @code{gprof} tool.
19737 @end enumerate
19739 The following sections detail the different steps, and indicate how
19740 to interpret the results.
19742 @menu
19743 * Compilation for profiling:: 
19744 * Program execution:: 
19745 * Running gprof:: 
19746 * Interpretation of profiling results:: 
19748 @end menu
19750 @node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
19751 @anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{175}@anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{176}
19752 @subsubsection Compilation for profiling
19755 @geindex -pg (gcc)
19756 @geindex for profiling
19758 @geindex -pg (gnatlink)
19759 @geindex for profiling
19761 In order to profile a program the first step is to tell the compiler
19762 to generate the necessary profiling information. The compiler switch to be used
19763 is @code{-pg}, which must be added to other compilation switches. This
19764 switch needs to be specified both during compilation and link stages, and can
19765 be specified once when using gnatmake:
19767 @quotation
19769 @example
19770 $ gnatmake -f -pg -P my_project
19771 @end example
19772 @end quotation
19774 Note that only the objects that were compiled with the @code{-pg} switch will
19775 be profiled; if you need to profile your whole project, use the @code{-f}
19776 gnatmake switch to force full recompilation.
19778 Note that on Windows, gprof does not support PIE. The @code{-no-pie} switch
19779 should be added to the linker flags to disable this feature.
19781 @node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
19782 @anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{177}@anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{178}
19783 @subsubsection Program execution
19786 Once the program has been compiled for profiling, you can run it as usual.
19788 The only constraint imposed by profiling is that the program must terminate
19789 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
19790 properly analyzed.
19792 Once the program completes execution, a data file called @code{gmon.out} is
19793 generated in the directory where the program was launched from. If this file
19794 already exists, it will be overwritten.
19796 @node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
19797 @anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{179}@anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{17a}
19798 @subsubsection Running gprof
19801 The @code{gprof} tool is called as follow:
19803 @quotation
19805 @example
19806 $ gprof my_prog gmon.out
19807 @end example
19808 @end quotation
19810 or simply:
19812 @quotation
19814 @example
19815 $ gprof my_prog
19816 @end example
19817 @end quotation
19819 The complete form of the gprof command line is the following:
19821 @quotation
19823 @example
19824 $ gprof [switches] [executable [data-file]]
19825 @end example
19826 @end quotation
19828 @code{gprof} supports numerous switches. The order of these
19829 switch does not matter. The full list of options can be found in
19830 the GNU Profiler User’s Guide documentation that comes with this documentation.
19832 The following is the subset of those switches that is most relevant:
19834 @geindex --demangle (gprof)
19837 @table @asis
19839 @item @code{--demangle[=@emph{style}]}, @code{--no-demangle}
19841 These options control whether symbol names should be demangled when
19842 printing output.  The default is to demangle C++ symbols.  The
19843 @code{--no-demangle} option may be used to turn off demangling. Different
19844 compilers have different mangling styles.  The optional demangling style
19845 argument can be used to choose an appropriate demangling style for your
19846 compiler, in particular Ada symbols generated by GNAT can be demangled using
19847 @code{--demangle=gnat}.
19848 @end table
19850 @geindex -e (gprof)
19853 @table @asis
19855 @item @code{-e @emph{function_name}}
19857 The @code{-e @emph{function}} option tells @code{gprof} not to print
19858 information about the function @code{function_name} (and its
19859 children…) in the call graph.  The function will still be listed
19860 as a child of any functions that call it, but its index number will be
19861 shown as @code{[not printed]}.  More than one @code{-e} option may be
19862 given; only one @code{function_name} may be indicated with each @code{-e}
19863 option.
19864 @end table
19866 @geindex -E (gprof)
19869 @table @asis
19871 @item @code{-E @emph{function_name}}
19873 The @code{-E @emph{function}} option works like the @code{-e} option, but
19874 execution time spent in the function (and children who were not called from
19875 anywhere else), will not be used to compute the percentages-of-time for
19876 the call graph.  More than one @code{-E} option may be given; only one
19877 @code{function_name} may be indicated with each @code{-E`} option.
19878 @end table
19880 @geindex -f (gprof)
19883 @table @asis
19885 @item @code{-f @emph{function_name}}
19887 The @code{-f @emph{function}} option causes @code{gprof} to limit the
19888 call graph to the function @code{function_name} and its children (and
19889 their children…).  More than one @code{-f} option may be given;
19890 only one @code{function_name} may be indicated with each @code{-f}
19891 option.
19892 @end table
19894 @geindex -F (gprof)
19897 @table @asis
19899 @item @code{-F @emph{function_name}}
19901 The @code{-F @emph{function}} option works like the @code{-f} option, but
19902 only time spent in the function and its children (and their
19903 children…) will be used to determine total-time and
19904 percentages-of-time for the call graph.  More than one @code{-F} option
19905 may be given; only one @code{function_name} may be indicated with each
19906 @code{-F} option.  The @code{-F} option overrides the @code{-E} option.
19907 @end table
19909 @node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
19910 @anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{17b}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{17c}
19911 @subsubsection Interpretation of profiling results
19914 The results of the profiling analysis are represented by two arrays: the
19915 ‘flat profile’ and the ‘call graph’. Full documentation of those outputs
19916 can be found in the GNU Profiler User’s Guide.
19918 The flat profile shows the time spent in each function of the program, and how
19919 many time it has been called. This allows you to locate easily the most
19920 time-consuming functions.
19922 The call graph shows, for each subprogram, the subprograms that call it,
19923 and the subprograms that it calls. It also provides an estimate of the time
19924 spent in each of those callers/called subprograms.
19926 @node Improving Performance,Overflow Check Handling in GNAT,Profiling,GNAT and Program Execution
19927 @anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{14a}@anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{17d}
19928 @section Improving Performance
19931 @geindex Improving performance
19933 This section presents several topics related to program performance.
19934 It first describes some of the tradeoffs that need to be considered
19935 and some of the techniques for making your program run faster.
19937 It then documents the unused subprogram/data elimination feature,
19938 which can reduce the size of program executables.
19940 @menu
19941 * Performance Considerations:: 
19942 * Text_IO Suggestions:: 
19943 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
19945 @end menu
19947 @node Performance Considerations,Text_IO Suggestions,,Improving Performance
19948 @anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{17e}@anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{17f}
19949 @subsection Performance Considerations
19952 The GNAT system provides a number of options that allow a trade-off
19953 between
19956 @itemize *
19958 @item 
19959 performance of the generated code
19961 @item 
19962 speed of compilation
19964 @item 
19965 minimization of dependences and recompilation
19967 @item 
19968 the degree of run-time checking.
19969 @end itemize
19971 The defaults (if no options are selected) aim at improving the speed
19972 of compilation and minimizing dependences, at the expense of performance
19973 of the generated code:
19976 @itemize *
19978 @item 
19979 no optimization
19981 @item 
19982 no inlining of subprogram calls
19984 @item 
19985 all run-time checks enabled except overflow and elaboration checks
19986 @end itemize
19988 These options are suitable for most program development purposes. This
19989 section describes how you can modify these choices, and also provides
19990 some guidelines on debugging optimized code.
19992 @menu
19993 * Controlling Run-Time Checks:: 
19994 * Use of Restrictions:: 
19995 * Optimization Levels:: 
19996 * Debugging Optimized Code:: 
19997 * Inlining of Subprograms:: 
19998 * Floating Point Operations:: 
19999 * Vectorization of loops:: 
20000 * Other Optimization Switches:: 
20001 * Optimization and Strict Aliasing:: 
20002 * Aliased Variables and Optimization:: 
20003 * Atomic Variables and Optimization:: 
20004 * Passive Task Optimization:: 
20006 @end menu
20008 @node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
20009 @anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{180}@anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{181}
20010 @subsubsection Controlling Run-Time Checks
20013 By default, GNAT generates all run-time checks, except stack overflow
20014 checks, and checks for access before elaboration on subprogram
20015 calls. The latter are not required in default mode, because all
20016 necessary checking is done at compile time.
20018 @geindex -gnatp (gcc)
20020 @geindex -gnato (gcc)
20022 The gnat switch, @code{-gnatp} allows this default to be modified. See
20023 @ref{ec,,Run-Time Checks}.
20025 Our experience is that the default is suitable for most development
20026 purposes.
20028 Elaboration checks are off by default, and also not needed by default, since
20029 GNAT uses a static elaboration analysis approach that avoids the need for
20030 run-time checking. This manual contains a full chapter discussing the issue
20031 of elaboration checks, and if the default is not satisfactory for your use,
20032 you should read this chapter.
20034 For validity checks, the minimal checks required by the Ada Reference
20035 Manual (for case statements and assignments to array elements) are on
20036 by default. These can be suppressed by use of the @code{-gnatVn} switch.
20037 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
20038 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
20039 it may be reasonable to routinely use @code{-gnatVn}. Validity checks
20040 are also suppressed entirely if @code{-gnatp} is used.
20042 @geindex Overflow checks
20044 @geindex Checks
20045 @geindex overflow
20047 @geindex Suppress
20049 @geindex Unsuppress
20051 @geindex pragma Suppress
20053 @geindex pragma Unsuppress
20055 Note that the setting of the switches controls the default setting of
20056 the checks. They may be modified using either @code{pragma Suppress} (to
20057 remove checks) or @code{pragma Unsuppress} (to add back suppressed
20058 checks) in the program source.
20060 @node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
20061 @anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{182}@anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{183}
20062 @subsubsection Use of Restrictions
20065 The use of pragma Restrictions allows you to control which features are
20066 permitted in your program. Apart from the obvious point that if you avoid
20067 relatively expensive features like finalization (enforceable by the use
20068 of pragma Restrictions (No_Finalization)), the use of this pragma does not
20069 affect the generated code in most cases.
20071 One notable exception to this rule is that the possibility of task abort
20072 results in some distributed overhead, particularly if finalization or
20073 exception handlers are used. The reason is that certain sections of code
20074 have to be marked as non-abortable.
20076 If you use neither the @code{abort} statement, nor asynchronous transfer
20077 of control (@code{select ... then abort}), then this distributed overhead
20078 is removed, which may have a general positive effect in improving
20079 overall performance.  Especially code involving frequent use of tasking
20080 constructs and controlled types will show much improved performance.
20081 The relevant restrictions pragmas are
20083 @quotation
20085 @example
20086 pragma Restrictions (No_Abort_Statements);
20087 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
20088 @end example
20089 @end quotation
20091 It is recommended that these restriction pragmas be used if possible. Note
20092 that this also means that you can write code without worrying about the
20093 possibility of an immediate abort at any point.
20095 @node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
20096 @anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{184}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{ef}
20097 @subsubsection Optimization Levels
20100 @geindex -O (gcc)
20102 Without any optimization option,
20103 the compiler’s goal is to reduce the cost of
20104 compilation and to make debugging produce the expected results.
20105 Statements are independent: if you stop the program with a breakpoint between
20106 statements, you can then assign a new value to any variable or change
20107 the program counter to any other statement in the subprogram and get exactly
20108 the results you would expect from the source code.
20110 Turning on optimization makes the compiler attempt to improve the
20111 performance and/or code size at the expense of compilation time and
20112 possibly the ability to debug the program.
20114 If you use multiple
20115 -O options, with or without level numbers,
20116 the last such option is the one that is effective.
20118 The default is optimization off. This results in the fastest compile
20119 times, but GNAT makes absolutely no attempt to optimize, and the
20120 generated programs are considerably larger and slower than when
20121 optimization is enabled. You can use the
20122 @code{-O} switch (the permitted forms are @code{-O0}, @code{-O1}
20123 @code{-O2}, @code{-O3}, and @code{-Os})
20124 to @code{gcc} to control the optimization level:
20127 @itemize *
20129 @item 
20131 @table @asis
20133 @item @code{-O0}
20135 No optimization (the default);
20136 generates unoptimized code but has
20137 the fastest compilation time.
20139 Note that many other compilers do substantial optimization even
20140 if ‘no optimization’ is specified. With gcc, it is very unusual
20141 to use @code{-O0} for production if execution time is of any concern,
20142 since @code{-O0} means (almost) no optimization. This difference
20143 between gcc and other compilers should be kept in mind when
20144 doing performance comparisons.
20145 @end table
20147 @item 
20149 @table @asis
20151 @item @code{-O1}
20153 Moderate optimization;
20154 optimizes reasonably well but does not
20155 degrade compilation time significantly.
20156 @end table
20158 @item 
20160 @table @asis
20162 @item @code{-O2}
20164 Full optimization;
20165 generates highly optimized code and has
20166 the slowest compilation time.
20167 @end table
20169 @item 
20171 @table @asis
20173 @item @code{-O3}
20175 Full optimization as in @code{-O2};
20176 also uses more aggressive automatic inlining of subprograms within a unit
20177 (@ref{102,,Inlining of Subprograms}) and attempts to vectorize loops.
20178 @end table
20180 @item 
20182 @table @asis
20184 @item @code{-Os}
20186 Optimize space usage (code and data) of resulting program.
20187 @end table
20188 @end itemize
20190 Higher optimization levels perform more global transformations on the
20191 program and apply more expensive analysis algorithms in order to generate
20192 faster and more compact code. The price in compilation time, and the
20193 resulting improvement in execution time,
20194 both depend on the particular application and the hardware environment.
20195 You should experiment to find the best level for your application.
20197 Since the precise set of optimizations done at each level will vary from
20198 release to release (and sometime from target to target), it is best to think
20199 of the optimization settings in general terms.
20200 See the @emph{Options That Control Optimization} section in
20201 @cite{Using the GNU Compiler Collection (GCC)}
20202 for details about
20203 the @code{-O} settings and a number of @code{-f} options that
20204 individually enable or disable specific optimizations.
20206 Unlike some other compilation systems, @code{gcc} has
20207 been tested extensively at all optimization levels. There are some bugs
20208 which appear only with optimization turned on, but there have also been
20209 bugs which show up only in @emph{unoptimized} code. Selecting a lower
20210 level of optimization does not improve the reliability of the code
20211 generator, which in practice is highly reliable at all optimization
20212 levels.
20214 Note regarding the use of @code{-O3}: The use of this optimization level
20215 ought not to be automatically preferred over that of level @code{-O2},
20216 since it often results in larger executables which may run more slowly.
20217 See further discussion of this point in @ref{102,,Inlining of Subprograms}.
20219 @node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
20220 @anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{185}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{186}
20221 @subsubsection Debugging Optimized Code
20224 @geindex Debugging optimized code
20226 @geindex Optimization and debugging
20228 Although it is possible to do a reasonable amount of debugging at
20229 nonzero optimization levels,
20230 the higher the level the more likely that
20231 source-level constructs will have been eliminated by optimization.
20232 For example, if a loop is strength-reduced, the loop
20233 control variable may be completely eliminated and thus cannot be
20234 displayed in the debugger.
20235 This can only happen at @code{-O2} or @code{-O3}.
20236 Explicit temporary variables that you code might be eliminated at
20237 level @code{-O1} or higher.
20239 @geindex -g (gcc)
20241 The use of the @code{-g} switch,
20242 which is needed for source-level debugging,
20243 affects the size of the program executable on disk,
20244 and indeed the debugging information can be quite large.
20245 However, it has no effect on the generated code (and thus does not
20246 degrade performance)
20248 Since the compiler generates debugging tables for a compilation unit before
20249 it performs optimizations, the optimizing transformations may invalidate some
20250 of the debugging data.  You therefore need to anticipate certain
20251 anomalous situations that may arise while debugging optimized code.
20252 These are the most common cases:
20255 @itemize *
20257 @item 
20258 @emph{The ‘hopping Program Counter’:}  Repeated @code{step} or @code{next}
20259 commands show
20260 the PC bouncing back and forth in the code.  This may result from any of
20261 the following optimizations:
20264 @itemize -
20266 @item 
20267 @emph{Common subexpression elimination:} using a single instance of code for a
20268 quantity that the source computes several times.  As a result you
20269 may not be able to stop on what looks like a statement.
20271 @item 
20272 @emph{Invariant code motion:} moving an expression that does not change within a
20273 loop, to the beginning of the loop.
20275 @item 
20276 @emph{Instruction scheduling:} moving instructions so as to
20277 overlap loads and stores (typically) with other code, or in
20278 general to move computations of values closer to their uses. Often
20279 this causes you to pass an assignment statement without the assignment
20280 happening and then later bounce back to the statement when the
20281 value is actually needed.  Placing a breakpoint on a line of code
20282 and then stepping over it may, therefore, not always cause all the
20283 expected side-effects.
20284 @end itemize
20286 @item 
20287 @emph{The ‘big leap’:} More commonly known as @emph{cross-jumping}, in which
20288 two identical pieces of code are merged and the program counter suddenly
20289 jumps to a statement that is not supposed to be executed, simply because
20290 it (and the code following) translates to the same thing as the code
20291 that @emph{was} supposed to be executed.  This effect is typically seen in
20292 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
20293 a @code{break} in a C @code{switch} statement.
20295 @item 
20296 @emph{The ‘roving variable’:} The symptom is an unexpected value in a variable.
20297 There are various reasons for this effect:
20300 @itemize -
20302 @item 
20303 In a subprogram prologue, a parameter may not yet have been moved to its
20304 ‘home’.
20306 @item 
20307 A variable may be dead, and its register re-used.  This is
20308 probably the most common cause.
20310 @item 
20311 As mentioned above, the assignment of a value to a variable may
20312 have been moved.
20314 @item 
20315 A variable may be eliminated entirely by value propagation or
20316 other means.  In this case, GCC may incorrectly generate debugging
20317 information for the variable
20318 @end itemize
20320 In general, when an unexpected value appears for a local variable or parameter
20321 you should first ascertain if that value was actually computed by
20322 your program, as opposed to being incorrectly reported by the debugger.
20323 Record fields or
20324 array elements in an object designated by an access value
20325 are generally less of a problem, once you have ascertained that the access
20326 value is sensible.
20327 Typically, this means checking variables in the preceding code and in the
20328 calling subprogram to verify that the value observed is explainable from other
20329 values (one must apply the procedure recursively to those
20330 other values); or re-running the code and stopping a little earlier
20331 (perhaps before the call) and stepping to better see how the variable obtained
20332 the value in question; or continuing to step @emph{from} the point of the
20333 strange value to see if code motion had simply moved the variable’s
20334 assignments later.
20335 @end itemize
20337 In light of such anomalies, a recommended technique is to use @code{-O0}
20338 early in the software development cycle, when extensive debugging capabilities
20339 are most needed, and then move to @code{-O1} and later @code{-O2} as
20340 the debugger becomes less critical.
20341 Whether to use the @code{-g} switch in the release version is
20342 a release management issue.
20343 Note that if you use @code{-g} you can then use the @code{strip} program
20344 on the resulting executable,
20345 which removes both debugging information and global symbols.
20347 @node Inlining of Subprograms,Floating Point Operations,Debugging Optimized Code,Performance Considerations
20348 @anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{187}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{102}
20349 @subsubsection Inlining of Subprograms
20352 A call to a subprogram in the current unit is inlined if all the
20353 following conditions are met:
20356 @itemize *
20358 @item 
20359 The optimization level is at least @code{-O1}.
20361 @item 
20362 The called subprogram is suitable for inlining: It must be small enough
20363 and not contain something that @code{gcc} cannot support in inlined
20364 subprograms.
20366 @geindex pragma Inline
20368 @geindex Inline
20370 @item 
20371 Any one of the following applies: @code{pragma Inline} is applied to the
20372 subprogram; the subprogram is local to the unit and called once from
20373 within it; the subprogram is small and optimization level @code{-O2} is
20374 specified; optimization level @code{-O3} is specified.
20375 @end itemize
20377 Calls to subprograms in @emph{with}ed units are normally not inlined.
20378 To achieve actual inlining (that is, replacement of the call by the code
20379 in the body of the subprogram), the following conditions must all be true:
20382 @itemize *
20384 @item 
20385 The optimization level is at least @code{-O1}.
20387 @item 
20388 The called subprogram is suitable for inlining: It must be small enough
20389 and not contain something that @code{gcc} cannot support in inlined
20390 subprograms.
20392 @item 
20393 There is a @code{pragma Inline} for the subprogram.
20395 @item 
20396 The @code{-gnatn} switch is used on the command line.
20397 @end itemize
20399 Even if all these conditions are met, it may not be possible for
20400 the compiler to inline the call, due to the length of the body,
20401 or features in the body that make it impossible for the compiler
20402 to do the inlining.
20404 Note that specifying the @code{-gnatn} switch causes additional
20405 compilation dependencies. Consider the following:
20407 @quotation
20409 @example
20410 package R is
20411    procedure Q;
20412    pragma Inline (Q);
20413 end R;
20414 package body R is
20415    ...
20416 end R;
20418 with R;
20419 procedure Main is
20420 begin
20421    ...
20422    R.Q;
20423 end Main;
20424 @end example
20425 @end quotation
20427 With the default behavior (no @code{-gnatn} switch specified), the
20428 compilation of the @code{Main} procedure depends only on its own source,
20429 @code{main.adb}, and the spec of the package in file @code{r.ads}. This
20430 means that editing the body of @code{R} does not require recompiling
20431 @code{Main}.
20433 On the other hand, the call @code{R.Q} is not inlined under these
20434 circumstances. If the @code{-gnatn} switch is present when @code{Main}
20435 is compiled, the call will be inlined if the body of @code{Q} is small
20436 enough, but now @code{Main} depends on the body of @code{R} in
20437 @code{r.adb} as well as on the spec. This means that if this body is edited,
20438 the main program must be recompiled. Note that this extra dependency
20439 occurs whether or not the call is in fact inlined by @code{gcc}.
20441 The use of front end inlining with @code{-gnatN} generates similar
20442 additional dependencies.
20444 @geindex -fno-inline (gcc)
20446 Note: The @code{-fno-inline} switch overrides all other conditions and ensures that
20447 no inlining occurs, unless requested with pragma Inline_Always for @code{gcc}
20448 back-ends. The extra dependences resulting from @code{-gnatn} will still be active,
20449 even if this switch is used to suppress the resulting inlining actions.
20451 @geindex -fno-inline-functions (gcc)
20453 Note: The @code{-fno-inline-functions} switch can be used to prevent
20454 automatic inlining of subprograms if @code{-O3} is used.
20456 @geindex -fno-inline-small-functions (gcc)
20458 Note: The @code{-fno-inline-small-functions} switch can be used to prevent
20459 automatic inlining of small subprograms if @code{-O2} is used.
20461 @geindex -fno-inline-functions-called-once (gcc)
20463 Note: The @code{-fno-inline-functions-called-once} switch
20464 can be used to prevent inlining of subprograms local to the unit
20465 and called once from within it if @code{-O1} is used.
20467 Note regarding the use of @code{-O3}: @code{-gnatn} is made up of two
20468 sub-switches @code{-gnatn1} and @code{-gnatn2} that can be directly
20469 specified in lieu of it, @code{-gnatn} being translated into one of them
20470 based on the optimization level. With @code{-O2} or below, @code{-gnatn}
20471 is equivalent to @code{-gnatn1} which activates pragma @code{Inline} with
20472 moderate inlining across modules. With @code{-O3}, @code{-gnatn} is
20473 equivalent to @code{-gnatn2} which activates pragma @code{Inline} with
20474 full inlining across modules. If you have used pragma @code{Inline} in
20475 appropriate cases, then it is usually much better to use @code{-O2}
20476 and @code{-gnatn} and avoid the use of @code{-O3} which has the additional
20477 effect of inlining subprograms you did not think should be inlined. We have
20478 found that the use of @code{-O3} may slow down the compilation and increase
20479 the code size by performing excessive inlining, leading to increased
20480 instruction cache pressure from the increased code size and thus minor
20481 performance improvements. So the bottom line here is that you should not
20482 automatically assume that @code{-O3} is better than @code{-O2}, and
20483 indeed you should use @code{-O3} only if tests show that it actually
20484 improves performance for your program.
20486 @node Floating Point Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
20487 @anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{188}@anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{189}
20488 @subsubsection Floating Point Operations
20491 @geindex Floating-Point Operations
20493 On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
20494 64-bit standard IEEE floating-point representations, and operations will
20495 use standard IEEE arithmetic as provided by the processor. On most, but
20496 not all, architectures, the attribute Machine_Overflows is False for these
20497 types, meaning that the semantics of overflow is implementation-defined.
20498 In the case of GNAT, these semantics correspond to the normal IEEE
20499 treatment of infinities and NaN (not a number) values. For example,
20500 1.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
20501 avoiding explicit overflow checks, the performance is greatly improved
20502 on many targets. However, if required, floating-point overflow can be
20503 enabled by the use of the pragma Check_Float_Overflow.
20505 Another consideration that applies specifically to x86 32-bit
20506 architectures is which form of floating-point arithmetic is used.
20507 By default the operations use the old style x86 floating-point,
20508 which implements an 80-bit extended precision form (on these
20509 architectures the type Long_Long_Float corresponds to that form).
20510 In addition, generation of efficient code in this mode means that
20511 the extended precision form will be used for intermediate results.
20512 This may be helpful in improving the final precision of a complex
20513 expression. However it means that the results obtained on the x86
20514 will be different from those on other architectures, and for some
20515 algorithms, the extra intermediate precision can be detrimental.
20517 In addition to this old-style floating-point, all modern x86 chips
20518 implement an alternative floating-point operation model referred
20519 to as SSE2. In this model there is no extended form, and furthermore
20520 execution performance is significantly enhanced. To force GNAT to use
20521 this more modern form, use both of the switches:
20523 @quotation
20525 -msse2 -mfpmath=sse
20526 @end quotation
20528 A unit compiled with these switches will automatically use the more
20529 efficient SSE2 instruction set for Float and Long_Float operations.
20530 Note that the ABI has the same form for both floating-point models,
20531 so it is permissible to mix units compiled with and without these
20532 switches.
20534 @node Vectorization of loops,Other Optimization Switches,Floating Point Operations,Performance Considerations
20535 @anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{18a}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{18b}
20536 @subsubsection Vectorization of loops
20539 @geindex Optimization Switches
20541 You can take advantage of the auto-vectorizer present in the @code{gcc}
20542 back end to vectorize loops with GNAT.  The corresponding command line switch
20543 is @code{-ftree-vectorize} but, as it is enabled by default at @code{-O3}
20544 and other aggressive optimizations helpful for vectorization also are enabled
20545 by default at this level, using @code{-O3} directly is recommended.
20547 You also need to make sure that the target architecture features a supported
20548 SIMD instruction set.  For example, for the x86 architecture, you should at
20549 least specify @code{-msse2} to get significant vectorization (but you don’t
20550 need to specify it for x86-64 as it is part of the base 64-bit architecture).
20551 Similarly, for the PowerPC architecture, you should specify @code{-maltivec}.
20553 The preferred loop form for vectorization is the @code{for} iteration scheme.
20554 Loops with a @code{while} iteration scheme can also be vectorized if they are
20555 very simple, but the vectorizer will quickly give up otherwise.  With either
20556 iteration scheme, the flow of control must be straight, in particular no
20557 @code{exit} statement may appear in the loop body.  The loop may however
20558 contain a single nested loop, if it can be vectorized when considered alone:
20560 @quotation
20562 @example
20563 A : array (1..4, 1..4) of Long_Float;
20564 S : array (1..4) of Long_Float;
20566 procedure Sum is
20567 begin
20568    for I in A'Range(1) loop
20569       for J in A'Range(2) loop
20570          S (I) := S (I) + A (I, J);
20571       end loop;
20572    end loop;
20573 end Sum;
20574 @end example
20575 @end quotation
20577 The vectorizable operations depend on the targeted SIMD instruction set, but
20578 the adding and some of the multiplying operators are generally supported, as
20579 well as the logical operators for modular types. Note that compiling
20580 with @code{-gnatp} might well reveal cases where some checks do thwart
20581 vectorization.
20583 Type conversions may also prevent vectorization if they involve semantics that
20584 are not directly supported by the code generator or the SIMD instruction set.
20585 A typical example is direct conversion from floating-point to integer types.
20586 The solution in this case is to use the following idiom:
20588 @quotation
20590 @example
20591 Integer (S'Truncation (F))
20592 @end example
20593 @end quotation
20595 if @code{S} is the subtype of floating-point object @code{F}.
20597 In most cases, the vectorizable loops are loops that iterate over arrays.
20598 All kinds of array types are supported, i.e. constrained array types with
20599 static bounds:
20601 @quotation
20603 @example
20604 type Array_Type is array (1 .. 4) of Long_Float;
20605 @end example
20606 @end quotation
20608 constrained array types with dynamic bounds:
20610 @quotation
20612 @example
20613 type Array_Type is array (1 .. Q.N) of Long_Float;
20615 type Array_Type is array (Q.K .. 4) of Long_Float;
20617 type Array_Type is array (Q.K .. Q.N) of Long_Float;
20618 @end example
20619 @end quotation
20621 or unconstrained array types:
20623 @quotation
20625 @example
20626 type Array_Type is array (Positive range <>) of Long_Float;
20627 @end example
20628 @end quotation
20630 The quality of the generated code decreases when the dynamic aspect of the
20631 array type increases, the worst code being generated for unconstrained array
20632 types.  This is so because, the less information the compiler has about the
20633 bounds of the array, the more fallback code it needs to generate in order to
20634 fix things up at run time.
20636 It is possible to specify that a given loop should be subject to vectorization
20637 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
20639 @quotation
20641 @example
20642 pragma Loop_Optimize (Vector);
20643 @end example
20644 @end quotation
20646 placed immediately within the loop will convey the appropriate hint to the
20647 compiler for this loop.
20649 It is also possible to help the compiler generate better vectorized code
20650 for a given loop by asserting that there are no loop-carried dependencies
20651 in the loop.  Consider for example the procedure:
20653 @quotation
20655 @example
20656 type Arr is array (1 .. 4) of Long_Float;
20658 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
20659 begin
20660   for I in Arr'Range loop
20661     R(I) := X(I) + Y(I);
20662   end loop;
20663 end;
20664 @end example
20665 @end quotation
20667 By default, the compiler cannot unconditionally vectorize the loop because
20668 assigning to a component of the array designated by R in one iteration could
20669 change the value read from the components of the array designated by X or Y
20670 in a later iteration.  As a result, the compiler will generate two versions
20671 of the loop in the object code, one vectorized and the other not vectorized,
20672 as well as a test to select the appropriate version at run time.  This can
20673 be overcome by another hint:
20675 @quotation
20677 @example
20678 pragma Loop_Optimize (Ivdep);
20679 @end example
20680 @end quotation
20682 placed immediately within the loop will tell the compiler that it can safely
20683 omit the non-vectorized version of the loop as well as the run-time test.
20685 @node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
20686 @anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{18c}@anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{18d}
20687 @subsubsection Other Optimization Switches
20690 @geindex Optimization Switches
20692 Since GNAT uses the @code{gcc} back end, all the specialized
20693 @code{gcc} optimization switches are potentially usable. These switches
20694 have not been extensively tested with GNAT but can generally be expected
20695 to work. Examples of switches in this category are @code{-funroll-loops}
20696 and the various target-specific @code{-m} options (in particular, it has
20697 been observed that @code{-march=xxx} can significantly improve performance
20698 on appropriate machines). For full details of these switches, see
20699 the @emph{Submodel Options} section in the @emph{Hardware Models and Configurations}
20700 chapter of @cite{Using the GNU Compiler Collection (GCC)}.
20702 @node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
20703 @anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{18e}@anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{e6}
20704 @subsubsection Optimization and Strict Aliasing
20707 @geindex Aliasing
20709 @geindex Strict Aliasing
20711 @geindex No_Strict_Aliasing
20713 The strong typing capabilities of Ada allow an optimizer to generate
20714 efficient code in situations where other languages would be forced to
20715 make worst case assumptions preventing such optimizations. Consider
20716 the following example:
20718 @quotation
20720 @example
20721 procedure R is
20722    type Int1 is new Integer;
20723    type Int2 is new Integer;
20724    type Int1A is access Int1;
20725    type Int2A is access Int2;
20726    Int1V : Int1A;
20727    Int2V : Int2A;
20728    ...
20730 begin
20731    ...
20732    for J in Data'Range loop
20733       if Data (J) = Int1V.all then
20734          Int2V.all := Int2V.all + 1;
20735       end if;
20736    end loop;
20737    ...
20738 end R;
20739 @end example
20740 @end quotation
20742 In this example, since the variable @code{Int1V} can only access objects
20743 of type @code{Int1}, and @code{Int2V} can only access objects of type
20744 @code{Int2}, there is no possibility that the assignment to
20745 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
20746 the compiler optimizer can “know” that the value @code{Int1V.all} is constant
20747 for all iterations of the loop and avoid the extra memory reference
20748 required to dereference it each time through the loop.
20750 This kind of optimization, called strict aliasing analysis, is
20751 triggered by specifying an optimization level of @code{-O2} or
20752 higher or @code{-Os} and allows GNAT to generate more efficient code
20753 when access values are involved.
20755 However, although this optimization is always correct in terms of
20756 the formal semantics of the Ada Reference Manual, difficulties can
20757 arise if features like @code{Unchecked_Conversion} are used to break
20758 the typing system. Consider the following complete program example:
20760 @quotation
20762 @example
20763 package p1 is
20764    type int1 is new integer;
20765    type int2 is new integer;
20766    type a1 is access int1;
20767    type a2 is access int2;
20768 end p1;
20770 with p1; use p1;
20771 package p2 is
20772    function to_a2 (Input : a1) return a2;
20773 end p2;
20775 with Ada.Unchecked_Conversion;
20776 package body p2 is
20777    function to_a2 (Input : a1) return a2 is
20778       function to_a2u is
20779         new Ada.Unchecked_Conversion (a1, a2);
20780    begin
20781       return to_a2u (Input);
20782    end to_a2;
20783 end p2;
20785 with p2; use p2;
20786 with p1; use p1;
20787 with Text_IO; use Text_IO;
20788 procedure m is
20789    v1 : a1 := new int1;
20790    v2 : a2 := to_a2 (v1);
20791 begin
20792    v1.all := 1;
20793    v2.all := 0;
20794    put_line (int1'image (v1.all));
20795 end;
20796 @end example
20797 @end quotation
20799 This program prints out 0 in @code{-O0} or @code{-O1}
20800 mode, but it prints out 1 in @code{-O2} mode. That’s
20801 because in strict aliasing mode, the compiler can and
20802 does assume that the assignment to @code{v2.all} could not
20803 affect the value of @code{v1.all}, since different types
20804 are involved.
20806 This behavior is not a case of non-conformance with the standard, since
20807 the Ada RM specifies that an unchecked conversion where the resulting
20808 bit pattern is not a correct value of the target type can result in an
20809 abnormal value and attempting to reference an abnormal value makes the
20810 execution of a program erroneous.  That’s the case here since the result
20811 does not point to an object of type @code{int2}.  This means that the
20812 effect is entirely unpredictable.
20814 However, although that explanation may satisfy a language
20815 lawyer, in practice an applications programmer expects an
20816 unchecked conversion involving pointers to create true
20817 aliases and the behavior of printing 1 seems plain wrong.
20818 In this case, the strict aliasing optimization is unwelcome.
20820 Indeed the compiler recognizes this possibility, and the
20821 unchecked conversion generates a warning:
20823 @quotation
20825 @example
20826 p2.adb:5:07: warning: possible aliasing problem with type "a2"
20827 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
20828 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
20829 @end example
20830 @end quotation
20832 Unfortunately the problem is recognized when compiling the body of
20833 package @code{p2}, but the actual “bad” code is generated while
20834 compiling the body of @code{m} and this latter compilation does not see
20835 the suspicious @code{Unchecked_Conversion}.
20837 As implied by the warning message, there are approaches you can use to
20838 avoid the unwanted strict aliasing optimization in a case like this.
20840 One possibility is to simply avoid the use of @code{-O2}, but
20841 that is a bit drastic, since it throws away a number of useful
20842 optimizations that do not involve strict aliasing assumptions.
20844 A less drastic approach is to compile the program using the
20845 option @code{-fno-strict-aliasing}. Actually it is only the
20846 unit containing the dereferencing of the suspicious pointer
20847 that needs to be compiled. So in this case, if we compile
20848 unit @code{m} with this switch, then we get the expected
20849 value of zero printed. Analyzing which units might need
20850 the switch can be painful, so a more reasonable approach
20851 is to compile the entire program with options @code{-O2}
20852 and @code{-fno-strict-aliasing}. If the performance is
20853 satisfactory with this combination of options, then the
20854 advantage is that the entire issue of possible “wrong”
20855 optimization due to strict aliasing is avoided.
20857 To avoid the use of compiler switches, the configuration
20858 pragma @code{No_Strict_Aliasing} with no parameters may be
20859 used to specify that for all access types, the strict
20860 aliasing optimization should be suppressed.
20862 However, these approaches are still overkill, in that they causes
20863 all manipulations of all access values to be deoptimized. A more
20864 refined approach is to concentrate attention on the specific
20865 access type identified as problematic.
20867 First, if a careful analysis of uses of the pointer shows
20868 that there are no possible problematic references, then
20869 the warning can be suppressed by bracketing the
20870 instantiation of @code{Unchecked_Conversion} to turn
20871 the warning off:
20873 @quotation
20875 @example
20876 pragma Warnings (Off);
20877 function to_a2u is
20878   new Ada.Unchecked_Conversion (a1, a2);
20879 pragma Warnings (On);
20880 @end example
20881 @end quotation
20883 Of course that approach is not appropriate for this particular
20884 example, since indeed there is a problematic reference. In this
20885 case we can take one of two other approaches.
20887 The first possibility is to move the instantiation of unchecked
20888 conversion to the unit in which the type is declared. In
20889 this example, we would move the instantiation of
20890 @code{Unchecked_Conversion} from the body of package
20891 @code{p2} to the spec of package @code{p1}. Now the
20892 warning disappears. That’s because any use of the
20893 access type knows there is a suspicious unchecked
20894 conversion, and the strict aliasing optimization
20895 is automatically suppressed for the type.
20897 If it is not practical to move the unchecked conversion to the same unit
20898 in which the destination access type is declared (perhaps because the
20899 source type is not visible in that unit), you may use pragma
20900 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
20901 same declarative sequence as the declaration of the access type:
20903 @quotation
20905 @example
20906 type a2 is access int2;
20907 pragma No_Strict_Aliasing (a2);
20908 @end example
20909 @end quotation
20911 Here again, the compiler now knows that the strict aliasing optimization
20912 should be suppressed for any reference to type @code{a2} and the
20913 expected behavior is obtained.
20915 Finally, note that although the compiler can generate warnings for
20916 simple cases of unchecked conversions, there are tricker and more
20917 indirect ways of creating type incorrect aliases which the compiler
20918 cannot detect. Examples are the use of address overlays and unchecked
20919 conversions involving composite types containing access types as
20920 components. In such cases, no warnings are generated, but there can
20921 still be aliasing problems. One safe coding practice is to forbid the
20922 use of address clauses for type overlaying, and to allow unchecked
20923 conversion only for primitive types. This is not really a significant
20924 restriction since any possible desired effect can be achieved by
20925 unchecked conversion of access values.
20927 The aliasing analysis done in strict aliasing mode can certainly
20928 have significant benefits. We have seen cases of large scale
20929 application code where the time is increased by up to 5% by turning
20930 this optimization off. If you have code that includes significant
20931 usage of unchecked conversion, you might want to just stick with
20932 @code{-O1} and avoid the entire issue. If you get adequate
20933 performance at this level of optimization level, that’s probably
20934 the safest approach. If tests show that you really need higher
20935 levels of optimization, then you can experiment with @code{-O2}
20936 and @code{-O2 -fno-strict-aliasing} to see how much effect this
20937 has on size and speed of the code. If you really need to use
20938 @code{-O2} with strict aliasing in effect, then you should
20939 review any uses of unchecked conversion of access types,
20940 particularly if you are getting the warnings described above.
20942 @node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
20943 @anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{18f}@anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{190}
20944 @subsubsection Aliased Variables and Optimization
20947 @geindex Aliasing
20949 There are scenarios in which programs may
20950 use low level techniques to modify variables
20951 that otherwise might be considered to be unassigned. For example,
20952 a variable can be passed to a procedure by reference, which takes
20953 the address of the parameter and uses the address to modify the
20954 variable’s value, even though it is passed as an IN parameter.
20955 Consider the following example:
20957 @quotation
20959 @example
20960 procedure P is
20961    Max_Length : constant Natural := 16;
20962    type Char_Ptr is access all Character;
20964    procedure Get_String(Buffer: Char_Ptr; Size : Integer);
20965    pragma Import (C, Get_String, "get_string");
20967    Name : aliased String (1 .. Max_Length) := (others => ' ');
20968    Temp : Char_Ptr;
20970    function Addr (S : String) return Char_Ptr is
20971       function To_Char_Ptr is
20972         new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
20973    begin
20974       return To_Char_Ptr (S (S'First)'Address);
20975    end;
20977 begin
20978    Temp := Addr (Name);
20979    Get_String (Temp, Max_Length);
20980 end;
20981 @end example
20982 @end quotation
20984 where Get_String is a C function that uses the address in Temp to
20985 modify the variable @code{Name}. This code is dubious, and arguably
20986 erroneous, and the compiler would be entitled to assume that
20987 @code{Name} is never modified, and generate code accordingly.
20989 However, in practice, this would cause some existing code that
20990 seems to work with no optimization to start failing at high
20991 levels of optimization.
20993 What the compiler does for such cases is to assume that marking
20994 a variable as aliased indicates that some “funny business” may
20995 be going on. The optimizer recognizes the aliased keyword and
20996 inhibits optimizations that assume the value cannot be assigned.
20997 This means that the above example will in fact “work” reliably,
20998 that is, it will produce the expected results.
21000 @node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
21001 @anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{191}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{192}
21002 @subsubsection Atomic Variables and Optimization
21005 @geindex Atomic
21007 There are two considerations with regard to performance when
21008 atomic variables are used.
21010 First, the RM only guarantees that access to atomic variables
21011 be atomic, it has nothing to say about how this is achieved,
21012 though there is a strong implication that this should not be
21013 achieved by explicit locking code. Indeed GNAT will never
21014 generate any locking code for atomic variable access (it will
21015 simply reject any attempt to make a variable or type atomic
21016 if the atomic access cannot be achieved without such locking code).
21018 That being said, it is important to understand that you cannot
21019 assume that the entire variable will always be accessed. Consider
21020 this example:
21022 @quotation
21024 @example
21025 type R is record
21026    A,B,C,D : Character;
21027 end record;
21028 for R'Size use 32;
21029 for R'Alignment use 4;
21031 RV : R;
21032 pragma Atomic (RV);
21033 X : Character;
21035 X := RV.B;
21036 @end example
21037 @end quotation
21039 You cannot assume that the reference to @code{RV.B}
21040 will read the entire 32-bit
21041 variable with a single load instruction. It is perfectly legitimate if
21042 the hardware allows it to do a byte read of just the B field. This read
21043 is still atomic, which is all the RM requires. GNAT can and does take
21044 advantage of this, depending on the architecture and optimization level.
21045 Any assumption to the contrary is non-portable and risky. Even if you
21046 examine the assembly language and see a full 32-bit load, this might
21047 change in a future version of the compiler.
21049 If your application requires that all accesses to @code{RV} in this
21050 example be full 32-bit loads, you need to make a copy for the access
21051 as in:
21053 @quotation
21055 @example
21056 declare
21057    RV_Copy : constant R := RV;
21058 begin
21059    X := RV_Copy.B;
21060 end;
21061 @end example
21062 @end quotation
21064 Now the reference to RV must read the whole variable.
21065 Actually one can imagine some compiler which figures
21066 out that the whole copy is not required (because only
21067 the B field is actually accessed), but GNAT
21068 certainly won’t do that, and we don’t know of any
21069 compiler that would not handle this right, and the
21070 above code will in practice work portably across
21071 all architectures (that permit the Atomic declaration).
21073 The second issue with atomic variables has to do with
21074 the possible requirement of generating synchronization
21075 code. For more details on this, consult the sections on
21076 the pragmas Enable/Disable_Atomic_Synchronization in the
21077 GNAT Reference Manual. If performance is critical, and
21078 such synchronization code is not required, it may be
21079 useful to disable it.
21081 @node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
21082 @anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{193}@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{194}
21083 @subsubsection Passive Task Optimization
21086 @geindex Passive Task
21088 A passive task is one which is sufficiently simple that
21089 in theory a compiler could recognize it an implement it
21090 efficiently without creating a new thread. The original design
21091 of Ada 83 had in mind this kind of passive task optimization, but
21092 only a few Ada 83 compilers attempted it. The problem was that
21093 it was difficult to determine the exact conditions under which
21094 the optimization was possible. The result is a very fragile
21095 optimization where a very minor change in the program can
21096 suddenly silently make a task non-optimizable.
21098 With the revisiting of this issue in Ada 95, there was general
21099 agreement that this approach was fundamentally flawed, and the
21100 notion of protected types was introduced. When using protected
21101 types, the restrictions are well defined, and you KNOW that the
21102 operations will be optimized, and furthermore this optimized
21103 performance is fully portable.
21105 Although it would theoretically be possible for GNAT to attempt to
21106 do this optimization, but it really doesn’t make sense in the
21107 context of Ada 95, and none of the Ada 95 compilers implement
21108 this optimization as far as we know. In particular GNAT never
21109 attempts to perform this optimization.
21111 In any new Ada 95 code that is written, you should always
21112 use protected types in place of tasks that might be able to
21113 be optimized in this manner.
21114 Of course this does not help if you have legacy Ada 83 code
21115 that depends on this optimization, but it is unusual to encounter
21116 a case where the performance gains from this optimization
21117 are significant.
21119 Your program should work correctly without this optimization. If
21120 you have performance problems, then the most practical
21121 approach is to figure out exactly where these performance problems
21122 arise, and update those particular tasks to be protected types. Note
21123 that typically clients of the tasks who call entries, will not have
21124 to be modified, only the task definition itself.
21126 @node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
21127 @anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{195}@anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{196}
21128 @subsection @code{Text_IO} Suggestions
21131 @geindex Text_IO and performance
21133 The @code{Ada.Text_IO} package has fairly high overheads due in part to
21134 the requirement of maintaining page and line counts. If performance
21135 is critical, a recommendation is to use @code{Stream_IO} instead of
21136 @code{Text_IO} for volume output, since this package has less overhead.
21138 If @code{Text_IO} must be used, note that by default output to the standard
21139 output and standard error files is unbuffered (this provides better
21140 behavior when output statements are used for debugging, or if the
21141 progress of a program is observed by tracking the output, e.g. by
21142 using the Unix @emph{tail -f} command to watch redirected output).
21144 If you are generating large volumes of output with @code{Text_IO} and
21145 performance is an important factor, use a designated file instead
21146 of the standard output file, or change the standard output file to
21147 be buffered using @code{Interfaces.C_Streams.setvbuf}.
21149 @node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
21150 @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}
21151 @subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
21154 @geindex Uunused subprogram/data elimination
21156 This section describes how you can eliminate unused subprograms and data from
21157 your executable just by setting options at compilation time.
21159 @menu
21160 * About unused subprogram/data elimination:: 
21161 * Compilation options:: 
21162 * Example of unused subprogram/data elimination:: 
21164 @end menu
21166 @node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
21167 @anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{199}@anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{19a}
21168 @subsubsection About unused subprogram/data elimination
21171 By default, an executable contains all code and data of its composing objects
21172 (directly linked or coming from statically linked libraries), even data or code
21173 never used by this executable.
21175 This feature will allow you to eliminate such unused code from your
21176 executable, making it smaller (in disk and in memory).
21178 This functionality is available on all Linux platforms except for the IA-64
21179 architecture and on all cross platforms using the ELF binary file format.
21180 In both cases GNU binutils version 2.16 or later are required to enable it.
21182 @node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
21183 @anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{19b}@anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{19c}
21184 @subsubsection Compilation options
21187 The operation of eliminating the unused code and data from the final executable
21188 is directly performed by the linker.
21190 @geindex -ffunction-sections (gcc)
21192 @geindex -fdata-sections (gcc)
21194 In order to do this, it has to work with objects compiled with the
21195 following options:
21196 @code{-ffunction-sections} @code{-fdata-sections}.
21198 These options are usable with C and Ada files.
21199 They will place respectively each
21200 function or data in a separate section in the resulting object file.
21202 Once the objects and static libraries are created with these options, the
21203 linker can perform the dead code elimination. You can do this by setting
21204 the @code{-Wl,--gc-sections} option to gcc command or in the
21205 @code{-largs} section of @code{gnatmake}. This will perform a
21206 garbage collection of code and data never referenced.
21208 If the linker performs a partial link (@code{-r} linker option), then you
21209 will need to provide the entry point using the @code{-e} / @code{--entry}
21210 linker option.
21212 Note that objects compiled without the @code{-ffunction-sections} and
21213 @code{-fdata-sections} options can still be linked with the executable.
21214 However, no dead code elimination will be performed on those objects (they will
21215 be linked as is).
21217 The GNAT static library is now compiled with -ffunction-sections and
21218 -fdata-sections on some platforms. This allows you to eliminate the unused code
21219 and data of the GNAT library from your executable.
21221 @node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
21222 @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}
21223 @subsubsection Example of unused subprogram/data elimination
21226 Here is a simple example:
21228 @quotation
21230 @example
21231 with Aux;
21233 procedure Test is
21234 begin
21235    Aux.Used (10);
21236 end Test;
21238 package Aux is
21239    Used_Data   : Integer;
21240    Unused_Data : Integer;
21242    procedure Used   (Data : Integer);
21243    procedure Unused (Data : Integer);
21244 end Aux;
21246 package body Aux is
21247    procedure Used (Data : Integer) is
21248    begin
21249       Used_Data := Data;
21250    end Used;
21252    procedure Unused (Data : Integer) is
21253    begin
21254       Unused_Data := Data;
21255    end Unused;
21256 end Aux;
21257 @end example
21258 @end quotation
21260 @code{Unused} and @code{Unused_Data} are never referenced in this code
21261 excerpt, and hence they may be safely removed from the final executable.
21263 @quotation
21265 @example
21266 $ gnatmake test
21268 $ nm test | grep used
21269 020015f0 T aux__unused
21270 02005d88 B aux__unused_data
21271 020015cc T aux__used
21272 02005d84 B aux__used_data
21274 $ gnatmake test -cargs -fdata-sections -ffunction-sections \\
21275      -largs -Wl,--gc-sections
21277 $ nm test | grep used
21278 02005350 T aux__used
21279 0201ffe0 B aux__used_data
21280 @end example
21281 @end quotation
21283 It can be observed that the procedure @code{Unused} and the object
21284 @code{Unused_Data} are removed by the linker when using the
21285 appropriate options.
21287 @geindex Overflow checks
21289 @geindex Checks (overflow)
21291 @node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
21292 @anchor{gnat_ugn/gnat_and_program_execution id45}@anchor{14b}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{19f}
21293 @section Overflow Check Handling in GNAT
21296 This section explains how to control the handling of overflow checks.
21298 @menu
21299 * Background:: 
21300 * Management of Overflows in GNAT:: 
21301 * Specifying the Desired Mode:: 
21302 * Default Settings:: 
21303 * Implementation Notes:: 
21305 @end menu
21307 @node Background,Management of Overflows in GNAT,,Overflow Check Handling in GNAT
21308 @anchor{gnat_ugn/gnat_and_program_execution background}@anchor{1a0}@anchor{gnat_ugn/gnat_and_program_execution id46}@anchor{1a1}
21309 @subsection Background
21312 Overflow checks are checks that the compiler may make to ensure
21313 that intermediate results are not out of range. For example:
21315 @quotation
21317 @example
21318 A : Integer;
21320 A := A + 1;
21321 @end example
21322 @end quotation
21324 If @code{A} has the value @code{Integer'Last}, then the addition may cause
21325 overflow since the result is out of range of the type @code{Integer}.
21326 In this case @code{Constraint_Error} will be raised if checks are
21327 enabled.
21329 A trickier situation arises in examples like the following:
21331 @quotation
21333 @example
21334 A, C : Integer;
21336 A := (A + 1) + C;
21337 @end example
21338 @end quotation
21340 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
21341 Now the final result of the expression on the right hand side is
21342 @code{Integer'Last} which is in range, but the question arises whether the
21343 intermediate addition of @code{(A + 1)} raises an overflow error.
21345 The (perhaps surprising) answer is that the Ada language
21346 definition does not answer this question. Instead it leaves
21347 it up to the implementation to do one of two things if overflow
21348 checks are enabled.
21351 @itemize *
21353 @item 
21354 raise an exception (@code{Constraint_Error}), or
21356 @item 
21357 yield the correct mathematical result which is then used in
21358 subsequent operations.
21359 @end itemize
21361 If the compiler chooses the first approach, then the assignment of this
21362 example will indeed raise @code{Constraint_Error} if overflow checking is
21363 enabled, or result in erroneous execution if overflow checks are suppressed.
21365 But if the compiler
21366 chooses the second approach, then it can perform both additions yielding
21367 the correct mathematical result, which is in range, so no exception
21368 will be raised, and the right result is obtained, regardless of whether
21369 overflow checks are suppressed.
21371 Note that in the first example an
21372 exception will be raised in either case, since if the compiler
21373 gives the correct mathematical result for the addition, it will
21374 be out of range of the target type of the assignment, and thus
21375 fails the range check.
21377 This lack of specified behavior in the handling of overflow for
21378 intermediate results is a source of non-portability, and can thus
21379 be problematic when programs are ported. Most typically this arises
21380 in a situation where the original compiler did not raise an exception,
21381 and then the application is moved to a compiler where the check is
21382 performed on the intermediate result and an unexpected exception is
21383 raised.
21385 Furthermore, when using Ada 2012’s preconditions and other
21386 assertion forms, another issue arises. Consider:
21388 @quotation
21390 @example
21391 procedure P (A, B : Integer) with
21392   Pre => A + B <= Integer'Last;
21393 @end example
21394 @end quotation
21396 One often wants to regard arithmetic in a context like this from
21397 a mathematical point of view. So for example, if the two actual parameters
21398 for a call to @code{P} are both @code{Integer'Last}, then
21399 the precondition should be regarded as False. If we are executing
21400 in a mode with run-time checks enabled for preconditions, then we would
21401 like this precondition to fail, rather than raising an exception
21402 because of the intermediate overflow.
21404 However, the language definition leaves the specification of
21405 whether the above condition fails (raising @code{Assert_Error}) or
21406 causes an intermediate overflow (raising @code{Constraint_Error})
21407 up to the implementation.
21409 The situation is worse in a case such as the following:
21411 @quotation
21413 @example
21414 procedure Q (A, B, C : Integer) with
21415   Pre => A + B + C <= Integer'Last;
21416 @end example
21417 @end quotation
21419 Consider the call
21421 @quotation
21423 @example
21424 Q (A => Integer'Last, B => 1, C => -1);
21425 @end example
21426 @end quotation
21428 From a mathematical point of view the precondition
21429 is True, but at run time we may (but are not guaranteed to) get an
21430 exception raised because of the intermediate overflow (and we really
21431 would prefer this precondition to be considered True at run time).
21433 @node Management of Overflows in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
21434 @anchor{gnat_ugn/gnat_and_program_execution id47}@anchor{1a2}@anchor{gnat_ugn/gnat_and_program_execution management-of-overflows-in-gnat}@anchor{1a3}
21435 @subsection Management of Overflows in GNAT
21438 To deal with the portability issue, and with the problem of
21439 mathematical versus run-time interpretation of the expressions in
21440 assertions, GNAT provides comprehensive control over the handling
21441 of intermediate overflow. GNAT can operate in three modes, and
21442 furthermore, permits separate selection of operating modes for
21443 the expressions within assertions (here the term ‘assertions’
21444 is used in the technical sense, which includes preconditions and so forth)
21445 and for expressions appearing outside assertions.
21447 The three modes are:
21450 @itemize *
21452 @item 
21453 @emph{Use base type for intermediate operations} (@code{STRICT})
21455 In this mode, all intermediate results for predefined arithmetic
21456 operators are computed using the base type, and the result must
21457 be in range of the base type. If this is not the
21458 case then either an exception is raised (if overflow checks are
21459 enabled) or the execution is erroneous (if overflow checks are suppressed).
21460 This is the normal default mode.
21462 @item 
21463 @emph{Most intermediate overflows avoided} (@code{MINIMIZED})
21465 In this mode, the compiler attempts to avoid intermediate overflows by
21466 using a larger integer type, typically @code{Long_Long_Integer},
21467 as the type in which arithmetic is
21468 performed for predefined arithmetic operators. This may be slightly more
21469 expensive at
21470 run time (compared to suppressing intermediate overflow checks), though
21471 the cost is negligible on modern 64-bit machines. For the examples given
21472 earlier, no intermediate overflows would have resulted in exceptions,
21473 since the intermediate results are all in the range of
21474 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
21475 of GNAT). In addition, if checks are enabled, this reduces the number of
21476 checks that must be made, so this choice may actually result in an
21477 improvement in space and time behavior.
21479 However, there are cases where @code{Long_Long_Integer} is not large
21480 enough, consider the following example:
21482 @quotation
21484 @example
21485 procedure R (A, B, C, D : Integer) with
21486   Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
21487 @end example
21488 @end quotation
21490 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
21491 Now the intermediate results are
21492 out of the range of @code{Long_Long_Integer} even though the final result
21493 is in range and the precondition is True (from a mathematical point
21494 of view). In such a case, operating in this mode, an overflow occurs
21495 for the intermediate computation (which is why this mode
21496 says @emph{most} intermediate overflows are avoided). In this case,
21497 an exception is raised if overflow checks are enabled, and the
21498 execution is erroneous if overflow checks are suppressed.
21500 @item 
21501 @emph{All intermediate overflows avoided} (@code{ELIMINATED})
21503 In this mode, the compiler  avoids all intermediate overflows
21504 by using arbitrary precision arithmetic as required. In this
21505 mode, the above example with @code{A**2 * B**2} would
21506 not cause intermediate overflow, because the intermediate result
21507 would be evaluated using sufficient precision, and the result
21508 of evaluating the precondition would be True.
21510 This mode has the advantage of avoiding any intermediate
21511 overflows, but at the expense of significant run-time overhead,
21512 including the use of a library (included automatically in this
21513 mode) for multiple-precision arithmetic.
21515 This mode provides cleaner semantics for assertions, since now
21516 the run-time behavior emulates true arithmetic behavior for the
21517 predefined arithmetic operators, meaning that there is never a
21518 conflict between the mathematical view of the assertion, and its
21519 run-time behavior.
21521 Note that in this mode, the behavior is unaffected by whether or
21522 not overflow checks are suppressed, since overflow does not occur.
21523 It is possible for gigantic intermediate expressions to raise
21524 @code{Storage_Error} as a result of attempting to compute the
21525 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
21526 but overflow is impossible.
21527 @end itemize
21529 Note that these modes apply only to the evaluation of predefined
21530 arithmetic, membership, and comparison operators for signed integer
21531 arithmetic.
21533 For fixed-point arithmetic, checks can be suppressed. But if checks
21534 are enabled
21535 then fixed-point values are always checked for overflow against the
21536 base type for intermediate expressions (that is such checks always
21537 operate in the equivalent of @code{STRICT} mode).
21539 For floating-point, on nearly all architectures, @code{Machine_Overflows}
21540 is False, and IEEE infinities are generated, so overflow exceptions
21541 are never raised. If you want to avoid infinities, and check that
21542 final results of expressions are in range, then you can declare a
21543 constrained floating-point type, and range checks will be carried
21544 out in the normal manner (with infinite values always failing all
21545 range checks).
21547 @node Specifying the Desired Mode,Default Settings,Management of Overflows in GNAT,Overflow Check Handling in GNAT
21548 @anchor{gnat_ugn/gnat_and_program_execution id48}@anchor{1a4}@anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{eb}
21549 @subsection Specifying the Desired Mode
21552 @geindex pragma Overflow_Mode
21554 The desired mode of for handling intermediate overflow can be specified using
21555 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
21556 The pragma has the form
21558 @quotation
21560 @example
21561 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
21562 @end example
21563 @end quotation
21565 where @code{MODE} is one of
21568 @itemize *
21570 @item 
21571 @code{STRICT}:  intermediate overflows checked (using base type)
21573 @item 
21574 @code{MINIMIZED}: minimize intermediate overflows
21576 @item 
21577 @code{ELIMINATED}: eliminate intermediate overflows
21578 @end itemize
21580 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
21581 @code{minimized} all have the same effect.
21583 If only the @code{General} parameter is present, then the given @code{MODE} applies
21584 to expressions both within and outside assertions. If both arguments
21585 are present, then @code{General} applies to expressions outside assertions,
21586 and @code{Assertions} applies to expressions within assertions. For example:
21588 @quotation
21590 @example
21591 pragma Overflow_Mode
21592   (General => Minimized, Assertions => Eliminated);
21593 @end example
21594 @end quotation
21596 specifies that general expressions outside assertions be evaluated
21597 in ‘minimize intermediate overflows’ mode, and expressions within
21598 assertions be evaluated in ‘eliminate intermediate overflows’ mode.
21599 This is often a reasonable choice, avoiding excessive overhead
21600 outside assertions, but assuring a high degree of portability
21601 when importing code from another compiler, while incurring
21602 the extra overhead for assertion expressions to ensure that
21603 the behavior at run time matches the expected mathematical
21604 behavior.
21606 The @code{Overflow_Mode} pragma has the same scoping and placement
21607 rules as pragma @code{Suppress}, so it can occur either as a
21608 configuration pragma, specifying a default for the whole
21609 program, or in a declarative scope, where it applies to the
21610 remaining declarations and statements in that scope.
21612 Note that pragma @code{Overflow_Mode} does not affect whether
21613 overflow checks are enabled or suppressed. It only controls the
21614 method used to compute intermediate values. To control whether
21615 overflow checking is enabled or suppressed, use pragma @code{Suppress}
21616 or @code{Unsuppress} in the usual manner.
21618 @geindex -gnato? (gcc)
21620 @geindex -gnato?? (gcc)
21622 Additionally, a compiler switch @code{-gnato?} or @code{-gnato??}
21623 can be used to control the checking mode default (which can be subsequently
21624 overridden using pragmas).
21626 Here @code{?} is one of the digits @code{1} through @code{3}:
21628 @quotation
21631 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
21632 @item
21634 @code{1}
21636 @tab
21638 use base type for intermediate operations (@code{STRICT})
21640 @item
21642 @code{2}
21644 @tab
21646 minimize intermediate overflows (@code{MINIMIZED})
21648 @item
21650 @code{3}
21652 @tab
21654 eliminate intermediate overflows (@code{ELIMINATED})
21656 @end multitable
21658 @end quotation
21660 As with the pragma, if only one digit appears then it applies to all
21661 cases; if two digits are given, then the first applies outside
21662 assertions, and the second within assertions. Thus the equivalent
21663 of the example pragma above would be
21664 @code{-gnato23}.
21666 If no digits follow the @code{-gnato}, then it is equivalent to
21667 @code{-gnato11},
21668 causing all intermediate operations to be computed using the base
21669 type (@code{STRICT} mode).
21671 @node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
21672 @anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{1a5}@anchor{gnat_ugn/gnat_and_program_execution id49}@anchor{1a6}
21673 @subsection Default Settings
21676 The default mode for overflow checks is
21678 @quotation
21680 @example
21681 General => Strict
21682 @end example
21683 @end quotation
21685 which causes all computations both inside and outside assertions to use the
21686 base type, and is equivalent to @code{-gnato} (with no digits following).
21688 The pragma @code{Suppress (Overflow_Check)} disables overflow
21689 checking, but it has no effect on the method used for computing
21690 intermediate results.
21692 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
21693 checking, but it has no effect on the method used for computing
21694 intermediate results.
21696 @node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
21697 @anchor{gnat_ugn/gnat_and_program_execution id50}@anchor{1a7}@anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{1a8}
21698 @subsection Implementation Notes
21701 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
21702 reasonably efficient, and can be generally used. It also helps
21703 to ensure compatibility with code imported from some other
21704 compiler to GNAT.
21706 Setting all intermediate overflows checking (@code{STRICT} mode)
21707 makes sense if you want to
21708 make sure that your code is compatible with any other possible
21709 Ada implementation. This may be useful in ensuring portability
21710 for code that is to be exported to some other compiler than GNAT.
21712 The Ada standard allows the reassociation of expressions at
21713 the same precedence level if no parentheses are present. For
21714 example, @code{A+B+C} parses as though it were @code{(A+B)+C}, but
21715 the compiler can reintepret this as @code{A+(B+C)}, possibly
21716 introducing or eliminating an overflow exception. The GNAT
21717 compiler never takes advantage of this freedom, and the
21718 expression @code{A+B+C} will be evaluated as @code{(A+B)+C}.
21719 If you need the other order, you can write the parentheses
21720 explicitly @code{A+(B+C)} and GNAT will respect this order.
21722 The use of @code{ELIMINATED} mode will cause the compiler to
21723 automatically include an appropriate arbitrary precision
21724 integer arithmetic package. The compiler will make calls
21725 to this package, though only in cases where it cannot be
21726 sure that @code{Long_Long_Integer} is sufficient to guard against
21727 intermediate overflows. This package does not use dynamic
21728 allocation, but it does use the secondary stack, so an
21729 appropriate secondary stack package must be present (this
21730 is always true for standard full Ada, but may require
21731 specific steps for restricted run times such as ZFP).
21733 Although @code{ELIMINATED} mode causes expressions to use arbitrary
21734 precision arithmetic, avoiding overflow, the final result
21735 must be in an appropriate range. This is true even if the
21736 final result is of type @code{[Long_[Long_]]Integer'Base}, which
21737 still has the same bounds as its associated constrained
21738 type at run-time.
21740 Currently, the @code{ELIMINATED} mode is only available on target
21741 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
21742 platforms).
21744 @node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
21745 @anchor{gnat_ugn/gnat_and_program_execution id51}@anchor{14c}@anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{1a9}
21746 @section Performing Dimensionality Analysis in GNAT
21749 @geindex Dimensionality analysis
21751 The GNAT compiler supports dimensionality checking. The user can
21752 specify physical units for objects, and the compiler will verify that uses
21753 of these objects are compatible with their dimensions, in a fashion that is
21754 familiar to engineering practice. The dimensions of algebraic expressions
21755 (including powers with static exponents) are computed from their constituents.
21757 @geindex Dimension_System aspect
21759 @geindex Dimension aspect
21761 This feature depends on Ada 2012 aspect specifications, and is available from
21762 version 7.0.1 of GNAT onwards.
21763 The GNAT-specific aspect @code{Dimension_System}
21764 allows you to define a system of units; the aspect @code{Dimension}
21765 then allows the user to declare dimensioned quantities within a given system.
21766 (These aspects are described in the @emph{Implementation Defined Aspects}
21767 chapter of the @emph{GNAT Reference Manual}).
21769 The major advantage of this model is that it does not require the declaration of
21770 multiple operators for all possible combinations of types: it is only necessary
21771 to use the proper subtypes in object declarations.
21773 @geindex System.Dim.Mks package (GNAT library)
21775 @geindex MKS_Type type
21777 The simplest way to impose dimensionality checking on a computation is to make
21778 use of one of the instantiations of the package @code{System.Dim.Generic_Mks}, which
21779 are part of the GNAT library. This generic package defines a floating-point
21780 type @code{MKS_Type}, for which a sequence of dimension names are specified,
21781 together with their conventional abbreviations.  The following should be read
21782 together with the full specification of the package, in file
21783 @code{s-digemk.ads}.
21785 @quotation
21787 @geindex s-digemk.ads file
21789 @example
21790 type Mks_Type is new Float_Type
21791   with
21792    Dimension_System => (
21793      (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
21794      (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
21795      (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
21796      (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
21797      (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
21798      (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
21799      (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
21800 @end example
21801 @end quotation
21803 The package then defines a series of subtypes that correspond to these
21804 conventional units. For example:
21806 @quotation
21808 @example
21809 subtype Length is Mks_Type
21810   with
21811    Dimension => (Symbol => 'm', Meter  => 1, others => 0);
21812 @end example
21813 @end quotation
21815 and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
21816 @code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
21817 @code{Luminous_Intensity} (the standard set of units of the SI system).
21819 The package also defines conventional names for values of each unit, for
21820 example:
21822 @quotation
21824 @example
21825 m   : constant Length           := 1.0;
21826 kg  : constant Mass             := 1.0;
21827 s   : constant Time             := 1.0;
21828 A   : constant Electric_Current := 1.0;
21829 @end example
21830 @end quotation
21832 as well as useful multiples of these units:
21834 @quotation
21836 @example
21837  cm  : constant Length := 1.0E-02;
21838  g   : constant Mass   := 1.0E-03;
21839  min : constant Time   := 60.0;
21840  day : constant Time   := 60.0 * 24.0 * min;
21842 @end example
21843 @end quotation
21845 There are three instantiations of @code{System.Dim.Generic_Mks} defined in the
21846 GNAT library:
21849 @itemize *
21851 @item 
21852 @code{System.Dim.Float_Mks} based on @code{Float} defined in @code{s-diflmk.ads}.
21854 @item 
21855 @code{System.Dim.Long_Mks} based on @code{Long_Float} defined in @code{s-dilomk.ads}.
21857 @item 
21858 @code{System.Dim.Mks} based on @code{Long_Long_Float} defined in @code{s-dimmks.ads}.
21859 @end itemize
21861 Using one of these packages, you can then define a derived unit by providing
21862 the aspect that specifies its dimensions within the MKS system, as well as the
21863 string to be used for output of a value of that unit:
21865 @quotation
21867 @example
21868 subtype Acceleration is Mks_Type
21869   with Dimension => ("m/sec^2",
21870                      Meter => 1,
21871                      Second => -2,
21872                      others => 0);
21873 @end example
21874 @end quotation
21876 Here is a complete example of use:
21878 @quotation
21880 @example
21881 with System.Dim.MKS; use System.Dim.Mks;
21882 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
21883 with Text_IO; use Text_IO;
21884 procedure Free_Fall is
21885   subtype Acceleration is Mks_Type
21886     with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
21887   G : constant acceleration := 9.81 * m / (s ** 2);
21888   T : Time := 10.0*s;
21889   Distance : Length;
21891 begin
21892   Put ("Gravitational constant: ");
21893   Put (G, Aft => 2, Exp => 0); Put_Line ("");
21894   Distance := 0.5 * G * T ** 2;
21895   Put ("distance travelled in 10 seconds of free fall ");
21896   Put (Distance, Aft => 2, Exp => 0);
21897   Put_Line ("");
21898 end Free_Fall;
21899 @end example
21900 @end quotation
21902 Execution of this program yields:
21904 @quotation
21906 @example
21907 Gravitational constant:  9.81 m/sec^2
21908 distance travelled in 10 seconds of free fall 490.50 m
21909 @end example
21910 @end quotation
21912 However, incorrect assignments such as:
21914 @quotation
21916 @example
21917 Distance := 5.0;
21918 Distance := 5.0 * kg;
21919 @end example
21920 @end quotation
21922 are rejected with the following diagnoses:
21924 @quotation
21926 @example
21927 Distance := 5.0;
21928    >>> dimensions mismatch in assignment
21929    >>> left-hand side has dimension [L]
21930    >>> right-hand side is dimensionless
21932 Distance := 5.0 * kg:
21933    >>> dimensions mismatch in assignment
21934    >>> left-hand side has dimension [L]
21935    >>> right-hand side has dimension [M]
21936 @end example
21937 @end quotation
21939 The dimensions of an expression are properly displayed, even if there is
21940 no explicit subtype for it. If we add to the program:
21942 @quotation
21944 @example
21945 Put ("Final velocity: ");
21946 Put (G * T, Aft =>2, Exp =>0);
21947 Put_Line ("");
21948 @end example
21949 @end quotation
21951 then the output includes:
21953 @quotation
21955 @example
21956 Final velocity: 98.10 m.s**(-1)
21957 @end example
21959 @geindex Dimensionable type
21961 @geindex Dimensioned subtype
21962 @end quotation
21964 The type @code{Mks_Type} is said to be a @emph{dimensionable type} since it has a
21965 @code{Dimension_System} aspect, and the subtypes @code{Length}, @code{Mass}, etc.,
21966 are said to be @emph{dimensioned subtypes} since each one has a @code{Dimension}
21967 aspect.
21969 @quotation
21971 @geindex Dimension Vector (for a dimensioned subtype)
21973 @geindex Dimension aspect
21975 @geindex Dimension_System aspect
21976 @end quotation
21978 The @code{Dimension} aspect of a dimensioned subtype @code{S} defines a mapping
21979 from the base type’s Unit_Names to integer (or, more generally, rational)
21980 values. This mapping is the @emph{dimension vector} (also referred to as the
21981 @emph{dimensionality}) for that subtype, denoted by @code{DV(S)}, and thus for each
21982 object of that subtype. Intuitively, the value specified for each
21983 @code{Unit_Name} is the exponent associated with that unit; a zero value
21984 means that the unit is not used. For example:
21986 @quotation
21988 @example
21989 declare
21990    Acc : Acceleration;
21991    ...
21992 begin
21993    ...
21994 end;
21995 @end example
21996 @end quotation
21998 Here @code{DV(Acc)} = @code{DV(Acceleration)} =
21999 @code{(Meter=>1, Kilogram=>0, Second=>-2, Ampere=>0, Kelvin=>0, Mole=>0, Candela=>0)}.
22000 Symbolically, we can express this as @code{Meter / Second**2}.
22002 The dimension vector of an arithmetic expression is synthesized from the
22003 dimension vectors of its components, with compile-time dimensionality checks
22004 that help prevent mismatches such as using an @code{Acceleration} where a
22005 @code{Length} is required.
22007 The dimension vector of the result of an arithmetic expression @emph{expr}, or
22008 @code{DV(@emph{expr})}, is defined as follows, assuming conventional
22009 mathematical definitions for the vector operations that are used:
22012 @itemize *
22014 @item 
22015 If @emph{expr} is of the type @emph{universal_real}, or is not of a dimensioned subtype,
22016 then @emph{expr} is dimensionless; @code{DV(@emph{expr})} is the empty vector.
22018 @item 
22019 @code{DV(@emph{op expr})}, where @emph{op} is a unary operator, is @code{DV(@emph{expr})}
22021 @item 
22022 @code{DV(@emph{expr1 op expr2})} where @emph{op} is “+” or “-” is @code{DV(@emph{expr1})}
22023 provided that @code{DV(@emph{expr1})} = @code{DV(@emph{expr2})}.
22024 If this condition is not met then the construct is illegal.
22026 @item 
22027 @code{DV(@emph{expr1} * @emph{expr2})} is @code{DV(@emph{expr1})} + @code{DV(@emph{expr2})},
22028 and @code{DV(@emph{expr1} / @emph{expr2})} = @code{DV(@emph{expr1})} - @code{DV(@emph{expr2})}.
22029 In this context if one of the @emph{expr}s is dimensionless then its empty
22030 dimension vector is treated as @code{(others => 0)}.
22032 @item 
22033 @code{DV(@emph{expr} ** @emph{power})} is @emph{power} * @code{DV(@emph{expr})},
22034 provided that @emph{power} is a static rational value. If this condition is not
22035 met then the construct is illegal.
22036 @end itemize
22038 Note that, by the above rules, it is illegal to use binary “+” or “-” to
22039 combine a dimensioned and dimensionless value.  Thus an expression such as
22040 @code{acc-10.0} is illegal, where @code{acc} is an object of subtype
22041 @code{Acceleration}.
22043 The dimensionality checks for relationals use the same rules as
22044 for “+” and “-”, except when comparing to a literal; thus
22046 @quotation
22048 @example
22049 acc > len
22050 @end example
22051 @end quotation
22053 is equivalent to
22055 @quotation
22057 @example
22058 acc-len > 0.0
22059 @end example
22060 @end quotation
22062 and is thus illegal, but
22064 @quotation
22066 @example
22067 acc > 10.0
22068 @end example
22069 @end quotation
22071 is accepted with a warning. Analogously a conditional expression requires the
22072 same dimension vector for each branch (with no exception for literals).
22074 The dimension vector of a type conversion @code{T(@emph{expr})} is defined
22075 as follows, based on the nature of @code{T}:
22078 @itemize *
22080 @item 
22081 If @code{T} is a dimensioned subtype then @code{DV(T(@emph{expr}))} is @code{DV(T)}
22082 provided that either @emph{expr} is dimensionless or
22083 @code{DV(T)} = @code{DV(@emph{expr})}. The conversion is illegal
22084 if @emph{expr} is dimensioned and @code{DV(@emph{expr})} /= @code{DV(T)}.
22085 Note that vector equality does not require that the corresponding
22086 Unit_Names be the same.
22088 As a consequence of the above rule, it is possible to convert between
22089 different dimension systems that follow the same international system
22090 of units, with the seven physical components given in the standard order
22091 (length, mass, time, etc.). Thus a length in meters can be converted to
22092 a length in inches (with a suitable conversion factor) but cannot be
22093 converted, for example, to a mass in pounds.
22095 @item 
22096 If @code{T} is the base type for @emph{expr} (and the dimensionless root type of
22097 the dimension system), then @code{DV(T(@emph{expr}))} is @code{DV(expr)}.
22098 Thus, if @emph{expr} is of a dimensioned subtype of @code{T}, the conversion may
22099 be regarded as a “view conversion” that preserves dimensionality.
22101 This rule makes it possible to write generic code that can be instantiated
22102 with compatible dimensioned subtypes.  The generic unit will contain
22103 conversions that will consequently be present in instantiations, but
22104 conversions to the base type will preserve dimensionality and make it
22105 possible to write generic code that is correct with respect to
22106 dimensionality.
22108 @item 
22109 Otherwise (i.e., @code{T} is neither a dimensioned subtype nor a dimensionable
22110 base type), @code{DV(T(@emph{expr}))} is the empty vector. Thus a dimensioned
22111 value can be explicitly converted to a non-dimensioned subtype, which
22112 of course then escapes dimensionality analysis.
22113 @end itemize
22115 The dimension vector for a type qualification @code{T'(@emph{expr})} is the same
22116 as for the type conversion @code{T(@emph{expr})}.
22118 An assignment statement
22120 @quotation
22122 @example
22123 Source := Target;
22124 @end example
22125 @end quotation
22127 requires @code{DV(Source)} = @code{DV(Target)}, and analogously for parameter
22128 passing (the dimension vector for the actual parameter must be equal to the
22129 dimension vector for the formal parameter).
22131 When using dimensioned types with elementary functions it is necessary to
22132 instantiate the @code{Ada.Numerics.Generic_Elementary_Functions} package using
22133 the @code{Mks_Type} and not any of the derived subtypes such as @code{Distance}.
22134 For functions such as @code{Sqrt} the dimensional analysis will fail when using
22135 the subtypes because both the parameter and return are of the same type.
22137 An example instantiation
22139 @quotation
22141 @example
22142 package Mks_Numerics is new
22143    Ada.Numerics.Generic_Elementary_Functions (System.Dim.Mks.Mks_Type);
22144 @end example
22145 @end quotation
22147 @node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
22148 @anchor{gnat_ugn/gnat_and_program_execution id52}@anchor{14d}@anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{1aa}
22149 @section Stack Related Facilities
22152 This section describes some useful tools associated with stack
22153 checking and analysis. In
22154 particular, it deals with dynamic and static stack usage measurements.
22156 @menu
22157 * Stack Overflow Checking:: 
22158 * Static Stack Usage Analysis:: 
22159 * Dynamic Stack Usage Analysis:: 
22161 @end menu
22163 @node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
22164 @anchor{gnat_ugn/gnat_and_program_execution id53}@anchor{1ab}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{e7}
22165 @subsection Stack Overflow Checking
22168 @geindex Stack Overflow Checking
22170 @geindex -fstack-check (gcc)
22172 For most operating systems, @code{gcc} does not perform stack overflow
22173 checking by default. This means that if the main environment task or
22174 some other task exceeds the available stack space, then unpredictable
22175 behavior will occur. Most native systems offer some level of protection by
22176 adding a guard page at the end of each task stack. This mechanism is usually
22177 not enough for dealing properly with stack overflow situations because
22178 a large local variable could “jump” above the guard page.
22179 Furthermore, when the
22180 guard page is hit, there may not be any space left on the stack for executing
22181 the exception propagation code. Enabling stack checking avoids
22182 such situations.
22184 To activate stack checking, compile all units with the @code{gcc} option
22185 @code{-fstack-check}. For example:
22187 @quotation
22189 @example
22190 $ gcc -c -fstack-check package1.adb
22191 @end example
22192 @end quotation
22194 Units compiled with this option will generate extra instructions to check
22195 that any use of the stack (for procedure calls or for declaring local
22196 variables in declare blocks) does not exceed the available stack space.
22197 If the space is exceeded, then a @code{Storage_Error} exception is raised.
22199 For declared tasks, the default stack size is defined by the GNAT runtime,
22200 whose size may be modified at bind time through the @code{-d} bind switch
22201 (@ref{112,,Switches for gnatbind}). Task specific stack sizes may be set using the
22202 @code{Storage_Size} pragma.
22204 For the environment task, the stack size is determined by the operating system.
22205 Consequently, to modify the size of the environment task please refer to your
22206 operating system documentation.
22208 @node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
22209 @anchor{gnat_ugn/gnat_and_program_execution id54}@anchor{1ac}@anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{e8}
22210 @subsection Static Stack Usage Analysis
22213 @geindex Static Stack Usage Analysis
22215 @geindex -fstack-usage
22217 A unit compiled with @code{-fstack-usage} will generate an extra file
22218 that specifies
22219 the maximum amount of stack used, on a per-function basis.
22220 The file has the same
22221 basename as the target object file with a @code{.su} extension.
22222 Each line of this file is made up of three fields:
22225 @itemize *
22227 @item 
22228 The name of the function.
22230 @item 
22231 A number of bytes.
22233 @item 
22234 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
22235 @end itemize
22237 The second field corresponds to the size of the known part of the function
22238 frame.
22240 The qualifier @code{static} means that the function frame size
22241 is purely static.
22242 It usually means that all local variables have a static size.
22243 In this case, the second field is a reliable measure of the function stack
22244 utilization.
22246 The qualifier @code{dynamic} means that the function frame size is not static.
22247 It happens mainly when some local variables have a dynamic size. When this
22248 qualifier appears alone, the second field is not a reliable measure
22249 of the function stack analysis. When it is qualified with  @code{bounded}, it
22250 means that the second field is a reliable maximum of the function stack
22251 utilization.
22253 A unit compiled with @code{-Wstack-usage} will issue a warning for each
22254 subprogram whose stack usage might be larger than the specified amount of
22255 bytes.  The wording is in keeping with the qualifier documented above.
22257 @node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
22258 @anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{115}@anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{1ad}
22259 @subsection Dynamic Stack Usage Analysis
22262 It is possible to measure the maximum amount of stack used by a task, by
22263 adding a switch to @code{gnatbind}, as:
22265 @quotation
22267 @example
22268 $ gnatbind -u0 file
22269 @end example
22270 @end quotation
22272 With this option, at each task termination, its stack usage is output on
22273 @code{stderr}.
22274 Note that this switch is not compatible with tools like
22275 Valgrind and DrMemory; they will report errors.
22277 It is not always convenient to output the stack usage when the program
22278 is still running. Hence, it is possible to delay this output until program
22279 termination. for a given number of tasks specified as the argument of the
22280 @code{-u} option. For instance:
22282 @quotation
22284 @example
22285 $ gnatbind -u100 file
22286 @end example
22287 @end quotation
22289 will buffer the stack usage information of the first 100 tasks to terminate and
22290 output this info at program termination. Results are displayed in four
22291 columns:
22293 @quotation
22295 @example
22296 Index | Task Name | Stack Size | Stack Usage
22297 @end example
22298 @end quotation
22300 where:
22303 @itemize *
22305 @item 
22306 @emph{Index} is a number associated with each task.
22308 @item 
22309 @emph{Task Name} is the name of the task analyzed.
22311 @item 
22312 @emph{Stack Size} is the maximum size for the stack.
22314 @item 
22315 @emph{Stack Usage} is the measure done by the stack analyzer.
22316 In order to prevent overflow, the stack
22317 is not entirely analyzed, and it’s not possible to know exactly how
22318 much has actually been used.
22319 @end itemize
22321 By default the environment task stack, the stack that contains the main unit,
22322 is not processed. To enable processing of the environment task stack, the
22323 environment variable GNAT_STACK_LIMIT needs to be set to the maximum size of
22324 the environment task stack. This amount is given in kilobytes. For example:
22326 @quotation
22328 @example
22329 $ set GNAT_STACK_LIMIT 1600
22330 @end example
22331 @end quotation
22333 would specify to the analyzer that the environment task stack has a limit
22334 of 1.6 megabytes. Any stack usage beyond this will be ignored by the analysis.
22336 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
22337 stack-usage reports at run time. See its body for the details.
22339 @node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
22340 @anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{14e}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{1ae}
22341 @section Memory Management Issues
22344 This section describes some useful memory pools provided in the GNAT library
22345 and in particular the GNAT Debug Pool facility, which can be used to detect
22346 incorrect uses of access values (including ‘dangling references’).
22349 @menu
22350 * Some Useful Memory Pools:: 
22351 * The GNAT Debug Pool Facility:: 
22353 @end menu
22355 @node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
22356 @anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{1af}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{1b0}
22357 @subsection Some Useful Memory Pools
22360 @geindex Memory Pool
22362 @geindex storage
22363 @geindex pool
22365 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
22366 storage pool. Allocations use the standard system call @code{malloc} while
22367 deallocations use the standard system call @code{free}. No reclamation is
22368 performed when the pool goes out of scope. For performance reasons, the
22369 standard default Ada allocators/deallocators do not use any explicit storage
22370 pools but if they did, they could use this storage pool without any change in
22371 behavior. That is why this storage pool is used  when the user
22372 manages to make the default implicit allocator explicit as in this example:
22374 @quotation
22376 @example
22377 type T1 is access Something;
22378  -- no Storage pool is defined for T2
22380 type T2 is access Something_Else;
22381 for T2'Storage_Pool use T1'Storage_Pool;
22382 -- the above is equivalent to
22383 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
22384 @end example
22385 @end quotation
22387 The @code{System.Pool_Local} package offers the @code{Unbounded_Reclaim_Pool} storage
22388 pool. The allocation strategy is similar to @code{Pool_Local}
22389 except that the all
22390 storage allocated with this pool is reclaimed when the pool object goes out of
22391 scope. This pool provides a explicit mechanism similar to the implicit one
22392 provided by several Ada 83 compilers for allocations performed through a local
22393 access type and whose purpose was to reclaim memory when exiting the
22394 scope of a given local access. As an example, the following program does not
22395 leak memory even though it does not perform explicit deallocation:
22397 @quotation
22399 @example
22400 with System.Pool_Local;
22401 procedure Pooloc1 is
22402    procedure Internal is
22403       type A is access Integer;
22404       X : System.Pool_Local.Unbounded_Reclaim_Pool;
22405       for A'Storage_Pool use X;
22406       v : A;
22407    begin
22408       for I in 1 .. 50 loop
22409          v := new Integer;
22410       end loop;
22411    end Internal;
22412 begin
22413    for I in 1 .. 100 loop
22414       Internal;
22415    end loop;
22416 end Pooloc1;
22417 @end example
22418 @end quotation
22420 The @code{System.Pool_Size} package implements the @code{Stack_Bounded_Pool} used when
22421 @code{Storage_Size} is specified for an access type.
22422 The whole storage for the pool is
22423 allocated at once, usually on the stack at the point where the access type is
22424 elaborated. It is automatically reclaimed when exiting the scope where the
22425 access type is defined. This package is not intended to be used directly by the
22426 user and it is implicitly used for each such declaration:
22428 @quotation
22430 @example
22431 type T1 is access Something;
22432 for T1'Storage_Size use 10_000;
22433 @end example
22434 @end quotation
22436 @node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
22437 @anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{1b1}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{1b2}
22438 @subsection The GNAT Debug Pool Facility
22441 @geindex Debug Pool
22443 @geindex storage
22444 @geindex pool
22445 @geindex memory corruption
22447 The use of unchecked deallocation and unchecked conversion can easily
22448 lead to incorrect memory references. The problems generated by such
22449 references are usually difficult to tackle because the symptoms can be
22450 very remote from the origin of the problem. In such cases, it is
22451 very helpful to detect the problem as early as possible. This is the
22452 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
22454 In order to use the GNAT specific debugging pool, the user must
22455 associate a debug pool object with each of the access types that may be
22456 related to suspected memory problems. See Ada Reference Manual 13.11.
22458 @quotation
22460 @example
22461 type Ptr is access Some_Type;
22462 Pool : GNAT.Debug_Pools.Debug_Pool;
22463 for Ptr'Storage_Pool use Pool;
22464 @end example
22465 @end quotation
22467 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
22468 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
22469 allow the user to redefine allocation and deallocation strategies. They
22470 also provide a checkpoint for each dereference, through the use of
22471 the primitive operation @code{Dereference} which is implicitly called at
22472 each dereference of an access value.
22474 Once an access type has been associated with a debug pool, operations on
22475 values of the type may raise four distinct exceptions,
22476 which correspond to four potential kinds of memory corruption:
22479 @itemize *
22481 @item 
22482 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
22484 @item 
22485 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
22487 @item 
22488 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
22490 @item 
22491 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
22492 @end itemize
22494 For types associated with a Debug_Pool, dynamic allocation is performed using
22495 the standard GNAT allocation routine. References to all allocated chunks of
22496 memory are kept in an internal dictionary. Several deallocation strategies are
22497 provided, whereupon the user can choose to release the memory to the system,
22498 keep it allocated for further invalid access checks, or fill it with an easily
22499 recognizable pattern for debug sessions. The memory pattern is the old IBM
22500 hexadecimal convention: @code{16#DEADBEEF#}.
22502 See the documentation in the file g-debpoo.ads for more information on the
22503 various strategies.
22505 Upon each dereference, a check is made that the access value denotes a
22506 properly allocated memory location. Here is a complete example of use of
22507 @code{Debug_Pools}, that includes typical instances of  memory corruption:
22509 @quotation
22511 @example
22512 with GNAT.IO; use GNAT.IO;
22513 with Ada.Unchecked_Deallocation;
22514 with Ada.Unchecked_Conversion;
22515 with GNAT.Debug_Pools;
22516 with System.Storage_Elements;
22517 with Ada.Exceptions; use Ada.Exceptions;
22518 procedure Debug_Pool_Test is
22520    type T is access Integer;
22521    type U is access all T;
22523    P : GNAT.Debug_Pools.Debug_Pool;
22524    for T'Storage_Pool use P;
22526    procedure Free is new Ada.Unchecked_Deallocation (Integer, T);
22527    function UC is new Ada.Unchecked_Conversion (U, T);
22528    A, B : aliased T;
22530    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
22532 begin
22533    Info (P);
22534    A := new Integer;
22535    B := new Integer;
22536    B := A;
22537    Info (P);
22538    Free (A);
22539    begin
22540       Put_Line (Integer'Image(B.all));
22541    exception
22542       when E : others => Put_Line ("raised: " & Exception_Name (E));
22543    end;
22544    begin
22545       Free (B);
22546    exception
22547       when E : others => Put_Line ("raised: " & Exception_Name (E));
22548    end;
22549    B := UC(A'Access);
22550    begin
22551       Put_Line (Integer'Image(B.all));
22552    exception
22553       when E : others => Put_Line ("raised: " & Exception_Name (E));
22554    end;
22555    begin
22556       Free (B);
22557    exception
22558       when E : others => Put_Line ("raised: " & Exception_Name (E));
22559    end;
22560    Info (P);
22561 end Debug_Pool_Test;
22562 @end example
22563 @end quotation
22565 The debug pool mechanism provides the following precise diagnostics on the
22566 execution of this erroneous program:
22568 @quotation
22570 @example
22571 Debug Pool info:
22572   Total allocated bytes :  0
22573   Total deallocated bytes :  0
22574   Current Water Mark:  0
22575   High Water Mark:  0
22577 Debug Pool info:
22578   Total allocated bytes :  8
22579   Total deallocated bytes :  0
22580   Current Water Mark:  8
22581   High Water Mark:  8
22583 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
22584 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
22585 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
22586 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
22587 Debug Pool info:
22588   Total allocated bytes :  8
22589   Total deallocated bytes :  4
22590   Current Water Mark:  4
22591   High Water Mark:  8
22592 @end example
22593 @end quotation
22596 @c -- Non-breaking space in running text
22597 @c -- E.g. Ada |nbsp| 95
22599 @node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
22600 @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}
22601 @chapter Platform-Specific Information
22604 This appendix contains information relating to the implementation
22605 of run-time libraries on various platforms and also covers topics
22606 related to the GNAT implementation on specific Operating Systems.
22608 @menu
22609 * Run-Time Libraries:: 
22610 * Specifying a Run-Time Library:: 
22611 * GNU/Linux Topics:: 
22612 * Microsoft Windows Topics:: 
22613 * Mac OS Topics:: 
22615 @end menu
22617 @node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
22618 @anchor{gnat_ugn/platform_specific_information id2}@anchor{1b5}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{1b6}
22619 @section Run-Time Libraries
22622 @geindex Tasking and threads libraries
22624 @geindex Threads libraries and tasking
22626 @geindex Run-time libraries (platform-specific information)
22628 The GNAT run-time implementation may vary with respect to both the
22629 underlying threads library and the exception-handling scheme.
22630 For threads support, the default run-time will bind to the thread
22631 package of the underlying operating system.
22633 For exception handling, either or both of two models are supplied:
22635 @quotation
22637 @geindex Zero-Cost Exceptions
22639 @geindex ZCX (Zero-Cost Exceptions)
22640 @end quotation
22643 @itemize *
22645 @item 
22646 @strong{Zero-Cost Exceptions} (“ZCX”),
22647 which uses binder-generated tables that
22648 are interrogated at run time to locate a handler.
22650 @geindex setjmp/longjmp Exception Model
22652 @geindex SJLJ (setjmp/longjmp Exception Model)
22654 @item 
22655 @strong{setjmp / longjmp} (‘SJLJ’),
22656 which uses dynamically-set data to establish
22657 the set of handlers
22658 @end itemize
22660 Most programs should experience a substantial speed improvement by
22661 being compiled with a ZCX run-time.
22662 This is especially true for
22663 tasking applications or applications with many exception handlers.
22664 Note however that the ZCX run-time does not support asynchronous abort
22665 of tasks (@code{abort} and @code{select-then-abort} constructs) and will instead
22666 implement abort by polling points in the runtime. You can also add additional
22667 polling points explicitly if needed in your application via @code{pragma
22668 Abort_Defer}.
22670 This section summarizes which combinations of threads and exception support
22671 are supplied on various GNAT platforms.
22673 @menu
22674 * Summary of Run-Time Configurations:: 
22676 @end menu
22678 @node Summary of Run-Time Configurations,,,Run-Time Libraries
22679 @anchor{gnat_ugn/platform_specific_information id3}@anchor{1b7}@anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{1b8}
22680 @subsection Summary of Run-Time Configurations
22684 @multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
22685 @headitem
22687 Platform
22689 @tab
22691 Run-Time
22693 @tab
22695 Tasking
22697 @tab
22699 Exceptions
22701 @item
22703 GNU/Linux
22705 @tab
22707 rts-native
22708 (default)
22710 @tab
22712 pthread library
22714 @tab
22718 @item
22720 rts-sjlj
22722 @tab
22724 pthread library
22726 @tab
22728 SJLJ
22730 @item
22732 Windows
22734 @tab
22736 rts-native
22737 (default)
22739 @tab
22741 native Win32 threads
22743 @tab
22747 @item
22749 rts-sjlj
22751 @tab
22753 native Win32 threads
22755 @tab
22757 SJLJ
22759 @item
22761 Mac OS
22763 @tab
22765 rts-native
22767 @tab
22769 pthread library
22771 @tab
22775 @end multitable
22778 @node Specifying a Run-Time Library,GNU/Linux Topics,Run-Time Libraries,Platform-Specific Information
22779 @anchor{gnat_ugn/platform_specific_information id4}@anchor{1b9}@anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{1ba}
22780 @section Specifying a Run-Time Library
22783 The @code{adainclude} subdirectory containing the sources of the GNAT
22784 run-time library, and the @code{adalib} subdirectory containing the
22785 @code{ALI} files and the static and/or shared GNAT library, are located
22786 in the gcc target-dependent area:
22788 @quotation
22790 @example
22791 target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
22792 @end example
22793 @end quotation
22795 As indicated above, on some platforms several run-time libraries are supplied.
22796 These libraries are installed in the target dependent area and
22797 contain a complete source and binary subdirectory. The detailed description
22798 below explains the differences between the different libraries in terms of
22799 their thread support.
22801 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22802 This default run-time is selected by the means of soft links.
22803 For example on x86-linux:
22805 @c --
22806 @c --  $(target-dir)
22807 @c --      |
22808 @c --      +--- adainclude----------+
22809 @c --      |                        |
22810 @c --      +--- adalib-----------+  |
22811 @c --      |                     |  |
22812 @c --      +--- rts-native       |  |
22813 @c --      |    |                |  |
22814 @c --      |    +--- adainclude <---+
22815 @c --      |    |                |
22816 @c --      |    +--- adalib <----+
22817 @c --      |
22818 @c --      +--- rts-sjlj
22819 @c --           |
22820 @c --           +--- adainclude
22821 @c --           |
22822 @c --           +--- adalib
22825 @example
22826                $(target-dir)
22827               __/ /      \ \___
22828       _______/   /        \    \_________________
22829      /          /          \                     \
22830     /          /            \                     \
22831 ADAINCLUDE  ADALIB      rts-native             rts-sjlj
22832    :          :            /    \                 /   \
22833    :          :           /      \               /     \
22834    :          :          /        \             /       \
22835    :          :         /          \           /         \
22836    +-------------> adainclude     adalib   adainclude   adalib
22837               :                     ^
22838               :                     :
22839               +---------------------+
22841               Run-Time Library Directory Structure
22842    (Upper-case names and dotted/dashed arrows represent soft links)
22843 @end example
22845 If the @emph{rts-sjlj} library is to be selected on a permanent basis,
22846 these soft links can be modified with the following commands:
22848 @quotation
22850 @example
22851 $ cd $target
22852 $ rm -f adainclude adalib
22853 $ ln -s rts-sjlj/adainclude adainclude
22854 $ ln -s rts-sjlj/adalib adalib
22855 @end example
22856 @end quotation
22858 Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
22859 @code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
22860 @code{$target/ada_object_path}.
22862 @geindex --RTS option
22864 Selecting another run-time library temporarily can be
22865 achieved by using the @code{--RTS} switch, e.g., @code{--RTS=sjlj}
22866 @anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy}@anchor{1bb}
22867 @geindex SCHED_FIFO scheduling policy
22869 @geindex SCHED_RR scheduling policy
22871 @geindex SCHED_OTHER scheduling policy
22873 @menu
22874 * Choosing the Scheduling Policy:: 
22876 @end menu
22878 @node Choosing the Scheduling Policy,,,Specifying a Run-Time Library
22879 @anchor{gnat_ugn/platform_specific_information id5}@anchor{1bc}
22880 @subsection Choosing the Scheduling Policy
22883 When using a POSIX threads implementation, you have a choice of several
22884 scheduling policies: @code{SCHED_FIFO}, @code{SCHED_RR} and @code{SCHED_OTHER}.
22886 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22887 or @code{SCHED_RR} requires special (e.g., root) privileges.
22889 @geindex pragma Time_Slice
22891 @geindex -T0 option
22893 @geindex pragma Task_Dispatching_Policy
22895 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22896 @code{SCHED_FIFO},
22897 you can use one of the following:
22900 @itemize *
22902 @item 
22903 @code{pragma Time_Slice (0.0)}
22905 @item 
22906 the corresponding binder option @code{-T0}
22908 @item 
22909 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22910 @end itemize
22912 To specify @code{SCHED_RR},
22913 you should use @code{pragma Time_Slice} with a
22914 value greater than 0.0, or else use the corresponding @code{-T}
22915 binder option.
22917 To make sure a program is running as root, you can put something like
22918 this in a library package body in your application:
22920 @quotation
22922 @example
22923 function geteuid return Integer;
22924 pragma Import (C, geteuid, "geteuid");
22925 Ignore : constant Boolean :=
22926   (if geteuid = 0 then True else raise Program_Error with "must be root");
22927 @end example
22928 @end quotation
22930 It gets the effective user id, and if it’s not 0 (i.e. root), it raises
22931 Program_Error. Note that if you re running the code in a container, this may
22932 not be sufficient, as you may have sufficient priviledge on the container,
22933 but not on the host machine running the container, so check that you also
22934 have sufficient priviledge for running the container image.
22936 @geindex Linux
22938 @geindex GNU/Linux
22940 @node GNU/Linux Topics,Microsoft Windows Topics,Specifying a Run-Time Library,Platform-Specific Information
22941 @anchor{gnat_ugn/platform_specific_information gnu-linux-topics}@anchor{1bd}@anchor{gnat_ugn/platform_specific_information id6}@anchor{1be}
22942 @section GNU/Linux Topics
22945 This section describes topics that are specific to GNU/Linux platforms.
22947 @menu
22948 * Required Packages on GNU/Linux:: 
22949 * Position Independent Executable (PIE) Enabled by Default on Linux: Position Independent Executable PIE Enabled by Default on Linux. 
22950 * A GNU/Linux Debug Quirk:: 
22952 @end menu
22954 @node Required Packages on GNU/Linux,Position Independent Executable PIE Enabled by Default on Linux,,GNU/Linux Topics
22955 @anchor{gnat_ugn/platform_specific_information id7}@anchor{1bf}@anchor{gnat_ugn/platform_specific_information required-packages-on-gnu-linux}@anchor{1c0}
22956 @subsection Required Packages on GNU/Linux
22959 GNAT requires the C library developer’s package to be installed.
22960 The name of of that package depends on your GNU/Linux distribution:
22963 @itemize *
22965 @item 
22966 RedHat, SUSE: @code{glibc-devel};
22968 @item 
22969 Debian, Ubuntu: @code{libc6-dev} (normally installed by default).
22970 @end itemize
22972 If using the 32-bit version of GNAT on a 64-bit version of GNU/Linux,
22973 you’ll need the 32-bit version of the following packages:
22976 @itemize *
22978 @item 
22979 RedHat, SUSE: @code{glibc.i686}, @code{glibc-devel.i686}, @code{ncurses-libs.i686}
22981 @item 
22982 SUSE: @code{glibc-locale-base-32bit}
22984 @item 
22985 Debian, Ubuntu: @code{libc6:i386}, @code{libc6-dev:i386}, @code{lib32ncursesw5}
22986 @end itemize
22988 Other GNU/Linux distributions might be choosing a different name
22989 for those packages.
22991 @node Position Independent Executable PIE Enabled by Default on Linux,A GNU/Linux Debug Quirk,Required Packages on GNU/Linux,GNU/Linux Topics
22992 @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}
22993 @subsection Position Independent Executable (PIE) Enabled by Default on Linux
22996 GNAT generates Position Independent Executable (PIE) code by default.
22997 PIE binaries are loaded into random memory locations, introducing
22998 an additional layer of protection against attacks.
23000 Building PIE binaries requires that all of their dependencies also be
23001 built as Position Independent. If the link of your project fails with
23002 an error like:
23004 @example
23005 /[...]/ld: /path/to/object/file: relocation R_X86_64_32S against symbol
23006 `symbol name' can not be used when making a PIE object;
23007 recompile with -fPIE
23008 @end example
23010 it means the identified object file has not been built as Position
23011 Independent.
23013 If you are not interested in building PIE binaries, you can simply
23014 turn this feature off by first compiling your code with @code{-fno-pie}
23015 and then by linking with @code{-no-pie} (note the subtle but important
23016 difference in the names of the options – the linker option does @strong{not}
23017 have an @cite{f} after the dash!). When using gprbuild, this is
23018 achieved by updating the @emph{Required_Switches} attribute in package @cite{Compiler}
23019 and, depending on your type of project, either attribute @emph{Switches}
23020 or attribute @emph{Library_Options} in package @cite{Linker}.
23022 On the other hand, if you would like to build PIE binaries and you are
23023 getting the error above, a quick and easy workaround to allow linking
23024 to succeed again is to disable PIE during the link, thus temporarily
23025 lifting the requirement that all dependencies also be Position
23026 Independent code. To do so, you simply need to add @code{-no-pie} to
23027 the list of switches passed to the linker. As part of this workaround,
23028 there is no need to adjust the compiler switches.
23030 From there, to be able to link your binaries with PIE and therefore
23031 drop the @code{-no-pie} workaround, you’ll need to get the identified
23032 dependencies rebuilt with PIE enabled (compiled with @code{-fPIE}
23033 and linked with @code{-pie}).
23035 @node A GNU/Linux Debug Quirk,,Position Independent Executable PIE Enabled by Default on Linux,GNU/Linux Topics
23036 @anchor{gnat_ugn/platform_specific_information a-gnu-linux-debug-quirk}@anchor{1c3}@anchor{gnat_ugn/platform_specific_information id8}@anchor{1c4}
23037 @subsection A GNU/Linux Debug Quirk
23040 On SuSE 15, some kernels have a defect causing issues when debugging
23041 programs using threads or Ada tasks. Due to the lack of documentation
23042 found regarding this kernel issue, we can only provide limited
23043 information about which kernels are impacted: kernel version 5.3.18 is
23044 known to be impacted, and kernels in the 5.14 range or newer are
23045 believed to fix this problem.
23047 The bug affects the debugging of 32-bit processes on a 64-bit system.
23048 Symptoms can vary: Unexpected @code{SIGABRT} signals being received by
23049 the program, “The futex facility returned an unexpected error code”
23050 error message, and inferior programs hanging indefinitely range among
23051 the symptoms most commonly observed.
23053 @geindex Windows
23055 @node Microsoft Windows Topics,Mac OS Topics,GNU/Linux Topics,Platform-Specific Information
23056 @anchor{gnat_ugn/platform_specific_information id9}@anchor{1c5}@anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{1c6}
23057 @section Microsoft Windows Topics
23060 This section describes topics that are specific to the Microsoft Windows
23061 platforms.
23064 @menu
23065 * Using GNAT on Windows:: 
23066 * Using a network installation of GNAT:: 
23067 * CONSOLE and WINDOWS subsystems:: 
23068 * Temporary Files:: 
23069 * Disabling Command Line Argument Expansion:: 
23070 * Windows Socket Timeouts:: 
23071 * Mixed-Language Programming on Windows:: 
23072 * Windows Specific Add-Ons:: 
23074 @end menu
23076 @node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
23077 @anchor{gnat_ugn/platform_specific_information id10}@anchor{1c7}@anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{1c8}
23078 @subsection Using GNAT on Windows
23081 One of the strengths of the GNAT technology is that its tool set
23082 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
23083 @code{gdb} debugger, etc.) is used in the same way regardless of the
23084 platform.
23086 On Windows this tool set is complemented by a number of Microsoft-specific
23087 tools that have been provided to facilitate interoperability with Windows
23088 when this is required. With these tools:
23091 @itemize *
23093 @item 
23094 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
23095 subsystems.
23097 @item 
23098 You can use any Dynamically Linked Library (DLL) in your Ada code (both
23099 relocatable and non-relocatable DLLs are supported).
23101 @item 
23102 You can build Ada DLLs for use in other applications. These applications
23103 can be written in a language other than Ada (e.g., C, C++, etc). Again both
23104 relocatable and non-relocatable Ada DLLs are supported.
23106 @item 
23107 You can include Windows resources in your Ada application.
23109 @item 
23110 You can use or create COM/DCOM objects.
23111 @end itemize
23113 Immediately below are listed all known general GNAT-for-Windows restrictions.
23114 Other restrictions about specific features like Windows Resources and DLLs
23115 are listed in separate sections below.
23118 @itemize *
23120 @item 
23121 It is not possible to use @code{GetLastError} and @code{SetLastError}
23122 when tasking, protected records, or exceptions are used. In these
23123 cases, in order to implement Ada semantics, the GNAT run-time system
23124 calls certain Win32 routines that set the last error variable to 0 upon
23125 success. It should be possible to use @code{GetLastError} and
23126 @code{SetLastError} when tasking, protected record, and exception
23127 features are not used, but it is not guaranteed to work.
23129 @item 
23130 It is not possible to link against Microsoft C++ libraries except for
23131 import libraries. Interfacing must be done by the mean of DLLs.
23133 @item 
23134 It is possible to link against Microsoft C libraries. Yet the preferred
23135 solution is to use C/C++ compiler that comes with GNAT, since it
23136 doesn’t require having two different development environments and makes the
23137 inter-language debugging experience smoother.
23139 @item 
23140 When the compilation environment is located on FAT32 drives, users may
23141 experience recompilations of the source files that have not changed if
23142 Daylight Saving Time (DST) state has changed since the last time files
23143 were compiled. NTFS drives do not have this problem.
23145 @item 
23146 No components of the GNAT toolset use any entries in the Windows
23147 registry. The only entries that can be created are file associations and
23148 PATH settings, provided the user has chosen to create them at installation
23149 time, as well as some minimal book-keeping information needed to correctly
23150 uninstall or integrate different GNAT products.
23151 @end itemize
23153 @node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
23154 @anchor{gnat_ugn/platform_specific_information id11}@anchor{1c9}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{1ca}
23155 @subsection Using a network installation of GNAT
23158 Make sure the system on which GNAT is installed is accessible from the
23159 current machine, i.e., the install location is shared over the network.
23160 Shared resources are accessed on Windows by means of UNC paths, which
23161 have the format @code{\\\\server\\sharename\\path}
23163 In order to use such a network installation, simply add the UNC path of the
23164 @code{bin} directory of your GNAT installation in front of your PATH. For
23165 example, if GNAT is installed in @code{\GNAT} directory of a share location
23166 called @code{c-drive} on a machine @code{LOKI}, the following command will
23167 make it available:
23169 @quotation
23171 @example
23172 $ path \\loki\c-drive\gnat\bin;%path%`
23173 @end example
23174 @end quotation
23176 Be aware that every compilation using the network installation results in the
23177 transfer of large amounts of data across the network and will likely cause
23178 serious performance penalty.
23180 @node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
23181 @anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{1cb}@anchor{gnat_ugn/platform_specific_information id12}@anchor{1cc}
23182 @subsection CONSOLE and WINDOWS subsystems
23185 @geindex CONSOLE Subsystem
23187 @geindex WINDOWS Subsystem
23189 @geindex -mwindows
23191 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
23192 (which is the default subsystem) will always create a console when
23193 launching the application. This is not something desirable when the
23194 application has a Windows GUI. To get rid of this console the
23195 application must be using the @code{WINDOWS} subsystem. To do so
23196 the @code{-mwindows} linker option must be specified.
23198 @quotation
23200 @example
23201 $ gnatmake winprog -largs -mwindows
23202 @end example
23203 @end quotation
23205 @node Temporary Files,Disabling Command Line Argument Expansion,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
23206 @anchor{gnat_ugn/platform_specific_information id13}@anchor{1cd}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{1ce}
23207 @subsection Temporary Files
23210 @geindex Temporary files
23212 It is possible to control where temporary files gets created by setting
23213 the 
23214 @geindex TMP
23215 @geindex environment variable; TMP
23216 @code{TMP} environment variable. The file will be created:
23219 @itemize *
23221 @item 
23222 Under the directory pointed to by the 
23223 @geindex TMP
23224 @geindex environment variable; TMP
23225 @code{TMP} environment variable if
23226 this directory exists.
23228 @item 
23229 Under @code{c:\temp}, if the 
23230 @geindex TMP
23231 @geindex environment variable; TMP
23232 @code{TMP} environment variable is not
23233 set (or not pointing to a directory) and if this directory exists.
23235 @item 
23236 Under the current working directory otherwise.
23237 @end itemize
23239 This allows you to determine exactly where the temporary
23240 file will be created. This is particularly useful in networked
23241 environments where you may not have write access to some
23242 directories.
23244 @node Disabling Command Line Argument Expansion,Windows Socket Timeouts,Temporary Files,Microsoft Windows Topics
23245 @anchor{gnat_ugn/platform_specific_information disabling-command-line-argument-expansion}@anchor{1cf}
23246 @subsection Disabling Command Line Argument Expansion
23249 @geindex Command Line Argument Expansion
23251 By default, an executable compiled for the Windows platform will do
23252 the following postprocessing on the arguments passed on the command
23253 line:
23256 @itemize *
23258 @item 
23259 If the argument contains the characters @code{*} and/or @code{?}, then
23260 file expansion will be attempted. For example, if the current directory
23261 contains @code{a.txt} and @code{b.txt}, then when calling:
23263 @example
23264 $ my_ada_program *.txt
23265 @end example
23267 The following arguments will effectively be passed to the main program
23268 (for example when using @code{Ada.Command_Line.Argument}):
23270 @example
23271 Ada.Command_Line.Argument (1) -> "a.txt"
23272 Ada.Command_Line.Argument (2) -> "b.txt"
23273 @end example
23275 @item 
23276 Filename expansion can be disabled for a given argument by using single
23277 quotes. Thus, calling:
23279 @example
23280 $ my_ada_program '*.txt'
23281 @end example
23283 will result in:
23285 @example
23286 Ada.Command_Line.Argument (1) -> "*.txt"
23287 @end example
23288 @end itemize
23290 Note that if the program is launched from a shell such as Cygwin Bash
23291 then quote removal might be performed by the shell.
23293 In some contexts it might be useful to disable this feature (for example if
23294 the program performs its own argument expansion). In order to do this, a C
23295 symbol needs to be defined and set to @code{0}. You can do this by
23296 adding the following code fragment in one of your Ada units:
23298 @example
23299 Do_Argv_Expansion : Integer := 0;
23300 pragma Export (C, Do_Argv_Expansion, "__gnat_do_argv_expansion");
23301 @end example
23303 The results of previous examples will be respectively:
23305 @example
23306 Ada.Command_Line.Argument (1) -> "*.txt"
23307 @end example
23309 and:
23311 @example
23312 Ada.Command_Line.Argument (1) -> "'*.txt'"
23313 @end example
23315 @node Windows Socket Timeouts,Mixed-Language Programming on Windows,Disabling Command Line Argument Expansion,Microsoft Windows Topics
23316 @anchor{gnat_ugn/platform_specific_information windows-socket-timeouts}@anchor{1d0}
23317 @subsection Windows Socket Timeouts
23320 Microsoft Windows desktops older than @code{8.0} and Microsoft Windows Servers
23321 older than @code{2019} set a socket timeout 500 milliseconds longer than the value
23322 set by setsockopt with @code{SO_RCVTIMEO} and @code{SO_SNDTIMEO} options. The GNAT
23323 runtime makes a correction for the difference in the corresponding Windows
23324 versions. For Windows Server starting with version @code{2019}, the user must
23325 provide a manifest file for the GNAT runtime to be able to recognize that
23326 the Windows version does not need the timeout correction. The manifest file
23327 should be located in the same directory as the executable file, and its file
23328 name must match the executable name suffixed by @code{.manifest}. For example,
23329 if the executable name is @code{sock_wto.exe}, then the manifest file name
23330 has to be @code{sock_wto.exe.manifest}. The manifest file must contain at
23331 least the following data:
23333 @example
23334 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
23335 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
23336 <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
23337 <application>
23338    <!-- Windows Vista -->
23339    <supportedOS Id="@{e2011457-1546-43c5-a5fe-008deee3d3f0@}"/>
23340    <!-- Windows 7 -->
23341    <supportedOS Id="@{35138b9a-5d96-4fbd-8e2d-a2440225f93a@}"/>
23342    <!-- Windows 8 -->
23343    <supportedOS Id="@{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38@}"/>
23344    <!-- Windows 8.1 -->
23345    <supportedOS Id="@{1f676c76-80e1-4239-95bb-83d0f6d0da78@}"/>
23346    <!-- Windows 10 -->
23347    <supportedOS Id="@{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a@}"/>
23348 </application>
23349 </compatibility>
23350 </assembly>
23351 @end example
23353 Without the manifest file, the socket timeout is going to be overcorrected on
23354 these Windows Server versions and the actual time is going to be 500
23355 milliseconds shorter than what was set with GNAT.Sockets.Set_Socket_Option.
23356 Note that on Microsoft Windows versions where correction is necessary, there
23357 is no way to set a socket timeout shorter than 500 ms. If a socket timeout
23358 shorter than 500 ms is needed on these Windows versions, a call to
23359 Check_Selector should be added before any socket read or write operations.
23361 @node Mixed-Language Programming on Windows,Windows Specific Add-Ons,Windows Socket Timeouts,Microsoft Windows Topics
23362 @anchor{gnat_ugn/platform_specific_information id14}@anchor{1d1}@anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{1d2}
23363 @subsection Mixed-Language Programming on Windows
23366 Developing pure Ada applications on Windows is no different than on
23367 other GNAT-supported platforms. However, when developing or porting an
23368 application that contains a mix of Ada and C/C++, the choice of your
23369 Windows C/C++ development environment conditions your overall
23370 interoperability strategy.
23372 If you use @code{gcc} or Microsoft C to compile the non-Ada part of
23373 your application, there are no Windows-specific restrictions that
23374 affect the overall interoperability with your Ada code. If you do want
23375 to use the Microsoft tools for your C++ code, you have two choices:
23378 @itemize *
23380 @item 
23381 Encapsulate your C++ code in a DLL to be linked with your Ada
23382 application. In this case, use the Microsoft or whatever environment to
23383 build the DLL and use GNAT to build your executable
23384 (@ref{1d3,,Using DLLs with GNAT}).
23386 @item 
23387 Or you can encapsulate your Ada code in a DLL to be linked with the
23388 other part of your application. In this case, use GNAT to build the DLL
23389 (@ref{1d4,,Building DLLs with GNAT Project files}) and use the Microsoft
23390 or whatever environment to build your executable.
23391 @end itemize
23393 In addition to the description about C main in
23394 @ref{2c,,Mixed Language Programming} section, if the C main uses a
23395 stand-alone library it is required on x86-windows to
23396 setup the SEH context. For this the C main must looks like this:
23398 @quotation
23400 @example
23401 /* main.c */
23402 extern void adainit (void);
23403 extern void adafinal (void);
23404 extern void __gnat_initialize(void*);
23405 extern void call_to_ada (void);
23407 int main (int argc, char *argv[])
23409   int SEH [2];
23411   /* Initialize the SEH context */
23412   __gnat_initialize (&SEH);
23414   adainit();
23416   /* Then call Ada services in the stand-alone library */
23418   call_to_ada();
23420   adafinal();
23422 @end example
23423 @end quotation
23425 Note that this is not needed on x86_64-windows where the Windows
23426 native SEH support is used.
23428 @menu
23429 * Windows Calling Conventions:: 
23430 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
23431 * Using DLLs with GNAT:: 
23432 * Building DLLs with GNAT Project files:: 
23433 * Building DLLs with GNAT:: 
23434 * Building DLLs with gnatdll:: 
23435 * Ada DLLs and Finalization:: 
23436 * Creating a Spec for Ada DLLs:: 
23437 * GNAT and Windows Resources:: 
23438 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
23439 * Debugging a DLL:: 
23440 * Setting Stack Size from gnatlink:: 
23441 * Setting Heap Size from gnatlink:: 
23443 @end menu
23445 @node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
23446 @anchor{gnat_ugn/platform_specific_information id15}@anchor{1d5}@anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{1d6}
23447 @subsubsection Windows Calling Conventions
23450 @geindex Stdcall
23452 @geindex APIENTRY
23454 This section pertain only to Win32. On Win64 there is a single native
23455 calling convention. All convention specifiers are ignored on this
23456 platform.
23458 When a subprogram @code{F} (caller) calls a subprogram @code{G}
23459 (callee), there are several ways to push @code{G}‘s parameters on the
23460 stack and there are several possible scenarios to clean up the stack
23461 upon @code{G}‘s return. A calling convention is an agreed upon software
23462 protocol whereby the responsibilities between the caller (@code{F}) and
23463 the callee (@code{G}) are clearly defined. Several calling conventions
23464 are available for Windows:
23467 @itemize *
23469 @item 
23470 @code{C} (Microsoft defined)
23472 @item 
23473 @code{Stdcall} (Microsoft defined)
23475 @item 
23476 @code{Win32} (GNAT specific)
23478 @item 
23479 @code{DLL} (GNAT specific)
23480 @end itemize
23482 @menu
23483 * C Calling Convention:: 
23484 * Stdcall Calling Convention:: 
23485 * Win32 Calling Convention:: 
23486 * DLL Calling Convention:: 
23488 @end menu
23490 @node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
23491 @anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{1d7}@anchor{gnat_ugn/platform_specific_information id16}@anchor{1d8}
23492 @subsubsection @code{C} Calling Convention
23495 This is the default calling convention used when interfacing to C/C++
23496 routines compiled with either @code{gcc} or Microsoft Visual C++.
23498 In the @code{C} calling convention subprogram parameters are pushed on the
23499 stack by the caller from right to left. The caller itself is in charge of
23500 cleaning up the stack after the call. In addition, the name of a routine
23501 with @code{C} calling convention is mangled by adding a leading underscore.
23503 The name to use on the Ada side when importing (or exporting) a routine
23504 with @code{C} calling convention is the name of the routine. For
23505 instance the C function:
23507 @quotation
23509 @example
23510 int get_val (long);
23511 @end example
23512 @end quotation
23514 should be imported from Ada as follows:
23516 @quotation
23518 @example
23519 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23520 pragma Import (C, Get_Val, External_Name => "get_val");
23521 @end example
23522 @end quotation
23524 Note that in this particular case the @code{External_Name} parameter could
23525 have been omitted since, when missing, this parameter is taken to be the
23526 name of the Ada entity in lower case. When the @code{Link_Name} parameter
23527 is missing, as in the above example, this parameter is set to be the
23528 @code{External_Name} with a leading underscore.
23530 When importing a variable defined in C, you should always use the @code{C}
23531 calling convention unless the object containing the variable is part of a
23532 DLL (in which case you should use the @code{Stdcall} calling
23533 convention, @ref{1d9,,Stdcall Calling Convention}).
23535 @node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
23536 @anchor{gnat_ugn/platform_specific_information id17}@anchor{1da}@anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{1d9}
23537 @subsubsection @code{Stdcall} Calling Convention
23540 This convention, which was the calling convention used for Pascal
23541 programs, is used by Microsoft for all the routines in the Win32 API for
23542 efficiency reasons. It must be used to import any routine for which this
23543 convention was specified.
23545 In the @code{Stdcall} calling convention subprogram parameters are pushed
23546 on the stack by the caller from right to left. The callee (and not the
23547 caller) is in charge of cleaning the stack on routine exit. In addition,
23548 the name of a routine with @code{Stdcall} calling convention is mangled by
23549 adding a leading underscore (as for the @code{C} calling convention) and a
23550 trailing @code{@@@emph{nn}}, where @code{nn} is the overall size (in
23551 bytes) of the parameters passed to the routine.
23553 The name to use on the Ada side when importing a C routine with a
23554 @code{Stdcall} calling convention is the name of the C routine. The leading
23555 underscore and trailing @code{@@@emph{nn}} are added automatically by
23556 the compiler. For instance the Win32 function:
23558 @quotation
23560 @example
23561 APIENTRY int get_val (long);
23562 @end example
23563 @end quotation
23565 should be imported from Ada as follows:
23567 @quotation
23569 @example
23570 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23571 pragma Import (Stdcall, Get_Val);
23572 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
23573 @end example
23574 @end quotation
23576 As for the @code{C} calling convention, when the @code{External_Name}
23577 parameter is missing, it is taken to be the name of the Ada entity in lower
23578 case. If instead of writing the above import pragma you write:
23580 @quotation
23582 @example
23583 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23584 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
23585 @end example
23586 @end quotation
23588 then the imported routine is @code{_retrieve_val@@4}. However, if instead
23589 of specifying the @code{External_Name} parameter you specify the
23590 @code{Link_Name} as in the following example:
23592 @quotation
23594 @example
23595 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23596 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
23597 @end example
23598 @end quotation
23600 then the imported routine is @code{retrieve_val}, that is, there is no
23601 decoration at all. No leading underscore and no Stdcall suffix
23602 @code{@@@emph{nn}}.
23604 This is especially important as in some special cases a DLL’s entry
23605 point name lacks a trailing @code{@@@emph{nn}} while the exported
23606 name generated for a call has it.
23608 It is also possible to import variables defined in a DLL by using an
23609 import pragma for a variable. As an example, if a DLL contains a
23610 variable defined as:
23612 @quotation
23614 @example
23615 int my_var;
23616 @end example
23617 @end quotation
23619 then, to access this variable from Ada you should write:
23621 @quotation
23623 @example
23624 My_Var : Interfaces.C.int;
23625 pragma Import (Stdcall, My_Var);
23626 @end example
23627 @end quotation
23629 Note that to ease building cross-platform bindings this convention
23630 will be handled as a @code{C} calling convention on non-Windows platforms.
23632 @node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
23633 @anchor{gnat_ugn/platform_specific_information id18}@anchor{1db}@anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{1dc}
23634 @subsubsection @code{Win32} Calling Convention
23637 This convention, which is GNAT-specific is fully equivalent to the
23638 @code{Stdcall} calling convention described above.
23640 @node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
23641 @anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{1dd}@anchor{gnat_ugn/platform_specific_information id19}@anchor{1de}
23642 @subsubsection @code{DLL} Calling Convention
23645 This convention, which is GNAT-specific is fully equivalent to the
23646 @code{Stdcall} calling convention described above.
23648 @node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
23649 @anchor{gnat_ugn/platform_specific_information id20}@anchor{1df}@anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{1e0}
23650 @subsubsection Introduction to Dynamic Link Libraries (DLLs)
23653 @geindex DLL
23655 A Dynamically Linked Library (DLL) is a library that can be shared by
23656 several applications running under Windows. A DLL can contain any number of
23657 routines and variables.
23659 One advantage of DLLs is that you can change and enhance them without
23660 forcing all the applications that depend on them to be relinked or
23661 recompiled. However, you should be aware than all calls to DLL routines are
23662 slower since, as you will understand below, such calls are indirect.
23664 To illustrate the remainder of this section, suppose that an application
23665 wants to use the services of a DLL @code{API.dll}. To use the services
23666 provided by @code{API.dll} you must statically link against the DLL or
23667 an import library which contains a jump table with an entry for each
23668 routine and variable exported by the DLL. In the Microsoft world this
23669 import library is called @code{API.lib}. When using GNAT this import
23670 library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
23671 @code{libAPI.a} or @code{libapi.a} (names are case insensitive).
23673 After you have linked your application with the DLL or the import library
23674 and you run your application, here is what happens:
23677 @itemize *
23679 @item 
23680 Your application is loaded into memory.
23682 @item 
23683 The DLL @code{API.dll} is mapped into the address space of your
23684 application. This means that:
23687 @itemize -
23689 @item 
23690 The DLL will use the stack of the calling thread.
23692 @item 
23693 The DLL will use the virtual address space of the calling process.
23695 @item 
23696 The DLL will allocate memory from the virtual address space of the calling
23697 process.
23699 @item 
23700 Handles (pointers) can be safely exchanged between routines in the DLL
23701 routines and routines in the application using the DLL.
23702 @end itemize
23704 @item 
23705 The entries in the jump table (from the import library @code{libAPI.dll.a}
23706 or @code{API.lib} or automatically created when linking against a DLL)
23707 which is part of your application are initialized with the addresses
23708 of the routines and variables in @code{API.dll}.
23710 @item 
23711 If present in @code{API.dll}, routines @code{DllMain} or
23712 @code{DllMainCRTStartup} are invoked. These routines typically contain
23713 the initialization code needed for the well-being of the routines and
23714 variables exported by the DLL.
23715 @end itemize
23717 There is an additional point which is worth mentioning. In the Windows
23718 world there are two kind of DLLs: relocatable and non-relocatable
23719 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
23720 in the target application address space. If the addresses of two
23721 non-relocatable DLLs overlap and these happen to be used by the same
23722 application, a conflict will occur and the application will run
23723 incorrectly. Hence, when possible, it is always preferable to use and
23724 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
23725 supported by GNAT. Note that the @code{-s} linker option (see GNU Linker
23726 User’s Guide) removes the debugging symbols from the DLL but the DLL can
23727 still be relocated.
23729 As a side note, an interesting difference between Microsoft DLLs and
23730 Unix shared libraries, is the fact that on most Unix systems all public
23731 routines are exported by default in a Unix shared library, while under
23732 Windows it is possible (but not required) to list exported routines in
23733 a definition file (see @ref{1e1,,The Definition File}).
23735 @node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
23736 @anchor{gnat_ugn/platform_specific_information id21}@anchor{1e2}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{1d3}
23737 @subsubsection Using DLLs with GNAT
23740 To use the services of a DLL, say @code{API.dll}, in your Ada application
23741 you must have:
23744 @itemize *
23746 @item 
23747 The Ada spec for the routines and/or variables you want to access in
23748 @code{API.dll}. If not available this Ada spec must be built from the C/C++
23749 header files provided with the DLL.
23751 @item 
23752 The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
23753 mentioned an import library is a statically linked library containing the
23754 import table which will be filled at load time to point to the actual
23755 @code{API.dll} routines. Sometimes you don’t have an import library for the
23756 DLL you want to use. The following sections will explain how to build
23757 one. Note that this is optional.
23759 @item 
23760 The actual DLL, @code{API.dll}.
23761 @end itemize
23763 Once you have all the above, to compile an Ada application that uses the
23764 services of @code{API.dll} and whose main subprogram is @code{My_Ada_App},
23765 you simply issue the command
23767 @quotation
23769 @example
23770 $ gnatmake my_ada_app -largs -lAPI
23771 @end example
23772 @end quotation
23774 The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
23775 tells the GNAT linker to look for an import library. The linker will
23776 look for a library name in this specific order:
23779 @itemize *
23781 @item 
23782 @code{libAPI.dll.a}
23784 @item 
23785 @code{API.dll.a}
23787 @item 
23788 @code{libAPI.a}
23790 @item 
23791 @code{API.lib}
23793 @item 
23794 @code{libAPI.dll}
23796 @item 
23797 @code{API.dll}
23798 @end itemize
23800 The first three are the GNU style import libraries. The third is the
23801 Microsoft style import libraries. The last two are the actual DLL names.
23803 Note that if the Ada package spec for @code{API.dll} contains the
23804 following pragma
23806 @quotation
23808 @example
23809 pragma Linker_Options ("-lAPI");
23810 @end example
23811 @end quotation
23813 you do not have to add @code{-largs -lAPI} at the end of the
23814 @code{gnatmake} command.
23816 If any one of the items above is missing you will have to create it
23817 yourself. The following sections explain how to do so using as an
23818 example a fictitious DLL called @code{API.dll}.
23820 @menu
23821 * Creating an Ada Spec for the DLL Services:: 
23822 * Creating an Import Library:: 
23824 @end menu
23826 @node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
23827 @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}
23828 @subsubsection Creating an Ada Spec for the DLL Services
23831 A DLL typically comes with a C/C++ header file which provides the
23832 definitions of the routines and variables exported by the DLL. The Ada
23833 equivalent of this header file is a package spec that contains definitions
23834 for the imported entities. If the DLL you intend to use does not come with
23835 an Ada spec you have to generate one such spec yourself. For example if
23836 the header file of @code{API.dll} is a file @code{api.h} containing the
23837 following two definitions:
23839 @quotation
23841 @example
23842 int some_var;
23843 int get (char *);
23844 @end example
23845 @end quotation
23847 then the equivalent Ada spec could be:
23849 @quotation
23851 @example
23852 with Interfaces.C.Strings;
23853 package API is
23854    use Interfaces;
23856    Some_Var : C.int;
23857    function Get (Str : C.Strings.Chars_Ptr) return C.int;
23859 private
23860    pragma Import (C, Get);
23861    pragma Import (DLL, Some_Var);
23862 end API;
23863 @end example
23864 @end quotation
23866 @node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
23867 @anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{1e5}@anchor{gnat_ugn/platform_specific_information id23}@anchor{1e6}
23868 @subsubsection Creating an Import Library
23871 @geindex Import library
23873 If a Microsoft-style import library @code{API.lib} or a GNAT-style
23874 import library @code{libAPI.dll.a} or @code{libAPI.a} is available
23875 with @code{API.dll} you can skip this section. You can also skip this
23876 section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
23877 as in this case it is possible to link directly against the
23878 DLL. Otherwise read on.
23880 @geindex Definition file
23881 @anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{1e1}
23882 @subsubheading The Definition File
23885 As previously mentioned, and unlike Unix systems, the list of symbols
23886 that are exported from a DLL must be provided explicitly in Windows.
23887 The main goal of a definition file is precisely that: list the symbols
23888 exported by a DLL. A definition file (usually a file with a @code{.def}
23889 suffix) has the following structure:
23891 @quotation
23893 @example
23894 [LIBRARY `@w{`}name`@w{`}]
23895 [DESCRIPTION `@w{`}string`@w{`}]
23896 EXPORTS
23897    `@w{`}symbol1`@w{`}
23898    `@w{`}symbol2`@w{`}
23899    ...
23900 @end example
23901 @end quotation
23904 @table @asis
23906 @item @emph{LIBRARY name}
23908 This section, which is optional, gives the name of the DLL.
23910 @item @emph{DESCRIPTION string}
23912 This section, which is optional, gives a description string that will be
23913 embedded in the import library.
23915 @item @emph{EXPORTS}
23917 This section gives the list of exported symbols (procedures, functions or
23918 variables). For instance in the case of @code{API.dll} the @code{EXPORTS}
23919 section of @code{API.def} looks like:
23921 @example
23922 EXPORTS
23923    some_var
23924    get
23925 @end example
23926 @end table
23928 Note that you must specify the correct suffix (@code{@@@emph{nn}})
23929 (see @ref{1d6,,Windows Calling Conventions}) for a Stdcall
23930 calling convention function in the exported symbols list.
23932 There can actually be other sections in a definition file, but these
23933 sections are not relevant to the discussion at hand.
23934 @anchor{gnat_ugn/platform_specific_information create-def-file-automatically}@anchor{1e7}
23935 @subsubheading Creating a Definition File Automatically
23938 You can automatically create the definition file @code{API.def}
23939 (see @ref{1e1,,The Definition File}) from a DLL.
23940 For that use the @code{dlltool} program as follows:
23942 @quotation
23944 @example
23945 $ dlltool API.dll -z API.def --export-all-symbols
23946 @end example
23948 Note that if some routines in the DLL have the @code{Stdcall} convention
23949 (@ref{1d6,,Windows Calling Conventions}) with stripped @code{@@@emph{nn}}
23950 suffix then you’ll have to edit @code{api.def} to add it, and specify
23951 @code{-k} to @code{gnatdll} when creating the import library.
23953 Here are some hints to find the right @code{@@@emph{nn}} suffix.
23956 @itemize -
23958 @item 
23959 If you have the Microsoft import library (.lib), it is possible to get
23960 the right symbols by using Microsoft @code{dumpbin} tool (see the
23961 corresponding Microsoft documentation for further details).
23963 @example
23964 $ dumpbin /exports api.lib
23965 @end example
23967 @item 
23968 If you have a message about a missing symbol at link time the compiler
23969 tells you what symbol is expected. You just have to go back to the
23970 definition file and add the right suffix.
23971 @end itemize
23972 @end quotation
23973 @anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{1e8}
23974 @subsubheading GNAT-Style Import Library
23977 To create a static import library from @code{API.dll} with the GNAT tools
23978 you should create the .def file, then use @code{gnatdll} tool
23979 (see @ref{1e9,,Using gnatdll}) as follows:
23981 @quotation
23983 @example
23984 $ gnatdll -e API.def -d API.dll
23985 @end example
23987 @code{gnatdll} takes as input a definition file @code{API.def} and the
23988 name of the DLL containing the services listed in the definition file
23989 @code{API.dll}. The name of the static import library generated is
23990 computed from the name of the definition file as follows: if the
23991 definition file name is @code{xyz.def}, the import library name will
23992 be @code{libxyz.a}. Note that in the previous example option
23993 @code{-e} could have been removed because the name of the definition
23994 file (before the @code{.def} suffix) is the same as the name of the
23995 DLL (@ref{1e9,,Using gnatdll} for more information about @code{gnatdll}).
23996 @end quotation
23997 @anchor{gnat_ugn/platform_specific_information msvs-style-import-library}@anchor{1ea}
23998 @subsubheading Microsoft-Style Import Library
24001 A Microsoft import library is needed only if you plan to make an
24002 Ada DLL available to applications developed with Microsoft
24003 tools (@ref{1d2,,Mixed-Language Programming on Windows}).
24005 To create a Microsoft-style import library for @code{API.dll} you
24006 should create the .def file, then build the actual import library using
24007 Microsoft’s @code{lib} utility:
24009 @quotation
24011 @example
24012 $ lib -machine:IX86 -def:API.def -out:API.lib
24013 @end example
24015 If you use the above command the definition file @code{API.def} must
24016 contain a line giving the name of the DLL:
24018 @example
24019 LIBRARY      "API"
24020 @end example
24022 See the Microsoft documentation for further details about the usage of
24023 @code{lib}.
24024 @end quotation
24026 @node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
24027 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{1d4}@anchor{gnat_ugn/platform_specific_information id24}@anchor{1eb}
24028 @subsubsection Building DLLs with GNAT Project files
24031 @geindex DLLs
24032 @geindex building
24034 There is nothing specific to Windows in the build process.
24035 See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24036 chapter of the @emph{GPRbuild User’s Guide}.
24038 Due to a system limitation, it is not possible under Windows to create threads
24039 when inside the @code{DllMain} routine which is used for auto-initialization
24040 of shared libraries, so it is not possible to have library level tasks in SALs.
24042 @node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
24043 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{1ec}@anchor{gnat_ugn/platform_specific_information id25}@anchor{1ed}
24044 @subsubsection Building DLLs with GNAT
24047 @geindex DLLs
24048 @geindex building
24050 This section explain how to build DLLs using the GNAT built-in DLL
24051 support. With the following procedure it is straight forward to build
24052 and use DLLs with GNAT.
24055 @itemize *
24057 @item 
24058 Building object files.
24059 The first step is to build all objects files that are to be included
24060 into the DLL. This is done by using the standard @code{gnatmake} tool.
24062 @item 
24063 Building the DLL.
24064 To build the DLL you must use the @code{gcc} @code{-shared} and
24065 @code{-shared-libgcc} options. It is quite simple to use this method:
24067 @example
24068 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
24069 @end example
24071 It is important to note that in this case all symbols found in the
24072 object files are automatically exported. It is possible to restrict
24073 the set of symbols to export by passing to @code{gcc} a definition
24074 file (see @ref{1e1,,The Definition File}).
24075 For example:
24077 @example
24078 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
24079 @end example
24081 If you use a definition file you must export the elaboration procedures
24082 for every package that required one. Elaboration procedures are named
24083 using the package name followed by “_E”.
24085 @item 
24086 Preparing DLL to be used.
24087 For the DLL to be used by client programs the bodies must be hidden
24088 from it and the .ali set with read-only attribute. This is very important
24089 otherwise GNAT will recompile all packages and will not actually use
24090 the code in the DLL. For example:
24092 @example
24093 $ mkdir apilib
24094 $ copy *.ads *.ali api.dll apilib
24095 $ attrib +R apilib\\*.ali
24096 @end example
24097 @end itemize
24099 At this point it is possible to use the DLL by directly linking
24100 against it. Note that you must use the GNAT shared runtime when using
24101 GNAT shared libraries. This is achieved by using the @code{-shared} binder
24102 option.
24104 @quotation
24106 @example
24107 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
24108 @end example
24109 @end quotation
24111 @node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
24112 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{1ee}@anchor{gnat_ugn/platform_specific_information id26}@anchor{1ef}
24113 @subsubsection Building DLLs with gnatdll
24116 @geindex DLLs
24117 @geindex building
24119 Note that it is preferred to use GNAT Project files
24120 (@ref{1d4,,Building DLLs with GNAT Project files}) or the built-in GNAT
24121 DLL support (@ref{1ec,,Building DLLs with GNAT}) or to build DLLs.
24123 This section explains how to build DLLs containing Ada code using
24124 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
24125 remainder of this section.
24127 The steps required to build an Ada DLL that is to be used by Ada as well as
24128 non-Ada applications are as follows:
24131 @itemize *
24133 @item 
24134 You need to mark each Ada entity exported by the DLL with a @code{C} or
24135 @code{Stdcall} calling convention to avoid any Ada name mangling for the
24136 entities exported by the DLL
24137 (see @ref{1f0,,Exporting Ada Entities}). You can
24138 skip this step if you plan to use the Ada DLL only from Ada applications.
24140 @item 
24141 Your Ada code must export an initialization routine which calls the routine
24142 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
24143 the Ada code in the DLL (@ref{1f1,,Ada DLLs and Elaboration}). The initialization
24144 routine exported by the Ada DLL must be invoked by the clients of the DLL
24145 to initialize the DLL.
24147 @item 
24148 When useful, the DLL should also export a finalization routine which calls
24149 routine @code{adafinal} generated by @code{gnatbind} to perform the
24150 finalization of the Ada code in the DLL (@ref{1f2,,Ada DLLs and Finalization}).
24151 The finalization routine exported by the Ada DLL must be invoked by the
24152 clients of the DLL when the DLL services are no further needed.
24154 @item 
24155 You must provide a spec for the services exported by the Ada DLL in each
24156 of the programming languages to which you plan to make the DLL available.
24158 @item 
24159 You must provide a definition file listing the exported entities
24160 (@ref{1e1,,The Definition File}).
24162 @item 
24163 Finally you must use @code{gnatdll} to produce the DLL and the import
24164 library (@ref{1e9,,Using gnatdll}).
24165 @end itemize
24167 Note that a relocatable DLL stripped using the @code{strip}
24168 binutils tool will not be relocatable anymore. To build a DLL without
24169 debug information pass @code{-largs -s} to @code{gnatdll}. This
24170 restriction does not apply to a DLL built using a Library Project.
24171 See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24172 chapter of the @emph{GPRbuild User’s Guide}.
24174 @c Limitations_When_Using_Ada_DLLs_from Ada:
24176 @menu
24177 * Limitations When Using Ada DLLs from Ada:: 
24178 * Exporting Ada Entities:: 
24179 * Ada DLLs and Elaboration:: 
24181 @end menu
24183 @node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
24184 @anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{1f3}
24185 @subsubsection Limitations When Using Ada DLLs from Ada
24188 When using Ada DLLs from Ada applications there is a limitation users
24189 should be aware of. Because on Windows the GNAT run-time is not in a DLL of
24190 its own, each Ada DLL includes a part of the GNAT run-time. Specifically,
24191 each Ada DLL includes the services of the GNAT run-time that are necessary
24192 to the Ada code inside the DLL. As a result, when an Ada program uses an
24193 Ada DLL there are two independent GNAT run-times: one in the Ada DLL and
24194 one in the main program.
24196 It is therefore not possible to exchange GNAT run-time objects between the
24197 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
24198 handles (e.g., @code{Text_IO.File_Type}), tasks types, protected objects
24199 types, etc.
24201 It is completely safe to exchange plain elementary, array or record types,
24202 Windows object handles, etc.
24204 @node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
24205 @anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{1f0}@anchor{gnat_ugn/platform_specific_information id27}@anchor{1f4}
24206 @subsubsection Exporting Ada Entities
24209 @geindex Export table
24211 Building a DLL is a way to encapsulate a set of services usable from any
24212 application. As a result, the Ada entities exported by a DLL should be
24213 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
24214 any Ada name mangling. As an example here is an Ada package
24215 @code{API}, spec and body, exporting two procedures, a function, and a
24216 variable:
24218 @quotation
24220 @example
24221 with Interfaces.C; use Interfaces;
24222 package API is
24223    Count : C.int := 0;
24224    function Factorial (Val : C.int) return C.int;
24226    procedure Initialize_API;
24227    procedure Finalize_API;
24228    --  Initialization & Finalization routines. More in the next section.
24229 private
24230    pragma Export (C, Initialize_API);
24231    pragma Export (C, Finalize_API);
24232    pragma Export (C, Count);
24233    pragma Export (C, Factorial);
24234 end API;
24235 @end example
24237 @example
24238 package body API is
24239    function Factorial (Val : C.int) return C.int is
24240       Fact : C.int := 1;
24241    begin
24242       Count := Count + 1;
24243       for K in 1 .. Val loop
24244          Fact := Fact * K;
24245       end loop;
24246       return Fact;
24247    end Factorial;
24249    procedure Initialize_API is
24250       procedure Adainit;
24251       pragma Import (C, Adainit);
24252    begin
24253       Adainit;
24254    end Initialize_API;
24256    procedure Finalize_API is
24257       procedure Adafinal;
24258       pragma Import (C, Adafinal);
24259    begin
24260       Adafinal;
24261    end Finalize_API;
24262 end API;
24263 @end example
24264 @end quotation
24266 If the Ada DLL you are building will only be used by Ada applications
24267 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
24268 convention. As an example, the previous package could be written as
24269 follows:
24271 @quotation
24273 @example
24274 package API is
24275    Count : Integer := 0;
24276    function Factorial (Val : Integer) return Integer;
24278    procedure Initialize_API;
24279    procedure Finalize_API;
24280    --  Initialization and Finalization routines.
24281 end API;
24282 @end example
24284 @example
24285 package body API is
24286    function Factorial (Val : Integer) return Integer is
24287       Fact : Integer := 1;
24288    begin
24289       Count := Count + 1;
24290       for K in 1 .. Val loop
24291          Fact := Fact * K;
24292       end loop;
24293       return Fact;
24294    end Factorial;
24296    ...
24297    --  The remainder of this package body is unchanged.
24298 end API;
24299 @end example
24300 @end quotation
24302 Note that if you do not export the Ada entities with a @code{C} or
24303 @code{Stdcall} convention you will have to provide the mangled Ada names
24304 in the definition file of the Ada DLL
24305 (@ref{1f5,,Creating the Definition File}).
24307 @node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
24308 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{1f1}@anchor{gnat_ugn/platform_specific_information id28}@anchor{1f6}
24309 @subsubsection Ada DLLs and Elaboration
24312 @geindex DLLs and elaboration
24314 The DLL that you are building contains your Ada code as well as all the
24315 routines in the Ada library that are needed by it. The first thing a
24316 user of your DLL must do is elaborate the Ada code
24317 (@ref{f,,Elaboration Order Handling in GNAT}).
24319 To achieve this you must export an initialization routine
24320 (@code{Initialize_API} in the previous example), which must be invoked
24321 before using any of the DLL services. This elaboration routine must call
24322 the Ada elaboration routine @code{adainit} generated by the GNAT binder
24323 (@ref{7e,,Binding with Non-Ada Main Programs}). See the body of
24324 @code{Initialize_Api} for an example. Note that the GNAT binder is
24325 automatically invoked during the DLL build process by the @code{gnatdll}
24326 tool (@ref{1e9,,Using gnatdll}).
24328 When a DLL is loaded, Windows systematically invokes a routine called
24329 @code{DllMain}. It would therefore be possible to call @code{adainit}
24330 directly from @code{DllMain} without having to provide an explicit
24331 initialization routine. Unfortunately, it is not possible to call
24332 @code{adainit} from the @code{DllMain} if your program has library level
24333 tasks because access to the @code{DllMain} entry point is serialized by
24334 the system (that is, only a single thread can execute ‘through’ it at a
24335 time), which means that the GNAT run-time will deadlock waiting for the
24336 newly created task to complete its initialization.
24338 @node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
24339 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{1f2}@anchor{gnat_ugn/platform_specific_information id29}@anchor{1f7}
24340 @subsubsection Ada DLLs and Finalization
24343 @geindex DLLs and finalization
24345 When the services of an Ada DLL are no longer needed, the client code should
24346 invoke the DLL finalization routine, if available. The DLL finalization
24347 routine is in charge of releasing all resources acquired by the DLL. In the
24348 case of the Ada code contained in the DLL, this is achieved by calling
24349 routine @code{adafinal} generated by the GNAT binder
24350 (@ref{7e,,Binding with Non-Ada Main Programs}).
24351 See the body of @code{Finalize_Api} for an
24352 example. As already pointed out the GNAT binder is automatically invoked
24353 during the DLL build process by the @code{gnatdll} tool
24354 (@ref{1e9,,Using gnatdll}).
24356 @node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
24357 @anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{1f8}@anchor{gnat_ugn/platform_specific_information id30}@anchor{1f9}
24358 @subsubsection Creating a Spec for Ada DLLs
24361 To use the services exported by the Ada DLL from another programming
24362 language (e.g., C), you have to translate the specs of the exported Ada
24363 entities in that language. For instance in the case of @code{API.dll},
24364 the corresponding C header file could look like:
24366 @quotation
24368 @example
24369 extern int *_imp__count;
24370 #define count (*_imp__count)
24371 int factorial (int);
24372 @end example
24373 @end quotation
24375 It is important to understand that when building an Ada DLL to be used by
24376 other Ada applications, you need two different specs for the packages
24377 contained in the DLL: one for building the DLL and the other for using
24378 the DLL. This is because the @code{DLL} calling convention is needed to
24379 use a variable defined in a DLL, but when building the DLL, the variable
24380 must have either the @code{Ada} or @code{C} calling convention. As an
24381 example consider a DLL comprising the following package @code{API}:
24383 @quotation
24385 @example
24386 package API is
24387    Count : Integer := 0;
24388    ...
24389    --  Remainder of the package omitted.
24390 end API;
24391 @end example
24392 @end quotation
24394 After producing a DLL containing package @code{API}, the spec that
24395 must be used to import @code{API.Count} from Ada code outside of the
24396 DLL is:
24398 @quotation
24400 @example
24401 package API is
24402    Count : Integer;
24403    pragma Import (DLL, Count);
24404 end API;
24405 @end example
24406 @end quotation
24408 @menu
24409 * Creating the Definition File:: 
24410 * Using gnatdll:: 
24412 @end menu
24414 @node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
24415 @anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{1f5}@anchor{gnat_ugn/platform_specific_information id31}@anchor{1fa}
24416 @subsubsection Creating the Definition File
24419 The definition file is the last file needed to build the DLL. It lists
24420 the exported symbols. As an example, the definition file for a DLL
24421 containing only package @code{API} (where all the entities are exported
24422 with a @code{C} calling convention) is:
24424 @quotation
24426 @example
24427 EXPORTS
24428     count
24429     factorial
24430     finalize_api
24431     initialize_api
24432 @end example
24433 @end quotation
24435 If the @code{C} calling convention is missing from package @code{API},
24436 then the definition file contains the mangled Ada names of the above
24437 entities, which in this case are:
24439 @quotation
24441 @example
24442 EXPORTS
24443     api__count
24444     api__factorial
24445     api__finalize_api
24446     api__initialize_api
24447 @end example
24448 @end quotation
24450 @node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
24451 @anchor{gnat_ugn/platform_specific_information id32}@anchor{1fb}@anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{1e9}
24452 @subsubsection Using @code{gnatdll}
24455 @geindex gnatdll
24457 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
24458 and non-Ada sources that make up your DLL have been compiled.
24459 @code{gnatdll} is actually in charge of two distinct tasks: build the
24460 static import library for the DLL and the actual DLL. The form of the
24461 @code{gnatdll} command is
24463 @quotation
24465 @example
24466 $ gnatdll [ switches ] list-of-files [ -largs opts ]
24467 @end example
24468 @end quotation
24470 where @code{list-of-files} is a list of ALI and object files. The object
24471 file list must be the exact list of objects corresponding to the non-Ada
24472 sources whose services are to be included in the DLL. The ALI file list
24473 must be the exact list of ALI files for the corresponding Ada sources
24474 whose services are to be included in the DLL. If @code{list-of-files} is
24475 missing, only the static import library is generated.
24477 You may specify any of the following switches to @code{gnatdll}:
24479 @quotation
24481 @geindex -a (gnatdll)
24482 @end quotation
24485 @table @asis
24487 @item @code{-a[@emph{address}]}
24489 Build a non-relocatable DLL at @code{address}. If @code{address} is not
24490 specified the default address @code{0x11000000} will be used. By default,
24491 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
24492 advise the reader to build relocatable DLL.
24494 @geindex -b (gnatdll)
24496 @item @code{-b @emph{address}}
24498 Set the relocatable DLL base address. By default the address is
24499 @code{0x11000000}.
24501 @geindex -bargs (gnatdll)
24503 @item @code{-bargs @emph{opts}}
24505 Binder options. Pass @code{opts} to the binder.
24507 @geindex -d (gnatdll)
24509 @item @code{-d @emph{dllfile}}
24511 @code{dllfile} is the name of the DLL. This switch must be present for
24512 @code{gnatdll} to do anything. The name of the generated import library is
24513 obtained algorithmically from @code{dllfile} as shown in the following
24514 example: if @code{dllfile} is @code{xyz.dll}, the import library name is
24515 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
24516 by option @code{-e}) is obtained algorithmically from @code{dllfile}
24517 as shown in the following example:
24518 if @code{dllfile} is @code{xyz.dll}, the definition
24519 file used is @code{xyz.def}.
24521 @geindex -e (gnatdll)
24523 @item @code{-e @emph{deffile}}
24525 @code{deffile} is the name of the definition file.
24527 @geindex -g (gnatdll)
24529 @item @code{-g}
24531 Generate debugging information. This information is stored in the object
24532 file and copied from there to the final DLL file by the linker,
24533 where it can be read by the debugger. You must use the
24534 @code{-g} switch if you plan on using the debugger or the symbolic
24535 stack traceback.
24537 @geindex -h (gnatdll)
24539 @item @code{-h}
24541 Help mode. Displays @code{gnatdll} switch usage information.
24543 @geindex -I (gnatdll)
24545 @item @code{-I@emph{dir}}
24547 Direct @code{gnatdll} to search the @code{dir} directory for source and
24548 object files needed to build the DLL.
24549 (@ref{73,,Search Paths and the Run-Time Library (RTL)}).
24551 @geindex -k (gnatdll)
24553 @item @code{-k}
24555 Removes the @code{@@@emph{nn}} suffix from the import library’s exported
24556 names, but keeps them for the link names. You must specify this
24557 option if you want to use a @code{Stdcall} function in a DLL for which
24558 the @code{@@@emph{nn}} suffix has been removed. This is the case for most
24559 of the Windows NT DLL for example. This option has no effect when
24560 @code{-n} option is specified.
24562 @geindex -l (gnatdll)
24564 @item @code{-l @emph{file}}
24566 The list of ALI and object files used to build the DLL are listed in
24567 @code{file}, instead of being given in the command line. Each line in
24568 @code{file} contains the name of an ALI or object file.
24570 @geindex -n (gnatdll)
24572 @item @code{-n}
24574 No Import. Do not create the import library.
24576 @geindex -q (gnatdll)
24578 @item @code{-q}
24580 Quiet mode. Do not display unnecessary messages.
24582 @geindex -v (gnatdll)
24584 @item @code{-v}
24586 Verbose mode. Display extra information.
24588 @geindex -largs (gnatdll)
24590 @item @code{-largs @emph{opts}}
24592 Linker options. Pass @code{opts} to the linker.
24593 @end table
24595 @subsubheading @code{gnatdll} Example
24598 As an example the command to build a relocatable DLL from @code{api.adb}
24599 once @code{api.adb} has been compiled and @code{api.def} created is
24601 @quotation
24603 @example
24604 $ gnatdll -d api.dll api.ali
24605 @end example
24606 @end quotation
24608 The above command creates two files: @code{libapi.dll.a} (the import
24609 library) and @code{api.dll} (the actual DLL). If you want to create
24610 only the DLL, just type:
24612 @quotation
24614 @example
24615 $ gnatdll -d api.dll -n api.ali
24616 @end example
24617 @end quotation
24619 Alternatively if you want to create just the import library, type:
24621 @quotation
24623 @example
24624 $ gnatdll -d api.dll
24625 @end example
24626 @end quotation
24628 @subsubheading @code{gnatdll} behind the Scenes
24631 This section details the steps involved in creating a DLL. @code{gnatdll}
24632 does these steps for you. Unless you are interested in understanding what
24633 goes on behind the scenes, you should skip this section.
24635 We use the previous example of a DLL containing the Ada package @code{API},
24636 to illustrate the steps necessary to build a DLL. The starting point is a
24637 set of objects that will make up the DLL and the corresponding ALI
24638 files. In the case of this example this means that @code{api.o} and
24639 @code{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
24640 the following:
24643 @itemize *
24645 @item 
24646 @code{gnatdll} builds the base file (@code{api.base}). A base file gives
24647 the information necessary to generate relocation information for the
24648 DLL.
24650 @example
24651 $ gnatbind -n api
24652 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
24653 @end example
24655 In addition to the base file, the @code{gnatlink} command generates an
24656 output file @code{api.jnk} which can be discarded. The @code{-mdll} switch
24657 asks @code{gnatlink} to generate the routines @code{DllMain} and
24658 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
24659 is loaded into memory.
24661 @item 
24662 @code{gnatdll} uses @code{dlltool} (see @ref{1fc,,Using dlltool}) to build the
24663 export table (@code{api.exp}). The export table contains the relocation
24664 information in a form which can be used during the final link to ensure
24665 that the Windows loader is able to place the DLL anywhere in memory.
24667 @example
24668 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
24669           --output-exp api.exp
24670 @end example
24672 @item 
24673 @code{gnatdll} builds the base file using the new export table. Note that
24674 @code{gnatbind} must be called once again since the binder generated file
24675 has been deleted during the previous call to @code{gnatlink}.
24677 @example
24678 $ gnatbind -n api
24679 $ gnatlink api -o api.jnk api.exp -mdll
24680       -Wl,--base-file,api.base
24681 @end example
24683 @item 
24684 @code{gnatdll} builds the new export table using the new base file and
24685 generates the DLL import library @code{libAPI.dll.a}.
24687 @example
24688 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
24689           --output-exp api.exp --output-lib libAPI.a
24690 @end example
24692 @item 
24693 Finally @code{gnatdll} builds the relocatable DLL using the final export
24694 table.
24696 @example
24697 $ gnatbind -n api
24698 $ gnatlink api api.exp -o api.dll -mdll
24699 @end example
24700 @end itemize
24701 @anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{1fc}
24702 @subsubheading Using @code{dlltool}
24705 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
24706 DLLs and static import libraries. This section summarizes the most
24707 common @code{dlltool} switches. The form of the @code{dlltool} command
24710 @quotation
24712 @example
24713 $ dlltool [`switches`]
24714 @end example
24715 @end quotation
24717 @code{dlltool} switches include:
24719 @geindex --base-file (dlltool)
24722 @table @asis
24724 @item @code{--base-file @emph{basefile}}
24726 Read the base file @code{basefile} generated by the linker. This switch
24727 is used to create a relocatable DLL.
24728 @end table
24730 @geindex --def (dlltool)
24733 @table @asis
24735 @item @code{--def @emph{deffile}}
24737 Read the definition file.
24738 @end table
24740 @geindex --dllname (dlltool)
24743 @table @asis
24745 @item @code{--dllname @emph{name}}
24747 Gives the name of the DLL. This switch is used to embed the name of the
24748 DLL in the static import library generated by @code{dlltool} with switch
24749 @code{--output-lib}.
24750 @end table
24752 @geindex -k (dlltool)
24755 @table @asis
24757 @item @code{-k}
24759 Kill @code{@@@emph{nn}} from exported names
24760 (@ref{1d6,,Windows Calling Conventions}
24761 for a discussion about @code{Stdcall}-style symbols).
24762 @end table
24764 @geindex --help (dlltool)
24767 @table @asis
24769 @item @code{--help}
24771 Prints the @code{dlltool} switches with a concise description.
24772 @end table
24774 @geindex --output-exp (dlltool)
24777 @table @asis
24779 @item @code{--output-exp @emph{exportfile}}
24781 Generate an export file @code{exportfile}. The export file contains the
24782 export table (list of symbols in the DLL) and is used to create the DLL.
24783 @end table
24785 @geindex --output-lib (dlltool)
24788 @table @asis
24790 @item @code{--output-lib @emph{libfile}}
24792 Generate a static import library @code{libfile}.
24793 @end table
24795 @geindex -v (dlltool)
24798 @table @asis
24800 @item @code{-v}
24802 Verbose mode.
24803 @end table
24805 @geindex --as (dlltool)
24808 @table @asis
24810 @item @code{--as @emph{assembler-name}}
24812 Use @code{assembler-name} as the assembler. The default is @code{as}.
24813 @end table
24815 @node GNAT and Windows Resources,Using GNAT DLLs from Microsoft Visual Studio Applications,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
24816 @anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{1fd}@anchor{gnat_ugn/platform_specific_information id33}@anchor{1fe}
24817 @subsubsection GNAT and Windows Resources
24820 @geindex Resources
24821 @geindex windows
24823 Resources are an easy way to add Windows specific objects to your
24824 application. The objects that can be added as resources include:
24827 @itemize *
24829 @item 
24830 menus
24832 @item 
24833 accelerators
24835 @item 
24836 dialog boxes
24838 @item 
24839 string tables
24841 @item 
24842 bitmaps
24844 @item 
24845 cursors
24847 @item 
24848 icons
24850 @item 
24851 fonts
24853 @item 
24854 version information
24855 @end itemize
24857 For example, a version information resource can be defined as follow and
24858 embedded into an executable or DLL:
24860 A version information resource can be used to embed information into an
24861 executable or a DLL. These information can be viewed using the file properties
24862 from the Windows Explorer. Here is an example of a version information
24863 resource:
24865 @quotation
24867 @example
24868 1 VERSIONINFO
24869 FILEVERSION     1,0,0,0
24870 PRODUCTVERSION  1,0,0,0
24871 BEGIN
24872   BLOCK "StringFileInfo"
24873   BEGIN
24874     BLOCK "080904E4"
24875     BEGIN
24876       VALUE "CompanyName", "My Company Name"
24877       VALUE "FileDescription", "My application"
24878       VALUE "FileVersion", "1.0"
24879       VALUE "InternalName", "my_app"
24880       VALUE "LegalCopyright", "My Name"
24881       VALUE "OriginalFilename", "my_app.exe"
24882       VALUE "ProductName", "My App"
24883       VALUE "ProductVersion", "1.0"
24884     END
24885   END
24887   BLOCK "VarFileInfo"
24888   BEGIN
24889     VALUE "Translation", 0x809, 1252
24890   END
24892 @end example
24893 @end quotation
24895 The value @code{0809} (langID) is for the U.K English language and
24896 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
24897 multilingual.
24899 This section explains how to build, compile and use resources. Note that this
24900 section does not cover all resource objects, for a complete description see
24901 the corresponding Microsoft documentation.
24903 @menu
24904 * Building Resources:: 
24905 * Compiling Resources:: 
24906 * Using Resources:: 
24908 @end menu
24910 @node Building Resources,Compiling Resources,,GNAT and Windows Resources
24911 @anchor{gnat_ugn/platform_specific_information building-resources}@anchor{1ff}@anchor{gnat_ugn/platform_specific_information id34}@anchor{200}
24912 @subsubsection Building Resources
24915 @geindex Resources
24916 @geindex building
24918 A resource file is an ASCII file. By convention resource files have an
24919 @code{.rc} extension.
24920 The easiest way to build a resource file is to use Microsoft tools
24921 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
24922 @code{dlgedit.exe} to build dialogs.
24923 It is always possible to build an @code{.rc} file yourself by writing a
24924 resource script.
24926 It is not our objective to explain how to write a resource file. A
24927 complete description of the resource script language can be found in the
24928 Microsoft documentation.
24930 @node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
24931 @anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{201}@anchor{gnat_ugn/platform_specific_information id35}@anchor{202}
24932 @subsubsection Compiling Resources
24935 @geindex rc
24937 @geindex windres
24939 @geindex Resources
24940 @geindex compiling
24942 This section describes how to build a GNAT-compatible (COFF) object file
24943 containing the resources. This is done using the Resource Compiler
24944 @code{windres} as follows:
24946 @quotation
24948 @example
24949 $ windres -i myres.rc -o myres.o
24950 @end example
24951 @end quotation
24953 By default @code{windres} will run @code{gcc} to preprocess the @code{.rc}
24954 file. You can specify an alternate preprocessor (usually named
24955 @code{cpp.exe}) using the @code{windres} @code{--preprocessor}
24956 parameter. A list of all possible options may be obtained by entering
24957 the command @code{windres} @code{--help}.
24959 It is also possible to use the Microsoft resource compiler @code{rc.exe}
24960 to produce a @code{.res} file (binary resource file). See the
24961 corresponding Microsoft documentation for further details. In this case
24962 you need to use @code{windres} to translate the @code{.res} file to a
24963 GNAT-compatible object file as follows:
24965 @quotation
24967 @example
24968 $ windres -i myres.res -o myres.o
24969 @end example
24970 @end quotation
24972 @node Using Resources,,Compiling Resources,GNAT and Windows Resources
24973 @anchor{gnat_ugn/platform_specific_information id36}@anchor{203}@anchor{gnat_ugn/platform_specific_information using-resources}@anchor{204}
24974 @subsubsection Using Resources
24977 @geindex Resources
24978 @geindex using
24980 To include the resource file in your program just add the
24981 GNAT-compatible object file for the resource(s) to the linker
24982 arguments. With @code{gnatmake} this is done by using the @code{-largs}
24983 option:
24985 @quotation
24987 @example
24988 $ gnatmake myprog -largs myres.o
24989 @end example
24990 @end quotation
24992 @node Using GNAT DLLs from Microsoft Visual Studio Applications,Debugging a DLL,GNAT and Windows Resources,Mixed-Language Programming on Windows
24993 @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}
24994 @subsubsection Using GNAT DLLs from Microsoft Visual Studio Applications
24997 @geindex Microsoft Visual Studio
24998 @geindex use with GNAT DLLs
25000 This section describes a common case of mixed GNAT/Microsoft Visual Studio
25001 application development, where the main program is developed using MSVS, and
25002 is linked with a DLL developed using GNAT. Such a mixed application should
25003 be developed following the general guidelines outlined above; below is the
25004 cookbook-style sequence of steps to follow:
25007 @enumerate 
25009 @item 
25010 First develop and build the GNAT shared library using a library project
25011 (let’s assume the project is @code{mylib.gpr}, producing the library @code{libmylib.dll}):
25012 @end enumerate
25014 @quotation
25016 @example
25017 $ gprbuild -p mylib.gpr
25018 @end example
25019 @end quotation
25022 @enumerate 2
25024 @item 
25025 Produce a .def file for the symbols you need to interface with, either by
25026 hand or automatically with possibly some manual adjustments
25027 (see @ref{1e7,,Creating Definition File Automatically}):
25028 @end enumerate
25030 @quotation
25032 @example
25033 $ dlltool libmylib.dll -z libmylib.def --export-all-symbols
25034 @end example
25035 @end quotation
25038 @enumerate 3
25040 @item 
25041 Make sure that MSVS command-line tools are accessible on the path.
25043 @item 
25044 Create the Microsoft-style import library (see @ref{1ea,,MSVS-Style Import Library}):
25045 @end enumerate
25047 @quotation
25049 @example
25050 $ lib -machine:IX86 -def:libmylib.def -out:libmylib.lib
25051 @end example
25052 @end quotation
25054 If you are using a 64-bit toolchain, the above becomes…
25056 @quotation
25058 @example
25059 $ lib -machine:X64 -def:libmylib.def -out:libmylib.lib
25060 @end example
25061 @end quotation
25064 @enumerate 5
25066 @item 
25067 Build the C main
25068 @end enumerate
25070 @quotation
25072 @example
25073 $ cl /O2 /MD main.c libmylib.lib
25074 @end example
25075 @end quotation
25078 @enumerate 6
25080 @item 
25081 Before running the executable, make sure you have set the PATH to the DLL,
25082 or copy the DLL into into the directory containing the .exe.
25083 @end enumerate
25085 @node Debugging a DLL,Setting Stack Size from gnatlink,Using GNAT DLLs from Microsoft Visual Studio Applications,Mixed-Language Programming on Windows
25086 @anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{207}@anchor{gnat_ugn/platform_specific_information id37}@anchor{208}
25087 @subsubsection Debugging a DLL
25090 @geindex DLL debugging
25092 Debugging a DLL is similar to debugging a standard program. But
25093 we have to deal with two different executable parts: the DLL and the
25094 program that uses it. We have the following four possibilities:
25097 @itemize *
25099 @item 
25100 The program and the DLL are built with GCC/GNAT.
25102 @item 
25103 The program is built with foreign tools and the DLL is built with
25104 GCC/GNAT.
25106 @item 
25107 The program is built with GCC/GNAT and the DLL is built with
25108 foreign tools.
25109 @end itemize
25111 In this section we address only cases one and two above.
25112 There is no point in trying to debug
25113 a DLL with GNU/GDB, if there is no GDB-compatible debugging
25114 information in it. To do so you must use a debugger compatible with the
25115 tools suite used to build the DLL.
25117 @menu
25118 * Program and DLL Both Built with GCC/GNAT:: 
25119 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
25121 @end menu
25123 @node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
25124 @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}
25125 @subsubsection Program and DLL Both Built with GCC/GNAT
25128 This is the simplest case. Both the DLL and the program have @code{GDB}
25129 compatible debugging information. It is then possible to break anywhere in
25130 the process. Let’s suppose here that the main procedure is named
25131 @code{ada_main} and that in the DLL there is an entry point named
25132 @code{ada_dll}.
25134 The DLL (@ref{1e0,,Introduction to Dynamic Link Libraries (DLLs)}) and
25135 program must have been built with the debugging information (see GNAT -g
25136 switch). Here are the step-by-step instructions for debugging it:
25139 @itemize *
25141 @item 
25142 Launch @code{GDB} on the main program.
25144 @example
25145 $ gdb -nw ada_main
25146 @end example
25148 @item 
25149 Start the program and stop at the beginning of the main procedure
25151 @example
25152 (gdb) start
25153 @end example
25155 This step is required to be able to set a breakpoint inside the DLL. As long
25156 as the program is not run, the DLL is not loaded. This has the
25157 consequence that the DLL debugging information is also not loaded, so it is not
25158 possible to set a breakpoint in the DLL.
25160 @item 
25161 Set a breakpoint inside the DLL
25163 @example
25164 (gdb) break ada_dll
25165 (gdb) cont
25166 @end example
25167 @end itemize
25169 At this stage a breakpoint is set inside the DLL. From there on
25170 you can use the standard approach to debug the whole program
25171 (@ref{14f,,Running and Debugging Ada Programs}).
25173 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
25174 @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}
25175 @subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
25178 In this case things are slightly more complex because it is not possible to
25179 start the main program and then break at the beginning to load the DLL and the
25180 associated DLL debugging information. It is not possible to break at the
25181 beginning of the program because there is no @code{GDB} debugging information,
25182 and therefore there is no direct way of getting initial control. This
25183 section addresses this issue by describing some methods that can be used
25184 to break somewhere in the DLL to debug it.
25186 First suppose that the main procedure is named @code{main} (this is for
25187 example some C code built with Microsoft Visual C) and that there is a
25188 DLL named @code{test.dll} containing an Ada entry point named
25189 @code{ada_dll}.
25191 The DLL (see @ref{1e0,,Introduction to Dynamic Link Libraries (DLLs)}) must have
25192 been built with debugging information (see the GNAT @code{-g} option).
25194 @subsubheading Debugging the DLL Directly
25198 @itemize *
25200 @item 
25201 Find out the executable starting address
25203 @example
25204 $ objdump --file-header main.exe
25205 @end example
25207 The starting address is reported on the last line. For example:
25209 @example
25210 main.exe:     file format pei-i386
25211 architecture: i386, flags 0x0000010a:
25212 EXEC_P, HAS_DEBUG, D_PAGED
25213 start address 0x00401010
25214 @end example
25216 @item 
25217 Launch the debugger on the executable.
25219 @example
25220 $ gdb main.exe
25221 @end example
25223 @item 
25224 Set a breakpoint at the starting address, and launch the program.
25226 @example
25227 $ (gdb) break *0x00401010
25228 $ (gdb) run
25229 @end example
25231 The program will stop at the given address.
25233 @item 
25234 Set a breakpoint on a DLL subroutine.
25236 @example
25237 (gdb) break ada_dll.adb:45
25238 @end example
25240 Or if you want to break using a symbol on the DLL, you need first to
25241 select the Ada language (language used by the DLL).
25243 @example
25244 (gdb) set language ada
25245 (gdb) break ada_dll
25246 @end example
25248 @item 
25249 Continue the program.
25251 @example
25252 (gdb) cont
25253 @end example
25255 This will run the program until it reaches the breakpoint that has been
25256 set. From that point you can use the standard way to debug a program
25257 as described in (@ref{14f,,Running and Debugging Ada Programs}).
25258 @end itemize
25260 It is also possible to debug the DLL by attaching to a running process.
25262 @subsubheading Attaching to a Running Process
25265 @geindex DLL debugging
25266 @geindex attach to process
25268 With @code{GDB} it is always possible to debug a running process by
25269 attaching to it. It is possible to debug a DLL this way. The limitation
25270 of this approach is that the DLL must run long enough to perform the
25271 attach operation. It may be useful for instance to insert a time wasting
25272 loop in the code of the DLL to meet this criterion.
25275 @itemize *
25277 @item 
25278 Launch the main program @code{main.exe}.
25280 @example
25281 $ main
25282 @end example
25284 @item 
25285 Use the Windows @emph{Task Manager} to find the process ID. Let’s say
25286 that the process PID for @code{main.exe} is 208.
25288 @item 
25289 Launch gdb.
25291 @example
25292 $ gdb
25293 @end example
25295 @item 
25296 Attach to the running process to be debugged.
25298 @example
25299 (gdb) attach 208
25300 @end example
25302 @item 
25303 Load the process debugging information.
25305 @example
25306 (gdb) symbol-file main.exe
25307 @end example
25309 @item 
25310 Break somewhere in the DLL.
25312 @example
25313 (gdb) break ada_dll
25314 @end example
25316 @item 
25317 Continue process execution.
25319 @example
25320 (gdb) cont
25321 @end example
25322 @end itemize
25324 This last step will resume the process execution, and stop at
25325 the breakpoint we have set. From there you can use the standard
25326 approach to debug a program as described in
25327 @ref{14f,,Running and Debugging Ada Programs}.
25329 @node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
25330 @anchor{gnat_ugn/platform_specific_information id40}@anchor{20d}@anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{129}
25331 @subsubsection Setting Stack Size from @code{gnatlink}
25334 It is possible to specify the program stack size at link time. On modern
25335 versions of Windows, starting with XP, this is mostly useful to set the size of
25336 the main stack (environment task). The other task stacks are set with pragma
25337 Storage_Size or with the @emph{gnatbind -d} command.
25339 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
25340 reserve size of individual tasks, the link-time stack size applies to all
25341 tasks, and pragma Storage_Size has no effect.
25342 In particular, Stack Overflow checks are made against this
25343 link-time specified size.
25345 This setting can be done with @code{gnatlink} using either of the following:
25348 @itemize *
25350 @item 
25351 @code{-Xlinker} linker option
25353 @example
25354 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
25355 @end example
25357 This sets the stack reserve size to 0x10000 bytes and the stack commit
25358 size to 0x1000 bytes.
25360 @item 
25361 @code{-Wl} linker option
25363 @example
25364 $ gnatlink hello -Wl,--stack=0x1000000
25365 @end example
25367 This sets the stack reserve size to 0x1000000 bytes. Note that with
25368 @code{-Wl} option it is not possible to set the stack commit size
25369 because the comma is a separator for this option.
25370 @end itemize
25372 @node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
25373 @anchor{gnat_ugn/platform_specific_information id41}@anchor{20e}@anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{12a}
25374 @subsubsection Setting Heap Size from @code{gnatlink}
25377 Under Windows systems, it is possible to specify the program heap size from
25378 @code{gnatlink} using either of the following:
25381 @itemize *
25383 @item 
25384 @code{-Xlinker} linker option
25386 @example
25387 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
25388 @end example
25390 This sets the heap reserve size to 0x10000 bytes and the heap commit
25391 size to 0x1000 bytes.
25393 @item 
25394 @code{-Wl} linker option
25396 @example
25397 $ gnatlink hello -Wl,--heap=0x1000000
25398 @end example
25400 This sets the heap reserve size to 0x1000000 bytes. Note that with
25401 @code{-Wl} option it is not possible to set the heap commit size
25402 because the comma is a separator for this option.
25403 @end itemize
25405 @node Windows Specific Add-Ons,,Mixed-Language Programming on Windows,Microsoft Windows Topics
25406 @anchor{gnat_ugn/platform_specific_information win32-specific-addons}@anchor{20f}@anchor{gnat_ugn/platform_specific_information windows-specific-add-ons}@anchor{210}
25407 @subsection Windows Specific Add-Ons
25410 This section describes the Windows specific add-ons.
25412 @menu
25413 * Win32Ada:: 
25414 * wPOSIX:: 
25416 @end menu
25418 @node Win32Ada,wPOSIX,,Windows Specific Add-Ons
25419 @anchor{gnat_ugn/platform_specific_information id42}@anchor{211}@anchor{gnat_ugn/platform_specific_information win32ada}@anchor{212}
25420 @subsubsection Win32Ada
25423 Win32Ada is a binding for the Microsoft Win32 API. This binding can be
25424 easily installed from the provided installer. To use the Win32Ada
25425 binding you need to use a project file, and adding a single with_clause
25426 will give you full access to the Win32Ada binding sources and ensure
25427 that the proper libraries are passed to the linker.
25429 @quotation
25431 @example
25432 with "win32ada";
25433 project P is
25434    for Sources use ...;
25435 end P;
25436 @end example
25437 @end quotation
25439 To build the application you just need to call gprbuild for the
25440 application’s project, here p.gpr:
25442 @quotation
25444 @example
25445 gprbuild p.gpr
25446 @end example
25447 @end quotation
25449 @node wPOSIX,,Win32Ada,Windows Specific Add-Ons
25450 @anchor{gnat_ugn/platform_specific_information id43}@anchor{213}@anchor{gnat_ugn/platform_specific_information wposix}@anchor{214}
25451 @subsubsection wPOSIX
25454 wPOSIX is a minimal POSIX binding whose goal is to help with building
25455 cross-platforms applications. This binding is not complete though, as
25456 the Win32 API does not provide the necessary support for all POSIX APIs.
25458 To use the wPOSIX binding you need to use a project file, and adding
25459 a single with_clause will give you full access to the wPOSIX binding
25460 sources and ensure that the proper libraries are passed to the linker.
25462 @quotation
25464 @example
25465 with "wposix";
25466 project P is
25467    for Sources use ...;
25468 end P;
25469 @end example
25470 @end quotation
25472 To build the application you just need to call gprbuild for the
25473 application’s project, here p.gpr:
25475 @quotation
25477 @example
25478 gprbuild p.gpr
25479 @end example
25480 @end quotation
25482 @node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
25483 @anchor{gnat_ugn/platform_specific_information id44}@anchor{215}@anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{216}
25484 @section Mac OS Topics
25487 @geindex OS X
25489 This section describes topics that are specific to Apple’s OS X
25490 platform.
25492 @menu
25493 * Codesigning the Debugger:: 
25495 @end menu
25497 @node Codesigning the Debugger,,,Mac OS Topics
25498 @anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{217}
25499 @subsection Codesigning the Debugger
25502 The Darwin Kernel requires the debugger to have special permissions
25503 before it is allowed to control other processes. These permissions
25504 are granted by codesigning the GDB executable. Without these
25505 permissions, the debugger will report error messages such as:
25507 @example
25508 Starting program: /x/y/foo
25509 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
25510 (please check gdb is codesigned - see taskgated(8))
25511 @end example
25513 Codesigning requires a certificate.  The following procedure explains
25514 how to create one:
25517 @itemize *
25519 @item 
25520 Start the Keychain Access application (in
25521 /Applications/Utilities/Keychain Access.app)
25523 @item 
25524 Select the Keychain Access -> Certificate Assistant ->
25525 Create a Certificate… menu
25527 @item 
25528 Then:
25531 @itemize *
25533 @item 
25534 Choose a name for the new certificate (this procedure will use
25535 “gdb-cert” as an example)
25537 @item 
25538 Set “Identity Type” to “Self Signed Root”
25540 @item 
25541 Set “Certificate Type” to “Code Signing”
25543 @item 
25544 Activate the “Let me override defaults” option
25545 @end itemize
25547 @item 
25548 Click several times on “Continue” until the “Specify a Location
25549 For The Certificate” screen appears, then set “Keychain” to “System”
25551 @item 
25552 Click on “Continue” until the certificate is created
25554 @item 
25555 Finally, in the view, double-click on the new certificate,
25556 and set “When using this certificate” to “Always Trust”
25558 @item 
25559 Exit the Keychain Access application and restart the computer
25560 (this is unfortunately required)
25561 @end itemize
25563 Once a certificate has been created, the debugger can be codesigned
25564 as follow. In a Terminal, run the following command:
25566 @quotation
25568 @example
25569 $ codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
25570 @end example
25571 @end quotation
25573 where “gdb-cert” should be replaced by the actual certificate
25574 name chosen above, and <gnat_install_prefix> should be replaced by
25575 the location where you installed GNAT.  Also, be sure that users are
25576 in the Unix group @code{_developer}.
25578 @node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
25579 @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}
25580 @chapter Example of Binder Output File
25583 @geindex Binder output (example)
25585 This Appendix displays the source code for the output file
25586 generated by @emph{gnatbind} for a simple ‘Hello World’ program.
25587 Comments have been added for clarification purposes.
25589 @example
25590 --  The package is called Ada_Main unless this name is actually used
25591 --  as a unit name in the partition, in which case some other unique
25592 --  name is used.
25594 pragma Ada_95;
25595 with System;
25596 package ada_main is
25597    pragma Warnings (Off);
25599    --  The main program saves the parameters (argument count,
25600    --  argument values, environment pointer) in global variables
25601    --  for later access by other units including
25602    --  Ada.Command_Line.
25604    gnat_argc : Integer;
25605    gnat_argv : System.Address;
25606    gnat_envp : System.Address;
25608    --  The actual variables are stored in a library routine. This
25609    --  is useful for some shared library situations, where there
25610    --  are problems if variables are not in the library.
25612    pragma Import (C, gnat_argc);
25613    pragma Import (C, gnat_argv);
25614    pragma Import (C, gnat_envp);
25616    --  The exit status is similarly an external location
25618    gnat_exit_status : Integer;
25619    pragma Import (C, gnat_exit_status);
25621    GNAT_Version : constant String :=
25622                     "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
25623    pragma Export (C, GNAT_Version, "__gnat_version");
25625    Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
25626    pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
25628    --  This is the generated adainit routine that performs
25629    --  initialization at the start of execution. In the case
25630    --  where Ada is the main program, this main program makes
25631    --  a call to adainit at program startup.
25633    procedure adainit;
25634    pragma Export (C, adainit, "adainit");
25636    --  This is the generated adafinal routine that performs
25637    --  finalization at the end of execution. In the case where
25638    --  Ada is the main program, this main program makes a call
25639    --  to adafinal at program termination.
25641    procedure adafinal;
25642    pragma Export (C, adafinal, "adafinal");
25644    --  This routine is called at the start of execution. It is
25645    --  a dummy routine that is used by the debugger to breakpoint
25646    --  at the start of execution.
25648    --  This is the actual generated main program (it would be
25649    --  suppressed if the no main program switch were used). As
25650    --  required by standard system conventions, this program has
25651    --  the external name main.
25653    function main
25654      (argc : Integer;
25655       argv : System.Address;
25656       envp : System.Address)
25657       return Integer;
25658    pragma Export (C, main, "main");
25660    --  The following set of constants give the version
25661    --  identification values for every unit in the bound
25662    --  partition. This identification is computed from all
25663    --  dependent semantic units, and corresponds to the
25664    --  string that would be returned by use of the
25665    --  Body_Version or Version attributes.
25667    --  The following Export pragmas export the version numbers
25668    --  with symbolic names ending in B (for body) or S
25669    --  (for spec) so that they can be located in a link. The
25670    --  information provided here is sufficient to track down
25671    --  the exact versions of units used in a given build.
25673    type Version_32 is mod 2 ** 32;
25674    u00001 : constant Version_32 := 16#8ad6e54a#;
25675    pragma Export (C, u00001, "helloB");
25676    u00002 : constant Version_32 := 16#fbff4c67#;
25677    pragma Export (C, u00002, "system__standard_libraryB");
25678    u00003 : constant Version_32 := 16#1ec6fd90#;
25679    pragma Export (C, u00003, "system__standard_libraryS");
25680    u00004 : constant Version_32 := 16#3ffc8e18#;
25681    pragma Export (C, u00004, "adaS");
25682    u00005 : constant Version_32 := 16#28f088c2#;
25683    pragma Export (C, u00005, "ada__text_ioB");
25684    u00006 : constant Version_32 := 16#f372c8ac#;
25685    pragma Export (C, u00006, "ada__text_ioS");
25686    u00007 : constant Version_32 := 16#2c143749#;
25687    pragma Export (C, u00007, "ada__exceptionsB");
25688    u00008 : constant Version_32 := 16#f4f0cce8#;
25689    pragma Export (C, u00008, "ada__exceptionsS");
25690    u00009 : constant Version_32 := 16#a46739c0#;
25691    pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
25692    u00010 : constant Version_32 := 16#3aac8c92#;
25693    pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
25694    u00011 : constant Version_32 := 16#1d274481#;
25695    pragma Export (C, u00011, "systemS");
25696    u00012 : constant Version_32 := 16#a207fefe#;
25697    pragma Export (C, u00012, "system__soft_linksB");
25698    u00013 : constant Version_32 := 16#467d9556#;
25699    pragma Export (C, u00013, "system__soft_linksS");
25700    u00014 : constant Version_32 := 16#b01dad17#;
25701    pragma Export (C, u00014, "system__parametersB");
25702    u00015 : constant Version_32 := 16#630d49fe#;
25703    pragma Export (C, u00015, "system__parametersS");
25704    u00016 : constant Version_32 := 16#b19b6653#;
25705    pragma Export (C, u00016, "system__secondary_stackB");
25706    u00017 : constant Version_32 := 16#b6468be8#;
25707    pragma Export (C, u00017, "system__secondary_stackS");
25708    u00018 : constant Version_32 := 16#39a03df9#;
25709    pragma Export (C, u00018, "system__storage_elementsB");
25710    u00019 : constant Version_32 := 16#30e40e85#;
25711    pragma Export (C, u00019, "system__storage_elementsS");
25712    u00020 : constant Version_32 := 16#41837d1e#;
25713    pragma Export (C, u00020, "system__stack_checkingB");
25714    u00021 : constant Version_32 := 16#93982f69#;
25715    pragma Export (C, u00021, "system__stack_checkingS");
25716    u00022 : constant Version_32 := 16#393398c1#;
25717    pragma Export (C, u00022, "system__exception_tableB");
25718    u00023 : constant Version_32 := 16#b33e2294#;
25719    pragma Export (C, u00023, "system__exception_tableS");
25720    u00024 : constant Version_32 := 16#ce4af020#;
25721    pragma Export (C, u00024, "system__exceptionsB");
25722    u00025 : constant Version_32 := 16#75442977#;
25723    pragma Export (C, u00025, "system__exceptionsS");
25724    u00026 : constant Version_32 := 16#37d758f1#;
25725    pragma Export (C, u00026, "system__exceptions__machineS");
25726    u00027 : constant Version_32 := 16#b895431d#;
25727    pragma Export (C, u00027, "system__exceptions_debugB");
25728    u00028 : constant Version_32 := 16#aec55d3f#;
25729    pragma Export (C, u00028, "system__exceptions_debugS");
25730    u00029 : constant Version_32 := 16#570325c8#;
25731    pragma Export (C, u00029, "system__img_intB");
25732    u00030 : constant Version_32 := 16#1ffca443#;
25733    pragma Export (C, u00030, "system__img_intS");
25734    u00031 : constant Version_32 := 16#b98c3e16#;
25735    pragma Export (C, u00031, "system__tracebackB");
25736    u00032 : constant Version_32 := 16#831a9d5a#;
25737    pragma Export (C, u00032, "system__tracebackS");
25738    u00033 : constant Version_32 := 16#9ed49525#;
25739    pragma Export (C, u00033, "system__traceback_entriesB");
25740    u00034 : constant Version_32 := 16#1d7cb2f1#;
25741    pragma Export (C, u00034, "system__traceback_entriesS");
25742    u00035 : constant Version_32 := 16#8c33a517#;
25743    pragma Export (C, u00035, "system__wch_conB");
25744    u00036 : constant Version_32 := 16#065a6653#;
25745    pragma Export (C, u00036, "system__wch_conS");
25746    u00037 : constant Version_32 := 16#9721e840#;
25747    pragma Export (C, u00037, "system__wch_stwB");
25748    u00038 : constant Version_32 := 16#2b4b4a52#;
25749    pragma Export (C, u00038, "system__wch_stwS");
25750    u00039 : constant Version_32 := 16#92b797cb#;
25751    pragma Export (C, u00039, "system__wch_cnvB");
25752    u00040 : constant Version_32 := 16#09eddca0#;
25753    pragma Export (C, u00040, "system__wch_cnvS");
25754    u00041 : constant Version_32 := 16#6033a23f#;
25755    pragma Export (C, u00041, "interfacesS");
25756    u00042 : constant Version_32 := 16#ece6fdb6#;
25757    pragma Export (C, u00042, "system__wch_jisB");
25758    u00043 : constant Version_32 := 16#899dc581#;
25759    pragma Export (C, u00043, "system__wch_jisS");
25760    u00044 : constant Version_32 := 16#10558b11#;
25761    pragma Export (C, u00044, "ada__streamsB");
25762    u00045 : constant Version_32 := 16#2e6701ab#;
25763    pragma Export (C, u00045, "ada__streamsS");
25764    u00046 : constant Version_32 := 16#db5c917c#;
25765    pragma Export (C, u00046, "ada__io_exceptionsS");
25766    u00047 : constant Version_32 := 16#12c8cd7d#;
25767    pragma Export (C, u00047, "ada__tagsB");
25768    u00048 : constant Version_32 := 16#ce72c228#;
25769    pragma Export (C, u00048, "ada__tagsS");
25770    u00049 : constant Version_32 := 16#c3335bfd#;
25771    pragma Export (C, u00049, "system__htableB");
25772    u00050 : constant Version_32 := 16#99e5f76b#;
25773    pragma Export (C, u00050, "system__htableS");
25774    u00051 : constant Version_32 := 16#089f5cd0#;
25775    pragma Export (C, u00051, "system__string_hashB");
25776    u00052 : constant Version_32 := 16#3bbb9c15#;
25777    pragma Export (C, u00052, "system__string_hashS");
25778    u00053 : constant Version_32 := 16#807fe041#;
25779    pragma Export (C, u00053, "system__unsigned_typesS");
25780    u00054 : constant Version_32 := 16#d27be59e#;
25781    pragma Export (C, u00054, "system__val_lluB");
25782    u00055 : constant Version_32 := 16#fa8db733#;
25783    pragma Export (C, u00055, "system__val_lluS");
25784    u00056 : constant Version_32 := 16#27b600b2#;
25785    pragma Export (C, u00056, "system__val_utilB");
25786    u00057 : constant Version_32 := 16#b187f27f#;
25787    pragma Export (C, u00057, "system__val_utilS");
25788    u00058 : constant Version_32 := 16#d1060688#;
25789    pragma Export (C, u00058, "system__case_utilB");
25790    u00059 : constant Version_32 := 16#392e2d56#;
25791    pragma Export (C, u00059, "system__case_utilS");
25792    u00060 : constant Version_32 := 16#84a27f0d#;
25793    pragma Export (C, u00060, "interfaces__c_streamsB");
25794    u00061 : constant Version_32 := 16#8bb5f2c0#;
25795    pragma Export (C, u00061, "interfaces__c_streamsS");
25796    u00062 : constant Version_32 := 16#6db6928f#;
25797    pragma Export (C, u00062, "system__crtlS");
25798    u00063 : constant Version_32 := 16#4e6a342b#;
25799    pragma Export (C, u00063, "system__file_ioB");
25800    u00064 : constant Version_32 := 16#ba56a5e4#;
25801    pragma Export (C, u00064, "system__file_ioS");
25802    u00065 : constant Version_32 := 16#b7ab275c#;
25803    pragma Export (C, u00065, "ada__finalizationB");
25804    u00066 : constant Version_32 := 16#19f764ca#;
25805    pragma Export (C, u00066, "ada__finalizationS");
25806    u00067 : constant Version_32 := 16#95817ed8#;
25807    pragma Export (C, u00067, "system__finalization_rootB");
25808    u00068 : constant Version_32 := 16#52d53711#;
25809    pragma Export (C, u00068, "system__finalization_rootS");
25810    u00069 : constant Version_32 := 16#769e25e6#;
25811    pragma Export (C, u00069, "interfaces__cB");
25812    u00070 : constant Version_32 := 16#4a38bedb#;
25813    pragma Export (C, u00070, "interfaces__cS");
25814    u00071 : constant Version_32 := 16#07e6ee66#;
25815    pragma Export (C, u00071, "system__os_libB");
25816    u00072 : constant Version_32 := 16#d7b69782#;
25817    pragma Export (C, u00072, "system__os_libS");
25818    u00073 : constant Version_32 := 16#1a817b8e#;
25819    pragma Export (C, u00073, "system__stringsB");
25820    u00074 : constant Version_32 := 16#639855e7#;
25821    pragma Export (C, u00074, "system__stringsS");
25822    u00075 : constant Version_32 := 16#e0b8de29#;
25823    pragma Export (C, u00075, "system__file_control_blockS");
25824    u00076 : constant Version_32 := 16#b5b2aca1#;
25825    pragma Export (C, u00076, "system__finalization_mastersB");
25826    u00077 : constant Version_32 := 16#69316dc1#;
25827    pragma Export (C, u00077, "system__finalization_mastersS");
25828    u00078 : constant Version_32 := 16#57a37a42#;
25829    pragma Export (C, u00078, "system__address_imageB");
25830    u00079 : constant Version_32 := 16#bccbd9bb#;
25831    pragma Export (C, u00079, "system__address_imageS");
25832    u00080 : constant Version_32 := 16#7268f812#;
25833    pragma Export (C, u00080, "system__img_boolB");
25834    u00081 : constant Version_32 := 16#e8fe356a#;
25835    pragma Export (C, u00081, "system__img_boolS");
25836    u00082 : constant Version_32 := 16#d7aac20c#;
25837    pragma Export (C, u00082, "system__ioB");
25838    u00083 : constant Version_32 := 16#8365b3ce#;
25839    pragma Export (C, u00083, "system__ioS");
25840    u00084 : constant Version_32 := 16#6d4d969a#;
25841    pragma Export (C, u00084, "system__storage_poolsB");
25842    u00085 : constant Version_32 := 16#e87cc305#;
25843    pragma Export (C, u00085, "system__storage_poolsS");
25844    u00086 : constant Version_32 := 16#e34550ca#;
25845    pragma Export (C, u00086, "system__pool_globalB");
25846    u00087 : constant Version_32 := 16#c88d2d16#;
25847    pragma Export (C, u00087, "system__pool_globalS");
25848    u00088 : constant Version_32 := 16#9d39c675#;
25849    pragma Export (C, u00088, "system__memoryB");
25850    u00089 : constant Version_32 := 16#445a22b5#;
25851    pragma Export (C, u00089, "system__memoryS");
25852    u00090 : constant Version_32 := 16#6a859064#;
25853    pragma Export (C, u00090, "system__storage_pools__subpoolsB");
25854    u00091 : constant Version_32 := 16#e3b008dc#;
25855    pragma Export (C, u00091, "system__storage_pools__subpoolsS");
25856    u00092 : constant Version_32 := 16#63f11652#;
25857    pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
25858    u00093 : constant Version_32 := 16#fe2f4b3a#;
25859    pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
25861    --  BEGIN ELABORATION ORDER
25862    --  ada%s
25863    --  interfaces%s
25864    --  system%s
25865    --  system.case_util%s
25866    --  system.case_util%b
25867    --  system.htable%s
25868    --  system.img_bool%s
25869    --  system.img_bool%b
25870    --  system.img_int%s
25871    --  system.img_int%b
25872    --  system.io%s
25873    --  system.io%b
25874    --  system.parameters%s
25875    --  system.parameters%b
25876    --  system.crtl%s
25877    --  interfaces.c_streams%s
25878    --  interfaces.c_streams%b
25879    --  system.standard_library%s
25880    --  system.exceptions_debug%s
25881    --  system.exceptions_debug%b
25882    --  system.storage_elements%s
25883    --  system.storage_elements%b
25884    --  system.stack_checking%s
25885    --  system.stack_checking%b
25886    --  system.string_hash%s
25887    --  system.string_hash%b
25888    --  system.htable%b
25889    --  system.strings%s
25890    --  system.strings%b
25891    --  system.os_lib%s
25892    --  system.traceback_entries%s
25893    --  system.traceback_entries%b
25894    --  ada.exceptions%s
25895    --  system.soft_links%s
25896    --  system.unsigned_types%s
25897    --  system.val_llu%s
25898    --  system.val_util%s
25899    --  system.val_util%b
25900    --  system.val_llu%b
25901    --  system.wch_con%s
25902    --  system.wch_con%b
25903    --  system.wch_cnv%s
25904    --  system.wch_jis%s
25905    --  system.wch_jis%b
25906    --  system.wch_cnv%b
25907    --  system.wch_stw%s
25908    --  system.wch_stw%b
25909    --  ada.exceptions.last_chance_handler%s
25910    --  ada.exceptions.last_chance_handler%b
25911    --  system.address_image%s
25912    --  system.exception_table%s
25913    --  system.exception_table%b
25914    --  ada.io_exceptions%s
25915    --  ada.tags%s
25916    --  ada.streams%s
25917    --  ada.streams%b
25918    --  interfaces.c%s
25919    --  system.exceptions%s
25920    --  system.exceptions%b
25921    --  system.exceptions.machine%s
25922    --  system.finalization_root%s
25923    --  system.finalization_root%b
25924    --  ada.finalization%s
25925    --  ada.finalization%b
25926    --  system.storage_pools%s
25927    --  system.storage_pools%b
25928    --  system.finalization_masters%s
25929    --  system.storage_pools.subpools%s
25930    --  system.storage_pools.subpools.finalization%s
25931    --  system.storage_pools.subpools.finalization%b
25932    --  system.memory%s
25933    --  system.memory%b
25934    --  system.standard_library%b
25935    --  system.pool_global%s
25936    --  system.pool_global%b
25937    --  system.file_control_block%s
25938    --  system.file_io%s
25939    --  system.secondary_stack%s
25940    --  system.file_io%b
25941    --  system.storage_pools.subpools%b
25942    --  system.finalization_masters%b
25943    --  interfaces.c%b
25944    --  ada.tags%b
25945    --  system.soft_links%b
25946    --  system.os_lib%b
25947    --  system.secondary_stack%b
25948    --  system.address_image%b
25949    --  system.traceback%s
25950    --  ada.exceptions%b
25951    --  system.traceback%b
25952    --  ada.text_io%s
25953    --  ada.text_io%b
25954    --  hello%b
25955    --  END ELABORATION ORDER
25957 end ada_main;
25958 @end example
25960 @example
25961 pragma Ada_95;
25962 --  The following source file name pragmas allow the generated file
25963 --  names to be unique for different main programs. They are needed
25964 --  since the package name will always be Ada_Main.
25966 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
25967 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
25969 pragma Suppress (Overflow_Check);
25970 with Ada.Exceptions;
25972 --  Generated package body for Ada_Main starts here
25974 package body ada_main is
25975    pragma Warnings (Off);
25977    --  These values are reference counter associated to units which have
25978    --  been elaborated. It is also used to avoid elaborating the
25979    --  same unit twice.
25981    E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
25982    E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
25983    E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
25984    E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
25985    E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
25986    E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
25987    E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
25988    E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
25989    E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
25990    E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
25991    E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
25992    E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
25993    E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
25994    E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
25995    E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
25996    E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
25997    E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
25998    E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
26000    Local_Priority_Specific_Dispatching : constant String := "";
26001    Local_Interrupt_States : constant String := "";
26003    Is_Elaborated : Boolean := False;
26005    procedure finalize_library is
26006    begin
26007       E06 := E06 - 1;
26008       declare
26009          procedure F1;
26010          pragma Import (Ada, F1, "ada__text_io__finalize_spec");
26011       begin
26012          F1;
26013       end;
26014       E77 := E77 - 1;
26015       E91 := E91 - 1;
26016       declare
26017          procedure F2;
26018          pragma Import (Ada, F2, "system__file_io__finalize_body");
26019       begin
26020          E64 := E64 - 1;
26021          F2;
26022       end;
26023       declare
26024          procedure F3;
26025          pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
26026       begin
26027          E75 := E75 - 1;
26028          F3;
26029       end;
26030       E87 := E87 - 1;
26031       declare
26032          procedure F4;
26033          pragma Import (Ada, F4, "system__pool_global__finalize_spec");
26034       begin
26035          F4;
26036       end;
26037       declare
26038          procedure F5;
26039          pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
26040       begin
26041          F5;
26042       end;
26043       declare
26044          procedure F6;
26045          pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
26046       begin
26047          F6;
26048       end;
26049       declare
26050          procedure Reraise_Library_Exception_If_Any;
26051          pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
26052       begin
26053          Reraise_Library_Exception_If_Any;
26054       end;
26055    end finalize_library;
26057    -------------
26058    -- adainit --
26059    -------------
26061    procedure adainit is
26063       Main_Priority : Integer;
26064       pragma Import (C, Main_Priority, "__gl_main_priority");
26065       Time_Slice_Value : Integer;
26066       pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
26067       WC_Encoding : Character;
26068       pragma Import (C, WC_Encoding, "__gl_wc_encoding");
26069       Locking_Policy : Character;
26070       pragma Import (C, Locking_Policy, "__gl_locking_policy");
26071       Queuing_Policy : Character;
26072       pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
26073       Task_Dispatching_Policy : Character;
26074       pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
26075       Priority_Specific_Dispatching : System.Address;
26076       pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
26077       Num_Specific_Dispatching : Integer;
26078       pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
26079       Main_CPU : Integer;
26080       pragma Import (C, Main_CPU, "__gl_main_cpu");
26081       Interrupt_States : System.Address;
26082       pragma Import (C, Interrupt_States, "__gl_interrupt_states");
26083       Num_Interrupt_States : Integer;
26084       pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
26085       Unreserve_All_Interrupts : Integer;
26086       pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
26087       Detect_Blocking : Integer;
26088       pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
26089       Default_Stack_Size : Integer;
26090       pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
26091       Leap_Seconds_Support : Integer;
26092       pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
26094       procedure Runtime_Initialize;
26095       pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
26097       Finalize_Library_Objects : No_Param_Proc;
26098       pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
26100    --  Start of processing for adainit
26102    begin
26104       --  Record various information for this partition.  The values
26105       --  are derived by the binder from information stored in the ali
26106       --  files by the compiler.
26108       if Is_Elaborated then
26109          return;
26110       end if;
26111       Is_Elaborated := True;
26112       Main_Priority := -1;
26113       Time_Slice_Value := -1;
26114       WC_Encoding := 'b';
26115       Locking_Policy := ' ';
26116       Queuing_Policy := ' ';
26117       Task_Dispatching_Policy := ' ';
26118       Priority_Specific_Dispatching :=
26119         Local_Priority_Specific_Dispatching'Address;
26120       Num_Specific_Dispatching := 0;
26121       Main_CPU := -1;
26122       Interrupt_States := Local_Interrupt_States'Address;
26123       Num_Interrupt_States := 0;
26124       Unreserve_All_Interrupts := 0;
26125       Detect_Blocking := 0;
26126       Default_Stack_Size := -1;
26127       Leap_Seconds_Support := 0;
26129       Runtime_Initialize;
26131       Finalize_Library_Objects := finalize_library'access;
26133       --  Now we have the elaboration calls for all units in the partition.
26134       --  The Elab_Spec and Elab_Body attributes generate references to the
26135       --  implicit elaboration procedures generated by the compiler for
26136       --  each unit that requires elaboration. Increment a counter of
26137       --  reference for each unit.
26139       System.Soft_Links'Elab_Spec;
26140       System.Exception_Table'Elab_Body;
26141       E23 := E23 + 1;
26142       Ada.Io_Exceptions'Elab_Spec;
26143       E46 := E46 + 1;
26144       Ada.Tags'Elab_Spec;
26145       Ada.Streams'Elab_Spec;
26146       E45 := E45 + 1;
26147       Interfaces.C'Elab_Spec;
26148       System.Exceptions'Elab_Spec;
26149       E25 := E25 + 1;
26150       System.Finalization_Root'Elab_Spec;
26151       E68 := E68 + 1;
26152       Ada.Finalization'Elab_Spec;
26153       E66 := E66 + 1;
26154       System.Storage_Pools'Elab_Spec;
26155       E85 := E85 + 1;
26156       System.Finalization_Masters'Elab_Spec;
26157       System.Storage_Pools.Subpools'Elab_Spec;
26158       System.Pool_Global'Elab_Spec;
26159       E87 := E87 + 1;
26160       System.File_Control_Block'Elab_Spec;
26161       E75 := E75 + 1;
26162       System.File_Io'Elab_Body;
26163       E64 := E64 + 1;
26164       E91 := E91 + 1;
26165       System.Finalization_Masters'Elab_Body;
26166       E77 := E77 + 1;
26167       E70 := E70 + 1;
26168       Ada.Tags'Elab_Body;
26169       E48 := E48 + 1;
26170       System.Soft_Links'Elab_Body;
26171       E13 := E13 + 1;
26172       System.Os_Lib'Elab_Body;
26173       E72 := E72 + 1;
26174       System.Secondary_Stack'Elab_Body;
26175       E17 := E17 + 1;
26176       Ada.Text_Io'Elab_Spec;
26177       Ada.Text_Io'Elab_Body;
26178       E06 := E06 + 1;
26179    end adainit;
26181    --------------
26182    -- adafinal --
26183    --------------
26185    procedure adafinal is
26186       procedure s_stalib_adafinal;
26187       pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
26189       procedure Runtime_Finalize;
26190       pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
26192    begin
26193       if not Is_Elaborated then
26194          return;
26195       end if;
26196       Is_Elaborated := False;
26197       Runtime_Finalize;
26198       s_stalib_adafinal;
26199    end adafinal;
26201    --  We get to the main program of the partition by using
26202    --  pragma Import because if we try to with the unit and
26203    --  call it Ada style, then not only do we waste time
26204    --  recompiling it, but also, we don't really know the right
26205    --  switches (e.g.@@: identifier character set) to be used
26206    --  to compile it.
26208    procedure Ada_Main_Program;
26209    pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26211    ----------
26212    -- main --
26213    ----------
26215    --  main is actually a function, as in the ANSI C standard,
26216    --  defined to return the exit status. The three parameters
26217    --  are the argument count, argument values and environment
26218    --  pointer.
26220    function main
26221      (argc : Integer;
26222       argv : System.Address;
26223       envp : System.Address)
26224       return Integer
26225    is
26226       --  The initialize routine performs low level system
26227       --  initialization using a standard library routine which
26228       --  sets up signal handling and performs any other
26229       --  required setup. The routine can be found in file
26230       --  a-init.c.
26232       procedure initialize;
26233       pragma Import (C, initialize, "__gnat_initialize");
26235       --  The finalize routine performs low level system
26236       --  finalization using a standard library routine. The
26237       --  routine is found in file a-final.c and in the standard
26238       --  distribution is a dummy routine that does nothing, so
26239       --  really this is a hook for special user finalization.
26241       procedure finalize;
26242       pragma Import (C, finalize, "__gnat_finalize");
26244       --  The following is to initialize the SEH exceptions
26246       SEH : aliased array (1 .. 2) of Integer;
26248       Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
26249       pragma Volatile (Ensure_Reference);
26251    --  Start of processing for main
26253    begin
26254       --  Save global variables
26256       gnat_argc := argc;
26257       gnat_argv := argv;
26258       gnat_envp := envp;
26260       --  Call low level system initialization
26262       Initialize (SEH'Address);
26264       --  Call our generated Ada initialization routine
26266       adainit;
26268       --  Now we call the main program of the partition
26270       Ada_Main_Program;
26272       --  Perform Ada finalization
26274       adafinal;
26276       --  Perform low level system finalization
26278       Finalize;
26280       --  Return the proper exit status
26281       return (gnat_exit_status);
26282    end;
26284 --  This section is entirely comments, so it has no effect on the
26285 --  compilation of the Ada_Main package. It provides the list of
26286 --  object files and linker options, as well as some standard
26287 --  libraries needed for the link. The gnatlink utility parses
26288 --  this b~hello.adb file to read these comment lines to generate
26289 --  the appropriate command line arguments for the call to the
26290 --  system linker. The BEGIN/END lines are used for sentinels for
26291 --  this parsing operation.
26293 --  The exact file names will of course depend on the environment,
26294 --  host/target and location of files on the host system.
26296 -- BEGIN Object file/option list
26297    --   ./hello.o
26298    --   -L./
26299    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
26300    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
26301 -- END Object file/option list
26303 end ada_main;
26304 @end example
26306 The Ada code in the above example is exactly what is generated by the
26307 binder. We have added comments to more clearly indicate the function
26308 of each part of the generated @code{Ada_Main} package.
26310 The code is standard Ada in all respects, and can be processed by any
26311 tools that handle Ada. In particular, it is possible to use the debugger
26312 in Ada mode to debug the generated @code{Ada_Main} package. For example,
26313 suppose that for reasons that you do not understand, your program is crashing
26314 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
26315 you can place a breakpoint on the call:
26317 @quotation
26319 @example
26320 Ada.Text_Io'Elab_Body;
26321 @end example
26322 @end quotation
26324 and trace the elaboration routine for this package to find out where
26325 the problem might be (more usually of course you would be debugging
26326 elaboration code in your own application).
26328 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
26330 @node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
26331 @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}
26332 @chapter Elaboration Order Handling in GNAT
26335 @geindex Order of elaboration
26337 @geindex Elaboration control
26339 This appendix describes the handling of elaboration code in Ada and GNAT, and
26340 discusses how the order of elaboration of program units can be controlled in
26341 GNAT, either automatically or with explicit programming features.
26343 @menu
26344 * Elaboration Code:: 
26345 * Elaboration Order:: 
26346 * Checking the Elaboration Order:: 
26347 * Controlling the Elaboration Order in Ada:: 
26348 * Controlling the Elaboration Order in GNAT:: 
26349 * Mixing Elaboration Models:: 
26350 * ABE Diagnostics:: 
26351 * SPARK Diagnostics:: 
26352 * Elaboration Circularities:: 
26353 * Resolving Elaboration Circularities:: 
26354 * Elaboration-related Compiler Switches:: 
26355 * Summary of Procedures for Elaboration Control:: 
26356 * Inspecting the Chosen Elaboration Order:: 
26358 @end menu
26360 @node Elaboration Code,Elaboration Order,,Elaboration Order Handling in GNAT
26361 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{21c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{21d}
26362 @section Elaboration Code
26365 Ada defines the term @emph{execution} as the process by which a construct achieves
26366 its run-time effect. This process is also referred to as @strong{elaboration} for
26367 declarations and @emph{evaluation} for expressions.
26369 The execution model in Ada allows for certain sections of an Ada program to be
26370 executed prior to execution of the program itself, primarily with the intent of
26371 initializing data. These sections are referred to as @strong{elaboration code}.
26372 Elaboration code is executed as follows:
26375 @itemize *
26377 @item 
26378 All partitions of an Ada program are executed in parallel with one another,
26379 possibly in a separate address space, and possibly on a separate computer.
26381 @item 
26382 The execution of a partition involves running the environment task for that
26383 partition.
26385 @item 
26386 The environment task executes all elaboration code (if available) for all
26387 units within that partition. This code is said to be executed at
26388 @strong{elaboration time}.
26390 @item 
26391 The environment task executes the Ada program (if available) for that
26392 partition.
26393 @end itemize
26395 In addition to the Ada terminology, this appendix defines the following terms:
26398 @itemize *
26400 @item 
26401 @emph{Invocation}
26403 The act of calling a subprogram, instantiating a generic, or activating a
26404 task.
26406 @item 
26407 @emph{Scenario}
26409 A construct that is elaborated or invoked by elaboration code is referred to
26410 as an @emph{elaboration scenario} or simply a @strong{scenario}. GNAT recognizes the
26411 following scenarios:
26414 @itemize -
26416 @item 
26417 @code{'Access} of entries, operators, and subprograms
26419 @item 
26420 Activation of tasks
26422 @item 
26423 Calls to entries, operators, and subprograms
26425 @item 
26426 Instantiations of generic templates
26427 @end itemize
26429 @item 
26430 @emph{Target}
26432 A construct elaborated by a scenario is referred to as @emph{elaboration target}
26433 or simply @strong{target}. GNAT recognizes the following targets:
26436 @itemize -
26438 @item 
26439 For @code{'Access} of entries, operators, and subprograms, the target is the
26440 entry, operator, or subprogram being aliased.
26442 @item 
26443 For activation of tasks, the target is the task body
26445 @item 
26446 For calls to entries, operators, and subprograms, the target is the entry,
26447 operator, or subprogram being invoked.
26449 @item 
26450 For instantiations of generic templates, the target is the generic template
26451 being instantiated.
26452 @end itemize
26453 @end itemize
26455 Elaboration code may appear in two distinct contexts:
26458 @itemize *
26460 @item 
26461 @emph{Library level}
26463 A scenario appears at the library level when it is encapsulated by a package
26464 [body] compilation unit, ignoring any other package [body] declarations in
26465 between.
26467 @example
26468 with Server;
26469 package Client is
26470    procedure Proc;
26472    package Nested is
26473       Val : ... := Server.Func;
26474    end Nested;
26475 end Client;
26476 @end example
26478 In the example above, the call to @code{Server.Func} is an elaboration scenario
26479 because it appears at the library level of package @code{Client}. Note that the
26480 declaration of package @code{Nested} is ignored according to the definition
26481 given above. As a result, the call to @code{Server.Func} will be invoked when
26482 the spec of unit @code{Client} is elaborated.
26484 @item 
26485 @emph{Package body statements}
26487 A scenario appears within the statement sequence of a package body when it is
26488 bounded by the region starting from the @code{begin} keyword of the package body
26489 and ending at the @code{end} keyword of the package body.
26491 @example
26492 package body Client is
26493    procedure Proc is
26494    begin
26495       ...
26496    end Proc;
26497 begin
26498    Proc;
26499 end Client;
26500 @end example
26502 In the example above, the call to @code{Proc} is an elaboration scenario because
26503 it appears within the statement sequence of package body @code{Client}. As a
26504 result, the call to @code{Proc} will be invoked when the body of @code{Client} is
26505 elaborated.
26506 @end itemize
26508 @node Elaboration Order,Checking the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
26509 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order}@anchor{21e}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{21f}
26510 @section Elaboration Order
26513 The sequence by which the elaboration code of all units within a partition is
26514 executed is referred to as @strong{elaboration order}.
26516 Within a single unit, elaboration code is executed in sequential order.
26518 @quotation
26520 @example
26521 package body Client is
26522    Result : ... := Server.Func;
26524    procedure Proc is
26525       package Inst is new Server.Gen;
26526    begin
26527       Inst.Eval (Result);
26528    end Proc;
26529 begin
26530    Proc;
26531 end Client;
26532 @end example
26533 @end quotation
26535 In the example above, the elaboration order within package body @code{Client} is
26536 as follows:
26539 @enumerate 
26541 @item 
26542 The object declaration of @code{Result} is elaborated.
26545 @itemize *
26547 @item 
26548 Function @code{Server.Func} is invoked.
26549 @end itemize
26551 @item 
26552 The subprogram body of @code{Proc} is elaborated.
26554 @item 
26555 Procedure @code{Proc} is invoked.
26558 @itemize *
26560 @item 
26561 Generic unit @code{Server.Gen} is instantiated as @code{Inst}.
26563 @item 
26564 Instance @code{Inst} is elaborated.
26566 @item 
26567 Procedure @code{Inst.Eval} is invoked.
26568 @end itemize
26569 @end enumerate
26571 The elaboration order of all units within a partition depends on the following
26572 factors:
26575 @itemize *
26577 @item 
26578 @emph{with}ed units
26580 @item 
26581 parent units
26583 @item 
26584 purity of units
26586 @item 
26587 preelaborability of units
26589 @item 
26590 presence of elaboration-control pragmas
26592 @item 
26593 invocations performed in elaboration code
26594 @end itemize
26596 A program may have several elaboration orders depending on its structure.
26598 @quotation
26600 @example
26601 package Server is
26602    function Func (Index : Integer) return Integer;
26603 end Server;
26604 @end example
26606 @example
26607 package body Server is
26608    Results : array (1 .. 5) of Integer := (1, 2, 3, 4, 5);
26610    function Func (Index : Integer) return Integer is
26611    begin
26612       return Results (Index);
26613    end Func;
26614 end Server;
26615 @end example
26617 @example
26618 with Server;
26619 package Client is
26620    Val : constant Integer := Server.Func (3);
26621 end Client;
26622 @end example
26624 @example
26625 with Client;
26626 procedure Main is begin null; end Main;
26627 @end example
26628 @end quotation
26630 The following elaboration order exhibits a fundamental problem referred to as
26631 @emph{access-before-elaboration} or simply @strong{ABE}.
26633 @quotation
26635 @example
26636 spec of Server
26637 spec of Client
26638 body of Server
26639 body of Main
26640 @end example
26641 @end quotation
26643 The elaboration of @code{Server}’s spec materializes function @code{Func}, making it
26644 callable. The elaboration of @code{Client}’s spec elaborates the declaration of
26645 @code{Val}. This invokes function @code{Server.Func}, however the body of
26646 @code{Server.Func} has not been elaborated yet because @code{Server}’s body comes
26647 after @code{Client}’s spec in the elaboration order. As a result, the value of
26648 constant @code{Val} is now undefined.
26650 Without any guarantees from the language, an undetected ABE problem may hinder
26651 proper initialization of data, which in turn may lead to undefined behavior at
26652 run time. To prevent such ABE problems, Ada employs dynamic checks in the same
26653 vein as index or null exclusion checks. A failed ABE check raises exception
26654 @code{Program_Error}.
26656 The following elaboration order avoids the ABE problem and the program can be
26657 successfully elaborated.
26659 @quotation
26661 @example
26662 spec of Server
26663 body of Server
26664 spec of Client
26665 body of Main
26666 @end example
26667 @end quotation
26669 Ada states that a total elaboration order must exist, but it does not define
26670 what this order is. A compiler is thus tasked with choosing a suitable
26671 elaboration order which satisfies the dependencies imposed by @emph{with} clauses,
26672 unit categorization, elaboration-control pragmas, and invocations performed in
26673 elaboration code. Ideally an order that avoids ABE problems should be chosen,
26674 however a compiler may not always find such an order due to complications with
26675 respect to control and data flow.
26677 @node Checking the Elaboration Order,Controlling the Elaboration Order in Ada,Elaboration Order,Elaboration Order Handling in GNAT
26678 @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}
26679 @section Checking the Elaboration Order
26682 To avoid placing the entire elaboration-order burden on the programmer, Ada
26683 provides three lines of defense:
26686 @itemize *
26688 @item 
26689 @emph{Static semantics}
26691 Static semantic rules restrict the possible choice of elaboration order. For
26692 instance, if unit Client @emph{with}s unit Server, then the spec of Server is
26693 always elaborated prior to Client. The same principle applies to child units
26694 - the spec of a parent unit is always elaborated prior to the child unit.
26696 @item 
26697 @emph{Dynamic semantics}
26699 Dynamic checks are performed at run time, to ensure that a target is
26700 elaborated prior to a scenario that invokes it, thus avoiding ABE problems.
26701 A failed run-time check raises exception @code{Program_Error}. The following
26702 restrictions apply:
26705 @itemize -
26707 @item 
26708 @emph{Restrictions on calls}
26710 An entry, operator, or subprogram can be called from elaboration code only
26711 when the corresponding body has been elaborated.
26713 @item 
26714 @emph{Restrictions on instantiations}
26716 A generic unit can be instantiated by elaboration code only when the
26717 corresponding body has been elaborated.
26719 @item 
26720 @emph{Restrictions on task activation}
26722 A task can be activated by elaboration code only when the body of the
26723 associated task type has been elaborated.
26724 @end itemize
26726 The restrictions above can be summarized by the following rule:
26728 @emph{If a target has a body, then this body must be elaborated prior to the
26729 scenario that invokes the target.}
26731 @item 
26732 @emph{Elaboration control}
26734 Pragmas are provided for the programmer to specify the desired elaboration
26735 order.
26736 @end itemize
26738 @node Controlling the Elaboration Order in Ada,Controlling the Elaboration Order in GNAT,Checking the Elaboration Order,Elaboration Order Handling in GNAT
26739 @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}
26740 @section Controlling the Elaboration Order in Ada
26743 Ada provides several idioms and pragmas to aid the programmer with specifying
26744 the desired elaboration order and avoiding ABE problems altogether.
26747 @itemize *
26749 @item 
26750 @emph{Packages without a body}
26752 A library package which does not require a completing body does not suffer
26753 from ABE problems.
26755 @example
26756 package Pack is
26757    generic
26758       type Element is private;
26759    package Containers is
26760       type Element_Array is array (1 .. 10) of Element;
26761    end Containers;
26762 end Pack;
26763 @end example
26765 In the example above, package @code{Pack} does not require a body because it
26766 does not contain any constructs which require completion in a body. As a
26767 result, generic @code{Pack.Containers} can be instantiated without encountering
26768 any ABE problems.
26769 @end itemize
26771 @geindex pragma Pure
26774 @itemize *
26776 @item 
26777 @emph{pragma Pure}
26779 Pragma @code{Pure} places sufficient restrictions on a unit to guarantee that no
26780 scenario within the unit can result in an ABE problem.
26781 @end itemize
26783 @geindex pragma Preelaborate
26786 @itemize *
26788 @item 
26789 @emph{pragma Preelaborate}
26791 Pragma @code{Preelaborate} is slightly less restrictive than pragma @code{Pure},
26792 but still strong enough to prevent ABE problems within a unit.
26793 @end itemize
26795 @geindex pragma Elaborate_Body
26798 @itemize *
26800 @item 
26801 @emph{pragma Elaborate_Body}
26803 Pragma @code{Elaborate_Body} requires that the body of a unit is elaborated
26804 immediately after its spec. This restriction guarantees that no client
26805 scenario can invoke a server target before the target body has been
26806 elaborated because the spec and body are effectively “glued” together.
26808 @example
26809 package Server is
26810    pragma Elaborate_Body;
26812    function Func return Integer;
26813 end Server;
26814 @end example
26816 @example
26817 package body Server is
26818    function Func return Integer is
26819    begin
26820       ...
26821    end Func;
26822 end Server;
26823 @end example
26825 @example
26826 with Server;
26827 package Client is
26828    Val : constant Integer := Server.Func;
26829 end Client;
26830 @end example
26832 In the example above, pragma @code{Elaborate_Body} guarantees the following
26833 elaboration order:
26835 @example
26836 spec of Server
26837 body of Server
26838 spec of Client
26839 @end example
26841 because the spec of @code{Server} must be elaborated prior to @code{Client} by
26842 virtue of the @emph{with} clause, and in addition the body of @code{Server} must be
26843 elaborated immediately after the spec of @code{Server}.
26845 Removing pragma @code{Elaborate_Body} could result in the following incorrect
26846 elaboration order:
26848 @example
26849 spec of Server
26850 spec of Client
26851 body of Server
26852 @end example
26854 where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func} has
26855 not been elaborated yet.
26856 @end itemize
26858 The pragmas outlined above allow a server unit to guarantee safe elaboration
26859 use by client units. Thus it is a good rule to mark units as @code{Pure} or
26860 @code{Preelaborate}, and if this is not possible, mark them as @code{Elaborate_Body}.
26862 There are however situations where @code{Pure}, @code{Preelaborate}, and
26863 @code{Elaborate_Body} are not applicable. Ada provides another set of pragmas for
26864 use by client units to help ensure the elaboration safety of server units they
26865 depend on.
26867 @geindex pragma Elaborate (Unit)
26870 @itemize *
26872 @item 
26873 @emph{pragma Elaborate (Unit)}
26875 Pragma @code{Elaborate} can be placed in the context clauses of a unit, after a
26876 @emph{with} clause. It guarantees that both the spec and body of its argument will
26877 be elaborated prior to the unit with the pragma. Note that other unrelated
26878 units may be elaborated in between the spec and the body.
26880 @example
26881 package Server is
26882    function Func return Integer;
26883 end Server;
26884 @end example
26886 @example
26887 package body Server is
26888    function Func return Integer is
26889    begin
26890       ...
26891    end Func;
26892 end Server;
26893 @end example
26895 @example
26896 with Server;
26897 pragma Elaborate (Server);
26898 package Client is
26899    Val : constant Integer := Server.Func;
26900 end Client;
26901 @end example
26903 In the example above, pragma @code{Elaborate} guarantees the following
26904 elaboration order:
26906 @example
26907 spec of Server
26908 body of Server
26909 spec of Client
26910 @end example
26912 Removing pragma @code{Elaborate} could result in the following incorrect
26913 elaboration order:
26915 @example
26916 spec of Server
26917 spec of Client
26918 body of Server
26919 @end example
26921 where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func}
26922 has not been elaborated yet.
26923 @end itemize
26925 @geindex pragma Elaborate_All (Unit)
26928 @itemize *
26930 @item 
26931 @emph{pragma Elaborate_All (Unit)}
26933 Pragma @code{Elaborate_All} is placed in the context clauses of a unit, after
26934 a @emph{with} clause. It guarantees that both the spec and body of its argument
26935 will be elaborated prior to the unit with the pragma, as well as all units
26936 @emph{with}ed by the spec and body of the argument, recursively. Note that other
26937 unrelated units may be elaborated in between the spec and the body.
26939 @example
26940 package Math is
26941    function Factorial (Val : Natural) return Natural;
26942 end Math;
26943 @end example
26945 @example
26946 package body Math is
26947    function Factorial (Val : Natural) return Natural is
26948    begin
26949       ...;
26950    end Factorial;
26951 end Math;
26952 @end example
26954 @example
26955 package Computer is
26956    type Operation_Kind is (None, Op_Factorial);
26958    function Compute
26959      (Val : Natural;
26960       Op  : Operation_Kind) return Natural;
26961 end Computer;
26962 @end example
26964 @example
26965 with Math;
26966 package body Computer is
26967    function Compute
26968      (Val : Natural;
26969       Op  : Operation_Kind) return Natural
26970    is
26971       if Op = Op_Factorial then
26972          return Math.Factorial (Val);
26973       end if;
26975       return 0;
26976    end Compute;
26977 end Computer;
26978 @end example
26980 @example
26981 with Computer;
26982 pragma Elaborate_All (Computer);
26983 package Client is
26984    Val : constant Natural :=
26985            Computer.Compute (123, Computer.Op_Factorial);
26986 end Client;
26987 @end example
26989 In the example above, pragma @code{Elaborate_All} can result in the following
26990 elaboration order:
26992 @example
26993 spec of Math
26994 body of Math
26995 spec of Computer
26996 body of Computer
26997 spec of Client
26998 @end example
27000 Note that there are several allowable suborders for the specs and bodies of
27001 @code{Math} and @code{Computer}, but the point is that these specs and bodies will
27002 be elaborated prior to @code{Client}.
27004 Removing pragma @code{Elaborate_All} could result in the following incorrect
27005 elaboration order:
27007 @example
27008 spec of Math
27009 spec of Computer
27010 body of Computer
27011 spec of Client
27012 body of Math
27013 @end example
27015 where @code{Client} invokes @code{Computer.Compute}, which in turn invokes
27016 @code{Math.Factorial}, but the body of @code{Math.Factorial} has not been
27017 elaborated yet.
27018 @end itemize
27020 All pragmas shown above can be summarized by the following rule:
27022 @emph{If a client unit elaborates a server target directly or indirectly, then if
27023 the server unit requires a body and does not have pragma Pure, Preelaborate,
27024 or Elaborate_Body, then the client unit should have pragma Elaborate or
27025 Elaborate_All for the server unit.}
27027 If the rule outlined above is not followed, then a program may fall in one of
27028 the following states:
27031 @itemize *
27033 @item 
27034 @emph{No elaboration order exists}
27036 In this case a compiler must diagnose the situation, and refuse to build an
27037 executable program.
27039 @item 
27040 @emph{One or more incorrect elaboration orders exist}
27042 In this case a compiler can build an executable program, but
27043 @code{Program_Error} will be raised when the program is run.
27045 @item 
27046 @emph{Several elaboration orders exist, some correct, some incorrect}
27048 In this case the programmer has not controlled the elaboration order. As a
27049 result, a compiler may or may not pick one of the correct orders, and the
27050 program may or may not raise @code{Program_Error} when it is run. This is the
27051 worst possible state because the program may fail on another compiler, or
27052 even another version of the same compiler.
27054 @item 
27055 @emph{One or more correct orders exist}
27057 In this case a compiler can build an executable program, and the program is
27058 run successfully. This state may be guaranteed by following the outlined
27059 rules, or may be the result of good program architecture.
27060 @end itemize
27062 Note that one additional advantage of using @code{Elaborate} and @code{Elaborate_All}
27063 is that the program continues to stay in the last state (one or more correct
27064 orders exist) even if maintenance changes the bodies of targets.
27066 @node Controlling the Elaboration Order in GNAT,Mixing Elaboration Models,Controlling the Elaboration Order in Ada,Elaboration Order Handling in GNAT
27067 @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}
27068 @section Controlling the Elaboration Order in GNAT
27071 In addition to Ada semantics and rules synthesized from them, GNAT offers
27072 three elaboration models to aid the programmer with specifying the correct
27073 elaboration order and to diagnose elaboration problems.
27075 @geindex Dynamic elaboration model
27078 @itemize *
27080 @item 
27081 @emph{Dynamic elaboration model}
27083 This is the most permissive of the three elaboration models and emulates the
27084 behavior specified by the Ada Reference Manual. When the dynamic model is in
27085 effect, GNAT makes the following assumptions:
27088 @itemize -
27090 @item 
27091 All code within all units in a partition is considered to be elaboration
27092 code.
27094 @item 
27095 Some of the invocations in elaboration code may not take place at run time
27096 due to conditional execution.
27097 @end itemize
27099 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
27100 that invoke internal targets. In addition, GNAT generates run-time checks for
27101 all external targets and for all scenarios that may exhibit ABE problems.
27103 The elaboration order is obtained by honoring all @emph{with} clauses, purity and
27104 preelaborability of units, and elaboration-control pragmas. The dynamic model
27105 attempts to take all invocations in elaboration code into account. If an
27106 invocation leads to a circularity, GNAT ignores the invocation based on the
27107 assumptions stated above. An order obtained using the dynamic model may fail
27108 an ABE check at run time when GNAT ignored an invocation.
27110 The dynamic model is enabled with compiler switch @code{-gnatE}.
27111 @end itemize
27113 @geindex Static elaboration model
27116 @itemize *
27118 @item 
27119 @emph{Static elaboration model}
27121 This is the middle ground of the three models. When the static model is in
27122 effect, GNAT makes the following assumptions:
27125 @itemize -
27127 @item 
27128 Only code at the library level and in package body statements within all
27129 units in a partition is considered to be elaboration code.
27131 @item 
27132 All invocations in elaboration will take place at run time, regardless of
27133 conditional execution.
27134 @end itemize
27136 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
27137 that invoke internal targets. In addition, GNAT generates run-time checks for
27138 all external targets and for all scenarios that may exhibit ABE problems.
27140 The elaboration order is obtained by honoring all @emph{with} clauses, purity and
27141 preelaborability of units, presence of elaboration-control pragmas, and all
27142 invocations in elaboration code. An order obtained using the static model is
27143 guaranteed to be ABE problem-free, excluding dispatching calls and
27144 access-to-subprogram types.
27146 The static model is the default model in GNAT.
27147 @end itemize
27149 @geindex SPARK elaboration model
27152 @itemize *
27154 @item 
27155 @emph{SPARK elaboration model}
27157 This is the most conservative of the three models and enforces the SPARK
27158 rules of elaboration as defined in the SPARK Reference Manual, section 7.7.
27159 The SPARK model is in effect only when a scenario and a target reside in a
27160 region subject to @code{SPARK_Mode On}, otherwise the dynamic or static model
27161 is in effect.
27163 The SPARK model is enabled with compiler switch @code{-gnatd.v}.
27164 @end itemize
27166 @geindex Legacy elaboration models
27169 @itemize *
27171 @item 
27172 @emph{Legacy elaboration models}
27174 In addition to the three elaboration models outlined above, GNAT provides the
27175 following legacy models:
27178 @itemize -
27180 @item 
27181 @cite{Legacy elaboration-checking model} available in pre-18.x versions of GNAT.
27182 This model is enabled with compiler switch @code{-gnatH}.
27184 @item 
27185 @cite{Legacy elaboration-order model} available in pre-20.x versions of GNAT.
27186 This model is enabled with binder switch @code{-H}.
27187 @end itemize
27188 @end itemize
27190 @geindex Relaxed elaboration mode
27192 The dynamic, legacy, and static models can be relaxed using compiler switch
27193 @code{-gnatJ}, making them more permissive. Note that in this mode, GNAT
27194 may not diagnose certain elaboration issues or install run-time checks.
27196 @node Mixing Elaboration Models,ABE Diagnostics,Controlling the Elaboration Order in GNAT,Elaboration Order Handling in GNAT
27197 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{226}@anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{227}
27198 @section Mixing Elaboration Models
27201 It is possible to mix units compiled with a different elaboration model,
27202 however the following rules must be observed:
27205 @itemize *
27207 @item 
27208 A client unit compiled with the dynamic model can only @emph{with} a server unit
27209 that meets at least one of the following criteria:
27212 @itemize -
27214 @item 
27215 The server unit is compiled with the dynamic model.
27217 @item 
27218 The server unit is a GNAT implementation unit from the @code{Ada}, @code{GNAT},
27219 @code{Interfaces}, or @code{System} hierarchies.
27221 @item 
27222 The server unit has pragma @code{Pure} or @code{Preelaborate}.
27224 @item 
27225 The client unit has an explicit @code{Elaborate_All} pragma for the server
27226 unit.
27227 @end itemize
27228 @end itemize
27230 These rules ensure that elaboration checks are not omitted. If the rules are
27231 violated, the binder emits a warning:
27233 @quotation
27235 @example
27236 warning: "x.ads" has dynamic elaboration checks and with's
27237 warning:   "y.ads" which has static elaboration checks
27238 @end example
27239 @end quotation
27241 The warnings can be suppressed by binder switch @code{-ws}.
27243 @node ABE Diagnostics,SPARK Diagnostics,Mixing Elaboration Models,Elaboration Order Handling in GNAT
27244 @anchor{gnat_ugn/elaboration_order_handling_in_gnat abe-diagnostics}@anchor{228}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{229}
27245 @section ABE Diagnostics
27248 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
27249 that invoke internal targets, regardless of whether the dynamic, SPARK, or
27250 static model is in effect.
27252 Note that GNAT emits warnings rather than hard errors whenever it encounters an
27253 elaboration problem. This is because the elaboration model in effect may be too
27254 conservative, or a particular scenario may not be invoked due conditional
27255 execution. The warnings can be suppressed selectively with @code{pragma Warnings
27256 (Off)} or globally with compiler switch @code{-gnatwL}.
27258 A @emph{guaranteed ABE} arises when the body of a target is not elaborated early
27259 enough, and causes @emph{all} scenarios that directly invoke the target to fail.
27261 @quotation
27263 @example
27264 package body Guaranteed_ABE is
27265    function ABE return Integer;
27267    Val : constant Integer := ABE;
27269    function ABE return Integer is
27270    begin
27271      ...
27272    end ABE;
27273 end Guaranteed_ABE;
27274 @end example
27275 @end quotation
27277 In the example above, the elaboration of @code{Guaranteed_ABE}’s body elaborates
27278 the declaration of @code{Val}. This invokes function @code{ABE}, however the body of
27279 @code{ABE} has not been elaborated yet. GNAT emits the following diagnostic:
27281 @quotation
27283 @example
27284 4.    Val : constant Integer := ABE;
27285                                 |
27286    >>> warning: cannot call "ABE" before body seen
27287    >>> warning: Program_Error will be raised at run time
27288 @end example
27289 @end quotation
27291 A @emph{conditional ABE} arises when the body of a target is not elaborated early
27292 enough, and causes @emph{some} scenarios that directly invoke the target to fail.
27294 @quotation
27296 @example
27297  1. package body Conditional_ABE is
27298  2.    procedure Force_Body is null;
27299  3.
27300  4.    generic
27301  5.       with function Func return Integer;
27302  6.    package Gen is
27303  7.       Val : constant Integer := Func;
27304  8.    end Gen;
27305  9.
27306 10.    function ABE return Integer;
27308 12.    function Cause_ABE return Boolean is
27309 13.       package Inst is new Gen (ABE);
27310 14.    begin
27311 15.       ...
27312 16.    end Cause_ABE;
27314 18.    Val : constant Boolean := Cause_ABE;
27316 20.    function ABE return Integer is
27317 21.    begin
27318 22.       ...
27319 23.    end ABE;
27321 25.    Safe : constant Boolean := Cause_ABE;
27322 26. end Conditional_ABE;
27323 @end example
27324 @end quotation
27326 In the example above, the elaboration of package body @code{Conditional_ABE}
27327 elaborates the declaration of @code{Val}. This invokes function @code{Cause_ABE},
27328 which instantiates generic unit @code{Gen} as @code{Inst}. The elaboration of
27329 @code{Inst} invokes function @code{ABE}, however the body of @code{ABE} has not been
27330 elaborated yet. GNAT emits the following diagnostic:
27332 @quotation
27334 @example
27335 13.       package Inst is new Gen (ABE);
27336           |
27337     >>> warning: in instantiation at line 7
27338     >>> warning: cannot call "ABE" before body seen
27339     >>> warning: Program_Error may be raised at run time
27340     >>> warning:   body of unit "Conditional_ABE" elaborated
27341     >>> warning:   function "Cause_ABE" called at line 18
27342     >>> warning:   function "ABE" called at line 7, instance at line 13
27343 @end example
27344 @end quotation
27346 Note that the same ABE problem does not occur with the elaboration of
27347 declaration @code{Safe} because the body of function @code{ABE} has already been
27348 elaborated at that point.
27350 @node SPARK Diagnostics,Elaboration Circularities,ABE Diagnostics,Elaboration Order Handling in GNAT
27351 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{22a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat spark-diagnostics}@anchor{22b}
27352 @section SPARK Diagnostics
27355 GNAT enforces the SPARK rules of elaboration as defined in the SPARK Reference
27356 Manual section 7.7 when compiler switch @code{-gnatd.v} is in effect. Note
27357 that GNAT emits hard errors whenever it encounters a violation of the SPARK
27358 rules.
27360 @quotation
27362 @example
27363 1. with Server;
27364 2. package body SPARK_Diagnostics with SPARK_Mode is
27365 3.    Val : constant Integer := Server.Func;
27366                                       |
27367    >>> call to "Func" during elaboration in SPARK
27368    >>> unit "SPARK_Diagnostics" requires pragma "Elaborate_All" for "Server"
27369    >>>   body of unit "SPARK_Model" elaborated
27370    >>>   function "Func" called at line 3
27372 4. end SPARK_Diagnostics;
27373 @end example
27374 @end quotation
27376 @node Elaboration Circularities,Resolving Elaboration Circularities,SPARK Diagnostics,Elaboration Order Handling in GNAT
27377 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-circularities}@anchor{22c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{22d}
27378 @section Elaboration Circularities
27381 An @strong{elaboration circularity} occurs whenever the elaboration of a set of
27382 units enters a deadlocked state, where each unit is waiting for another unit
27383 to be elaborated. This situation may be the result of improper use of @emph{with}
27384 clauses, elaboration-control pragmas, or invocations in elaboration code.
27386 The following example exhibits an elaboration circularity.
27388 @quotation
27390 @example
27391 with B; pragma Elaborate (B);
27392 package A is
27393 end A;
27394 @end example
27396 @example
27397 package B is
27398    procedure Force_Body;
27399 end B;
27400 @end example
27402 @example
27403 with C;
27404 package body B is
27405    procedure Force_Body is null;
27407    Elab : constant Integer := C.Func;
27408 end B;
27409 @end example
27411 @example
27412 package C is
27413    function Func return Integer;
27414 end C;
27415 @end example
27417 @example
27418 with A;
27419 package body C is
27420    function Func return Integer is
27421    begin
27422       ...
27423    end Func;
27424 end C;
27425 @end example
27426 @end quotation
27428 The binder emits the following diagnostic:
27430 @quotation
27432 @example
27433 error: Elaboration circularity detected
27434 info:
27435 info:    Reason:
27436 info:
27437 info:      unit "a (spec)" depends on its own elaboration
27438 info:
27439 info:    Circularity:
27440 info:
27441 info:      unit "a (spec)" has with clause and pragma Elaborate for unit "b (spec)"
27442 info:      unit "b (body)" is in the closure of pragma Elaborate
27443 info:      unit "b (body)" invokes a construct of unit "c (body)" at elaboration time
27444 info:      unit "c (body)" has with clause for unit "a (spec)"
27445 info:
27446 info:    Suggestions:
27447 info:
27448 info:      remove pragma Elaborate for unit "b (body)" in unit "a (spec)"
27449 info:      use the dynamic elaboration model (compiler switch -gnatE)
27450 @end example
27451 @end quotation
27453 The diagnostic consist of the following sections:
27456 @itemize *
27458 @item 
27459 Reason
27461 This section provides a short explanation describing why the set of units
27462 could not be ordered.
27464 @item 
27465 Circularity
27467 This section enumerates the units comprising the deadlocked set, along with
27468 their interdependencies.
27470 @item 
27471 Suggestions
27473 This section enumerates various tactics for eliminating the circularity.
27474 @end itemize
27476 @node Resolving Elaboration Circularities,Elaboration-related Compiler Switches,Elaboration Circularities,Elaboration Order Handling in GNAT
27477 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{22e}@anchor{gnat_ugn/elaboration_order_handling_in_gnat resolving-elaboration-circularities}@anchor{22f}
27478 @section Resolving Elaboration Circularities
27481 The most desirable option from the point of view of long-term maintenance is to
27482 rearrange the program so that the elaboration problems are avoided. One useful
27483 technique is to place the elaboration code into separate child packages.
27484 Another is to move some of the initialization code to explicitly invoked
27485 subprograms, where the program controls the order of initialization explicitly.
27486 Although this is the most desirable option, it may be impractical and involve
27487 too much modification, especially in the case of complex legacy code.
27489 When faced with an elaboration circularity, the programmer should also consider
27490 the tactics given in the suggestions section of the circularity diagnostic.
27491 Depending on the units involved in the circularity, their @emph{with} clauses,
27492 purity, preelaborability, presence of elaboration-control pragmas and
27493 invocations at elaboration time, the binder may suggest one or more of the
27494 following tactics to eliminate the circularity:
27497 @itemize *
27499 @item 
27500 Pragma Elaborate elimination
27502 @example
27503 remove pragma Elaborate for unit "..." in unit "..."
27504 @end example
27506 This tactic is suggested when the binder has determined that pragma
27507 @code{Elaborate}:
27510 @itemize -
27512 @item 
27513 Prevents a set of units from being elaborated.
27515 @item 
27516 The removal of the pragma will not eliminate the semantic effects of the
27517 pragma. In other words, the argument of the pragma will still be elaborated
27518 prior to the unit containing the pragma.
27520 @item 
27521 The removal of the pragma will enable the successful ordering of the units.
27522 @end itemize
27524 The programmer should remove the pragma as advised, and rebuild the program.
27526 @item 
27527 Pragma Elaborate_All elimination
27529 @example
27530 remove pragma Elaborate_All for unit "..." in unit "..."
27531 @end example
27533 This tactic is suggested when the binder has determined that pragma
27534 @code{Elaborate_All}:
27537 @itemize -
27539 @item 
27540 Prevents a set of units from being elaborated.
27542 @item 
27543 The removal of the pragma will not eliminate the semantic effects of the
27544 pragma. In other words, the argument of the pragma along with its @emph{with}
27545 closure will still be elaborated prior to the unit containing the pragma.
27547 @item 
27548 The removal of the pragma will enable the successful ordering of the units.
27549 @end itemize
27551 The programmer should remove the pragma as advised, and rebuild the program.
27553 @item 
27554 Pragma Elaborate_All downgrade
27556 @example
27557 change pragma Elaborate_All for unit "..." to Elaborate in unit "..."
27558 @end example
27560 This tactic is always suggested with the pragma @code{Elaborate_All} elimination
27561 tactic. It offers a different alternative of guaranteeing that the argument
27562 of the pragma will still be elaborated prior to the unit containing the
27563 pragma.
27565 The programmer should update the pragma as advised, and rebuild the program.
27567 @item 
27568 Pragma Elaborate_Body elimination
27570 @example
27571 remove pragma Elaborate_Body in unit "..."
27572 @end example
27574 This tactic is suggested when the binder has determined that pragma
27575 @code{Elaborate_Body}:
27578 @itemize -
27580 @item 
27581 Prevents a set of units from being elaborated.
27583 @item 
27584 The removal of the pragma will enable the successful ordering of the units.
27585 @end itemize
27587 Note that the binder cannot determine whether the pragma is required for
27588 other purposes, such as guaranteeing the initialization of a variable
27589 declared in the spec by elaboration code in the body.
27591 The programmer should remove the pragma as advised, and rebuild the program.
27593 @item 
27594 Use of pragma Restrictions
27596 @example
27597 use pragma Restrictions (No_Entry_Calls_In_Elaboration_Code)
27598 @end example
27600 This tactic is suggested when the binder has determined that a task
27601 activation at elaboration time:
27604 @itemize -
27606 @item 
27607 Prevents a set of units from being elaborated.
27608 @end itemize
27610 Note that the binder cannot determine with certainty whether the task will
27611 block at elaboration time.
27613 The programmer should create a configuration file, place the pragma within,
27614 update the general compilation arguments, and rebuild the program.
27616 @item 
27617 Use of dynamic elaboration model
27619 @example
27620 use the dynamic elaboration model (compiler switch -gnatE)
27621 @end example
27623 This tactic is suggested when the binder has determined that an invocation at
27624 elaboration time:
27627 @itemize -
27629 @item 
27630 Prevents a set of units from being elaborated.
27632 @item 
27633 The use of the dynamic model will enable the successful ordering of the
27634 units.
27635 @end itemize
27637 The programmer has two options:
27640 @itemize -
27642 @item 
27643 Determine the units involved in the invocation using the detailed
27644 invocation information, and add compiler switch @code{-gnatE} to the
27645 compilation arguments of selected files only. This approach will yield
27646 safer elaboration orders compared to the other option because it will
27647 minimize the opportunities presented to the dynamic model for ignoring
27648 invocations.
27650 @item 
27651 Add compiler switch @code{-gnatE} to the general compilation arguments.
27652 @end itemize
27654 @item 
27655 Use of detailed invocation information
27657 @example
27658 use detailed invocation information (compiler switch -gnatd_F)
27659 @end example
27661 This tactic is always suggested with the use of the dynamic model tactic. It
27662 causes the circularity section of the circularity diagnostic to describe the
27663 flow of elaboration code from a unit to a unit, enumerating all such paths in
27664 the process.
27666 The programmer should analyze this information to determine which units
27667 should be compiled with the dynamic model.
27669 @item 
27670 Forced-dependency elimination
27672 @example
27673 remove the dependency of unit "..." on unit "..." from the argument of switch -f
27674 @end example
27676 This tactic is suggested when the binder has determined that a dependency
27677 present in the forced-elaboration-order file indicated by binder switch
27678 @code{-f}:
27681 @itemize -
27683 @item 
27684 Prevents a set of units from being elaborated.
27686 @item 
27687 The removal of the dependency will enable the successful ordering of the
27688 units.
27689 @end itemize
27691 The programmer should edit the forced-elaboration-order file, remove the
27692 dependency, and rebind the program.
27694 @item 
27695 All forced-dependency elimination
27697 @example
27698 remove switch -f
27699 @end example
27701 This tactic is suggested in case editing the forced-elaboration-order file is
27702 not an option.
27704 The programmer should remove binder switch @code{-f} from the binder
27705 arguments, and rebind.
27707 @item 
27708 Multiple-circularities diagnostic
27710 @example
27711 diagnose all circularities (binder switch -d_C)
27712 @end example
27714 By default, the binder will diagnose only the highest-precedence circularity.
27715 If the program contains multiple circularities, the binder will suggest the
27716 use of binder switch @code{-d_C} in order to obtain the diagnostics of all
27717 circularities.
27719 The programmer should add binder switch @code{-d_C} to the binder
27720 arguments, and rebind.
27721 @end itemize
27723 If none of the tactics suggested by the binder eliminate the elaboration
27724 circularity, the programmer should consider using one of the legacy elaboration
27725 models, in the following order:
27728 @itemize *
27730 @item 
27731 Use the pre-20.x legacy elaboration-order model, with binder switch
27732 @code{-H}.
27734 @item 
27735 Use both pre-18.x and pre-20.x legacy elaboration models, with compiler
27736 switch @code{-gnatH} and binder switch @code{-H}.
27738 @item 
27739 Use the relaxed static-elaboration model, with compiler switches
27740 @code{-gnatH} @code{-gnatJ} and binder switch @code{-H}.
27742 @item 
27743 Use the relaxed dynamic-elaboration model, with compiler switches
27744 @code{-gnatH} @code{-gnatJ} @code{-gnatE} and binder switch
27745 @code{-H}.
27746 @end itemize
27748 @node Elaboration-related Compiler Switches,Summary of Procedures for Elaboration Control,Resolving Elaboration Circularities,Elaboration Order Handling in GNAT
27749 @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}
27750 @section Elaboration-related Compiler Switches
27753 GNAT has several switches that affect the elaboration model and consequently
27754 the elaboration order chosen by the binder.
27756 @geindex -gnatE (gnat)
27759 @table @asis
27761 @item @code{-gnatE}
27763 Dynamic elaboration checking mode enabled
27765 When this switch is in effect, GNAT activates the dynamic model.
27766 @end table
27768 @geindex -gnatel (gnat)
27771 @table @asis
27773 @item @code{-gnatel}
27775 Turn on info messages on generated Elaborate[_All] pragmas
27777 This switch is only applicable to the pre-20.x legacy elaboration models.
27778 The post-20.x elaboration model no longer relies on implicitly generated
27779 @code{Elaborate} and @code{Elaborate_All} pragmas to order units.
27781 When this switch is in effect, GNAT will emit the following supplementary
27782 information depending on the elaboration model in effect.
27785 @itemize -
27787 @item 
27788 @emph{Dynamic model}
27790 GNAT will indicate missing @code{Elaborate} and @code{Elaborate_All} pragmas for
27791 all library-level scenarios within the partition.
27793 @item 
27794 @emph{Static model}
27796 GNAT will indicate all scenarios invoked during elaboration. In addition,
27797 it will provide detailed traceback when an implicit @code{Elaborate} or
27798 @code{Elaborate_All} pragma is generated.
27800 @item 
27801 @emph{SPARK model}
27803 GNAT will indicate how an elaboration requirement is met by the context of
27804 a unit. This diagnostic requires compiler switch @code{-gnatd.v}.
27806 @example
27807 1. with Server; pragma Elaborate_All (Server);
27808 2. package Client with SPARK_Mode is
27809 3.    Val : constant Integer := Server.Func;
27810                                       |
27811    >>> info: call to "Func" during elaboration in SPARK
27812    >>> info: "Elaborate_All" requirement for unit "Server" met by pragma at line 1
27814 4. end Client;
27815 @end example
27816 @end itemize
27817 @end table
27819 @geindex -gnatH (gnat)
27822 @table @asis
27824 @item @code{-gnatH}
27826 Legacy elaboration checking mode enabled
27828 When this switch is in effect, GNAT will utilize the pre-18.x elaboration
27829 model.
27830 @end table
27832 @geindex -gnatJ (gnat)
27835 @table @asis
27837 @item @code{-gnatJ}
27839 Relaxed elaboration checking mode enabled
27841 When this switch is in effect, GNAT will not process certain scenarios,
27842 resulting in a more permissive elaboration model. Note that this may
27843 eliminate some diagnostics and run-time checks.
27844 @end table
27846 @geindex -gnatw.f (gnat)
27849 @table @asis
27851 @item @code{-gnatw.f}
27853 Turn on warnings for suspicious Subp’Access
27855 When this switch is in effect, GNAT will treat @code{'Access} of an entry,
27856 operator, or subprogram as a potential call to the target and issue warnings:
27858 @example
27859  1. package body Attribute_Call is
27860  2.    function Func return Integer;
27861  3.    type Func_Ptr is access function return Integer;
27862  4.
27863  5.    Ptr : constant Func_Ptr := Func'Access;
27864                                       |
27865     >>> warning: "Access" attribute of "Func" before body seen
27866     >>> warning: possible Program_Error on later references
27867     >>> warning:   body of unit "Attribute_Call" elaborated
27868     >>> warning:   "Access" of "Func" taken at line 5
27870  6.
27871  7.    function Func return Integer is
27872  8.    begin
27873  9.       ...
27874 10.    end Func;
27875 11. end Attribute_Call;
27876 @end example
27878 In the example above, the elaboration of declaration @code{Ptr} is assigned
27879 @code{Func'Access} before the body of @code{Func} has been elaborated.
27880 @end table
27882 @geindex -gnatwl (gnat)
27885 @table @asis
27887 @item @code{-gnatwl}
27889 Turn on warnings for elaboration problems
27891 When this switch is in effect, GNAT emits diagnostics in the form of warnings
27892 concerning various elaboration problems. The warnings are enabled by default.
27893 The switch is provided in case all warnings are suppressed, but elaboration
27894 warnings are still desired.
27896 @item @code{-gnatwL}
27898 Turn off warnings for elaboration problems
27900 When this switch is in effect, GNAT no longer emits any diagnostics in the
27901 form of warnings. Selective suppression of elaboration problems is possible
27902 using @code{pragma Warnings (Off)}.
27904 @example
27905  1. package body Selective_Suppression is
27906  2.    function ABE return Integer;
27907  3.
27908  4.    Val_1 : constant Integer := ABE;
27909                                    |
27910     >>> warning: cannot call "ABE" before body seen
27911     >>> warning: Program_Error will be raised at run time
27913  5.
27914  6.    pragma Warnings (Off);
27915  7.    Val_2 : constant Integer := ABE;
27916  8.    pragma Warnings (On);
27917  9.
27918 10.    function ABE return Integer is
27919 11.    begin
27920 12.       ...
27921 13.    end ABE;
27922 14. end Selective_Suppression;
27923 @end example
27925 Note that suppressing elaboration warnings does not eliminate run-time
27926 checks. The example above will still fail at run time with an ABE.
27927 @end table
27929 @node Summary of Procedures for Elaboration Control,Inspecting the Chosen Elaboration Order,Elaboration-related Compiler Switches,Elaboration Order Handling in GNAT
27930 @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}
27931 @section Summary of Procedures for Elaboration Control
27934 A programmer should first compile the program with the default options, using
27935 none of the binder or compiler switches. If the binder succeeds in finding an
27936 elaboration order, then apart from possible cases involving dispatching calls
27937 and access-to-subprogram types, the program is free of elaboration errors.
27939 If it is important for the program to be portable to compilers other than GNAT,
27940 then the programmer should use compiler switch @code{-gnatel} and consider
27941 the messages about missing or implicitly created @code{Elaborate} and
27942 @code{Elaborate_All} pragmas.
27944 If the binder reports an elaboration circularity, the programmer has several
27945 options:
27948 @itemize *
27950 @item 
27951 Ensure that elaboration warnings are enabled. This will allow the static
27952 model to output trace information of elaboration issues. The trace
27953 information could shed light on previously unforeseen dependencies, as well
27954 as their origins. Elaboration warnings are enabled with compiler switch
27955 @code{-gnatwl}.
27957 @item 
27958 Cosider the tactics given in the suggestions section of the circularity
27959 diagnostic.
27961 @item 
27962 If none of the steps outlined above resolve the circularity, use a more
27963 permissive elaboration model, in the following order:
27966 @itemize -
27968 @item 
27969 Use the pre-20.x legacy elaboration-order model, with binder switch
27970 @code{-H}.
27972 @item 
27973 Use both pre-18.x and pre-20.x legacy elaboration models, with compiler
27974 switch @code{-gnatH} and binder switch @code{-H}.
27976 @item 
27977 Use the relaxed static elaboration model, with compiler switches
27978 @code{-gnatH} @code{-gnatJ} and binder switch @code{-H}.
27980 @item 
27981 Use the relaxed dynamic elaboration model, with compiler switches
27982 @code{-gnatH} @code{-gnatJ} @code{-gnatE} and binder switch
27983 @code{-H}.
27984 @end itemize
27985 @end itemize
27987 @node Inspecting the Chosen Elaboration Order,,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
27988 @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}
27989 @section Inspecting the Chosen Elaboration Order
27992 To see the elaboration order chosen by the binder, inspect the contents of file
27993 @cite{b~xxx.adb}. On certain targets, this file appears as @cite{b_xxx.adb}. The
27994 elaboration order appears as a sequence of calls to @code{Elab_Body} and
27995 @code{Elab_Spec}, interspersed with assignments to @cite{Exxx} which indicates that a
27996 particular unit is elaborated. For example:
27998 @quotation
28000 @example
28001 System.Soft_Links'Elab_Body;
28002 E14 := True;
28003 System.Secondary_Stack'Elab_Body;
28004 E18 := True;
28005 System.Exception_Table'Elab_Body;
28006 E24 := True;
28007 Ada.Io_Exceptions'Elab_Spec;
28008 E67 := True;
28009 Ada.Tags'Elab_Spec;
28010 Ada.Streams'Elab_Spec;
28011 E43 := True;
28012 Interfaces.C'Elab_Spec;
28013 E69 := True;
28014 System.Finalization_Root'Elab_Spec;
28015 E60 := True;
28016 System.Os_Lib'Elab_Body;
28017 E71 := True;
28018 System.Finalization_Implementation'Elab_Spec;
28019 System.Finalization_Implementation'Elab_Body;
28020 E62 := True;
28021 Ada.Finalization'Elab_Spec;
28022 E58 := True;
28023 Ada.Finalization.List_Controller'Elab_Spec;
28024 E76 := True;
28025 System.File_Control_Block'Elab_Spec;
28026 E74 := True;
28027 System.File_Io'Elab_Body;
28028 E56 := True;
28029 Ada.Tags'Elab_Body;
28030 E45 := True;
28031 Ada.Text_Io'Elab_Spec;
28032 Ada.Text_Io'Elab_Body;
28033 E07 := True;
28034 @end example
28035 @end quotation
28037 Note also binder switch @code{-l}, which outputs the chosen elaboration
28038 order and provides a more readable form of the above:
28040 @quotation
28042 @example
28043 ada (spec)
28044 interfaces (spec)
28045 system (spec)
28046 system.case_util (spec)
28047 system.case_util (body)
28048 system.concat_2 (spec)
28049 system.concat_2 (body)
28050 system.concat_3 (spec)
28051 system.concat_3 (body)
28052 system.htable (spec)
28053 system.parameters (spec)
28054 system.parameters (body)
28055 system.crtl (spec)
28056 interfaces.c_streams (spec)
28057 interfaces.c_streams (body)
28058 system.restrictions (spec)
28059 system.restrictions (body)
28060 system.standard_library (spec)
28061 system.exceptions (spec)
28062 system.exceptions (body)
28063 system.storage_elements (spec)
28064 system.storage_elements (body)
28065 system.secondary_stack (spec)
28066 system.stack_checking (spec)
28067 system.stack_checking (body)
28068 system.string_hash (spec)
28069 system.string_hash (body)
28070 system.htable (body)
28071 system.strings (spec)
28072 system.strings (body)
28073 system.traceback (spec)
28074 system.traceback (body)
28075 system.traceback_entries (spec)
28076 system.traceback_entries (body)
28077 ada.exceptions (spec)
28078 ada.exceptions.last_chance_handler (spec)
28079 system.soft_links (spec)
28080 system.soft_links (body)
28081 ada.exceptions.last_chance_handler (body)
28082 system.secondary_stack (body)
28083 system.exception_table (spec)
28084 system.exception_table (body)
28085 ada.io_exceptions (spec)
28086 ada.tags (spec)
28087 ada.streams (spec)
28088 interfaces.c (spec)
28089 interfaces.c (body)
28090 system.finalization_root (spec)
28091 system.finalization_root (body)
28092 system.memory (spec)
28093 system.memory (body)
28094 system.standard_library (body)
28095 system.os_lib (spec)
28096 system.os_lib (body)
28097 system.unsigned_types (spec)
28098 system.stream_attributes (spec)
28099 system.stream_attributes (body)
28100 system.finalization_implementation (spec)
28101 system.finalization_implementation (body)
28102 ada.finalization (spec)
28103 ada.finalization (body)
28104 ada.finalization.list_controller (spec)
28105 ada.finalization.list_controller (body)
28106 system.file_control_block (spec)
28107 system.file_io (spec)
28108 system.file_io (body)
28109 system.val_uns (spec)
28110 system.val_util (spec)
28111 system.val_util (body)
28112 system.val_uns (body)
28113 system.wch_con (spec)
28114 system.wch_con (body)
28115 system.wch_cnv (spec)
28116 system.wch_jis (spec)
28117 system.wch_jis (body)
28118 system.wch_cnv (body)
28119 system.wch_stw (spec)
28120 system.wch_stw (body)
28121 ada.tags (body)
28122 ada.exceptions (body)
28123 ada.text_io (spec)
28124 ada.text_io (body)
28125 text_io (spec)
28126 gdbstr (body)
28127 @end example
28128 @end quotation
28130 @node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
28131 @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}
28132 @chapter Inline Assembler
28135 @geindex Inline Assembler
28137 If you need to write low-level software that interacts directly
28138 with the hardware, Ada provides two ways to incorporate assembly
28139 language code into your program.  First, you can import and invoke
28140 external routines written in assembly language, an Ada feature fully
28141 supported by GNAT.  However, for small sections of code it may be simpler
28142 or more efficient to include assembly language statements directly
28143 in your Ada source program, using the facilities of the implementation-defined
28144 package @code{System.Machine_Code}, which incorporates the gcc
28145 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
28146 including the following:
28149 @itemize *
28151 @item 
28152 No need to use non-Ada tools
28154 @item 
28155 Consistent interface over different targets
28157 @item 
28158 Automatic usage of the proper calling conventions
28160 @item 
28161 Access to Ada constants and variables
28163 @item 
28164 Definition of intrinsic routines
28166 @item 
28167 Possibility of inlining a subprogram comprising assembler code
28169 @item 
28170 Code optimizer can take Inline Assembler code into account
28171 @end itemize
28173 This appendix presents a series of examples to show you how to use
28174 the Inline Assembler.  Although it focuses on the Intel x86,
28175 the general approach applies also to other processors.
28176 It is assumed that you are familiar with Ada
28177 and with assembly language programming.
28179 @menu
28180 * Basic Assembler Syntax:: 
28181 * A Simple Example of Inline Assembler:: 
28182 * Output Variables in Inline Assembler:: 
28183 * Input Variables in Inline Assembler:: 
28184 * Inlining Inline Assembler Code:: 
28185 * Other Asm Functionality:: 
28187 @end menu
28189 @node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
28190 @anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{238}@anchor{gnat_ugn/inline_assembler id2}@anchor{239}
28191 @section Basic Assembler Syntax
28194 The assembler used by GNAT and gcc is based not on the Intel assembly
28195 language, but rather on a language that descends from the AT&T Unix
28196 assembler @code{as} (and which is often referred to as ‘AT&T syntax’).
28197 The following table summarizes the main features of @code{as} syntax
28198 and points out the differences from the Intel conventions.
28199 See the gcc @code{as} and @code{gas} (an @code{as} macro
28200 pre-processor) documentation for further information.
28203 @display
28204 @emph{Register names}@w{ }
28205 @display
28206 gcc / @code{as}: Prefix with ‘%’; for example @code{%eax}@w{ }
28207 Intel: No extra punctuation; for example @code{eax}@w{ }
28208 @end display
28209 @end display
28214 @display
28215 @emph{Immediate operand}@w{ }
28216 @display
28217 gcc / @code{as}: Prefix with ‘$’; for example @code{$4}@w{ }
28218 Intel: No extra punctuation; for example @code{4}@w{ }
28219 @end display
28220 @end display
28225 @display
28226 @emph{Address}@w{ }
28227 @display
28228 gcc / @code{as}: Prefix with ‘$’; for example @code{$loc}@w{ }
28229 Intel: No extra punctuation; for example @code{loc}@w{ }
28230 @end display
28231 @end display
28236 @display
28237 @emph{Memory contents}@w{ }
28238 @display
28239 gcc / @code{as}: No extra punctuation; for example @code{loc}@w{ }
28240 Intel: Square brackets; for example @code{[loc]}@w{ }
28241 @end display
28242 @end display
28247 @display
28248 @emph{Register contents}@w{ }
28249 @display
28250 gcc / @code{as}: Parentheses; for example @code{(%eax)}@w{ }
28251 Intel: Square brackets; for example @code{[eax]}@w{ }
28252 @end display
28253 @end display
28258 @display
28259 @emph{Hexadecimal numbers}@w{ }
28260 @display
28261 gcc / @code{as}: Leading ‘0x’ (C language syntax); for example @code{0xA0}@w{ }
28262 Intel: Trailing ‘h’; for example @code{A0h}@w{ }
28263 @end display
28264 @end display
28269 @display
28270 @emph{Operand size}@w{ }
28271 @display
28272 gcc / @code{as}: Explicit in op code; for example @code{movw} to move a 16-bit word@w{ }
28273 Intel: Implicit, deduced by assembler; for example @code{mov}@w{ }
28274 @end display
28275 @end display
28280 @display
28281 @emph{Instruction repetition}@w{ }
28282 @display
28283 gcc / @code{as}: Split into two lines; for example@w{ }
28284 @display
28285 @code{rep}@w{ }
28286 @code{stosl}@w{ }
28287 @end display
28288 Intel: Keep on one line; for example @code{rep stosl}@w{ }
28289 @end display
28290 @end display
28295 @display
28296 @emph{Order of operands}@w{ }
28297 @display
28298 gcc / @code{as}: Source first; for example @code{movw $4, %eax}@w{ }
28299 Intel: Destination first; for example @code{mov eax, 4}@w{ }
28300 @end display
28301 @end display
28305 @node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
28306 @anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{23a}@anchor{gnat_ugn/inline_assembler id3}@anchor{23b}
28307 @section A Simple Example of Inline Assembler
28310 The following example will generate a single assembly language statement,
28311 @code{nop}, which does nothing.  Despite its lack of run-time effect,
28312 the example will be useful in illustrating the basics of
28313 the Inline Assembler facility.
28315 @quotation
28317 @example
28318 with System.Machine_Code; use System.Machine_Code;
28319 procedure Nothing is
28320 begin
28321    Asm ("nop");
28322 end Nothing;
28323 @end example
28324 @end quotation
28326 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
28327 here it takes one parameter, a @emph{template string} that must be a static
28328 expression and that will form the generated instruction.
28329 @code{Asm} may be regarded as a compile-time procedure that parses
28330 the template string and additional parameters (none here),
28331 from which it generates a sequence of assembly language instructions.
28333 The examples in this chapter will illustrate several of the forms
28334 for invoking @code{Asm}; a complete specification of the syntax
28335 is found in the @code{Machine_Code_Insertions} section of the
28336 @cite{GNAT Reference Manual}.
28338 Under the standard GNAT conventions, the @code{Nothing} procedure
28339 should be in a file named @code{nothing.adb}.
28340 You can build the executable in the usual way:
28342 @quotation
28344 @example
28345 $ gnatmake nothing
28346 @end example
28347 @end quotation
28349 However, the interesting aspect of this example is not its run-time behavior
28350 but rather the generated assembly code.
28351 To see this output, invoke the compiler as follows:
28353 @quotation
28355 @example
28356 $ gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
28357 @end example
28358 @end quotation
28360 where the options are:
28363 @itemize *
28365 @item 
28367 @table @asis
28369 @item @code{-c}
28371 compile only (no bind or link)
28372 @end table
28374 @item 
28376 @table @asis
28378 @item @code{-S}
28380 generate assembler listing
28381 @end table
28383 @item 
28385 @table @asis
28387 @item @code{-fomit-frame-pointer}
28389 do not set up separate stack frames
28390 @end table
28392 @item 
28394 @table @asis
28396 @item @code{-gnatp}
28398 do not add runtime checks
28399 @end table
28400 @end itemize
28402 This gives a human-readable assembler version of the code. The resulting
28403 file will have the same name as the Ada source file, but with a @code{.s}
28404 extension. In our example, the file @code{nothing.s} has the following
28405 contents:
28407 @quotation
28409 @example
28410 .file "nothing.adb"
28411 gcc2_compiled.:
28412 ___gnu_compiled_ada:
28413 .text
28414    .align 4
28415 .globl __ada_nothing
28416 __ada_nothing:
28417 #APP
28418    nop
28419 #NO_APP
28420    jmp L1
28421    .align 2,0x90
28423    ret
28424 @end example
28425 @end quotation
28427 The assembly code you included is clearly indicated by
28428 the compiler, between the @code{#APP} and @code{#NO_APP}
28429 delimiters. The character before the ‘APP’ and ‘NOAPP’
28430 can differ on different targets. For example, GNU/Linux uses ‘#APP’ while
28431 on NT you will see ‘/APP’.
28433 If you make a mistake in your assembler code (such as using the
28434 wrong size modifier, or using a wrong operand for the instruction) GNAT
28435 will report this error in a temporary file, which will be deleted when
28436 the compilation is finished.  Generating an assembler file will help
28437 in such cases, since you can assemble this file separately using the
28438 @code{as} assembler that comes with gcc.
28440 Assembling the file using the command
28442 @quotation
28444 @example
28445 $ as nothing.s
28446 @end example
28447 @end quotation
28449 will give you error messages whose lines correspond to the assembler
28450 input file, so you can easily find and correct any mistakes you made.
28451 If there are no errors, @code{as} will generate an object file
28452 @code{nothing.out}.
28454 @node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
28455 @anchor{gnat_ugn/inline_assembler id4}@anchor{23c}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{23d}
28456 @section Output Variables in Inline Assembler
28459 The examples in this section, showing how to access the processor flags,
28460 illustrate how to specify the destination operands for assembly language
28461 statements.
28463 @quotation
28465 @example
28466 with Interfaces; use Interfaces;
28467 with Ada.Text_IO; use Ada.Text_IO;
28468 with System.Machine_Code; use System.Machine_Code;
28469 procedure Get_Flags is
28470    Flags : Unsigned_32;
28471    use ASCII;
28472 begin
28473    Asm ("pushfl"          & LF & HT & -- push flags on stack
28474         "popl %%eax"      & LF & HT & -- load eax with flags
28475         "movl %%eax, %0",             -- store flags in variable
28476         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28477    Put_Line ("Flags register:" & Flags'Img);
28478 end Get_Flags;
28479 @end example
28480 @end quotation
28482 In order to have a nicely aligned assembly listing, we have separated
28483 multiple assembler statements in the Asm template string with linefeed
28484 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
28485 The resulting section of the assembly output file is:
28487 @quotation
28489 @example
28490 #APP
28491    pushfl
28492    popl %eax
28493    movl %eax, -40(%ebp)
28494 #NO_APP
28495 @end example
28496 @end quotation
28498 It would have been legal to write the Asm invocation as:
28500 @quotation
28502 @example
28503 Asm ("pushfl popl %%eax movl %%eax, %0")
28504 @end example
28505 @end quotation
28507 but in the generated assembler file, this would come out as:
28509 @quotation
28511 @example
28512 #APP
28513    pushfl popl %eax movl %eax, -40(%ebp)
28514 #NO_APP
28515 @end example
28516 @end quotation
28518 which is not so convenient for the human reader.
28520 We use Ada comments
28521 at the end of each line to explain what the assembler instructions
28522 actually do.  This is a useful convention.
28524 When writing Inline Assembler instructions, you need to precede each register
28525 and variable name with a percent sign.  Since the assembler already requires
28526 a percent sign at the beginning of a register name, you need two consecutive
28527 percent signs for such names in the Asm template string, thus @code{%%eax}.
28528 In the generated assembly code, one of the percent signs will be stripped off.
28530 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
28531 variables: operands you later define using @code{Input} or @code{Output}
28532 parameters to @code{Asm}.
28533 An output variable is illustrated in
28534 the third statement in the Asm template string:
28536 @quotation
28538 @example
28539 movl %%eax, %0
28540 @end example
28541 @end quotation
28543 The intent is to store the contents of the eax register in a variable that can
28544 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
28545 necessarily work, since the compiler might optimize by using a register
28546 to hold Flags, and the expansion of the @code{movl} instruction would not be
28547 aware of this optimization.  The solution is not to store the result directly
28548 but rather to advise the compiler to choose the correct operand form;
28549 that is the purpose of the @code{%0} output variable.
28551 Information about the output variable is supplied in the @code{Outputs}
28552 parameter to @code{Asm}:
28554 @quotation
28556 @example
28557 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28558 @end example
28559 @end quotation
28561 The output is defined by the @code{Asm_Output} attribute of the target type;
28562 the general format is
28564 @quotation
28566 @example
28567 Type'Asm_Output (constraint_string, variable_name)
28568 @end example
28569 @end quotation
28571 The constraint string directs the compiler how
28572 to store/access the associated variable.  In the example
28574 @quotation
28576 @example
28577 Unsigned_32'Asm_Output ("=m", Flags);
28578 @end example
28579 @end quotation
28581 the @code{"m"} (memory) constraint tells the compiler that the variable
28582 @code{Flags} should be stored in a memory variable, thus preventing
28583 the optimizer from keeping it in a register.  In contrast,
28585 @quotation
28587 @example
28588 Unsigned_32'Asm_Output ("=r", Flags);
28589 @end example
28590 @end quotation
28592 uses the @code{"r"} (register) constraint, telling the compiler to
28593 store the variable in a register.
28595 If the constraint is preceded by the equal character ‘=’, it tells
28596 the compiler that the variable will be used to store data into it.
28598 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
28599 allowing the optimizer to choose whatever it deems best.
28601 There are a fairly large number of constraints, but the ones that are
28602 most useful (for the Intel x86 processor) are the following:
28604 @quotation
28607 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
28608 @item
28610 @emph{=}
28612 @tab
28614 output constraint
28616 @item
28618 @emph{g}
28620 @tab
28622 global (i.e., can be stored anywhere)
28624 @item
28626 @emph{m}
28628 @tab
28630 in memory
28632 @item
28634 @emph{I}
28636 @tab
28638 a constant
28640 @item
28642 @emph{a}
28644 @tab
28646 use eax
28648 @item
28650 @emph{b}
28652 @tab
28654 use ebx
28656 @item
28658 @emph{c}
28660 @tab
28662 use ecx
28664 @item
28666 @emph{d}
28668 @tab
28670 use edx
28672 @item
28674 @emph{S}
28676 @tab
28678 use esi
28680 @item
28682 @emph{D}
28684 @tab
28686 use edi
28688 @item
28690 @emph{r}
28692 @tab
28694 use one of eax, ebx, ecx or edx
28696 @item
28698 @emph{q}
28700 @tab
28702 use one of eax, ebx, ecx, edx, esi or edi
28704 @end multitable
28706 @end quotation
28708 The full set of constraints is described in the gcc and @code{as}
28709 documentation; note that it is possible to combine certain constraints
28710 in one constraint string.
28712 You specify the association of an output variable with an assembler operand
28713 through the @code{%@emph{n}} notation, where @emph{n} is a non-negative
28714 integer.  Thus in
28716 @quotation
28718 @example
28719 Asm ("pushfl"          & LF & HT & -- push flags on stack
28720      "popl %%eax"      & LF & HT & -- load eax with flags
28721      "movl %%eax, %0",             -- store flags in variable
28722      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28723 @end example
28724 @end quotation
28726 @code{%0} will be replaced in the expanded code by the appropriate operand,
28727 whatever
28728 the compiler decided for the @code{Flags} variable.
28730 In general, you may have any number of output variables:
28733 @itemize *
28735 @item 
28736 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
28738 @item 
28739 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
28740 of @code{Asm_Output} attributes
28741 @end itemize
28743 For example:
28745 @quotation
28747 @example
28748 Asm ("movl %%eax, %0" & LF & HT &
28749      "movl %%ebx, %1" & LF & HT &
28750      "movl %%ecx, %2",
28751      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
28752                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
28753                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
28754 @end example
28755 @end quotation
28757 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28758 in the Ada program.
28760 As a variation on the @code{Get_Flags} example, we can use the constraints
28761 string to direct the compiler to store the eax register into the @code{Flags}
28762 variable, instead of including the store instruction explicitly in the
28763 @code{Asm} template string:
28765 @quotation
28767 @example
28768 with Interfaces; use Interfaces;
28769 with Ada.Text_IO; use Ada.Text_IO;
28770 with System.Machine_Code; use System.Machine_Code;
28771 procedure Get_Flags_2 is
28772    Flags : Unsigned_32;
28773    use ASCII;
28774 begin
28775    Asm ("pushfl"      & LF & HT & -- push flags on stack
28776         "popl %%eax",             -- save flags in eax
28777         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28778    Put_Line ("Flags register:" & Flags'Img);
28779 end Get_Flags_2;
28780 @end example
28781 @end quotation
28783 The @code{"a"} constraint tells the compiler that the @code{Flags}
28784 variable will come from the eax register. Here is the resulting code:
28786 @quotation
28788 @example
28789 #APP
28790    pushfl
28791    popl %eax
28792 #NO_APP
28793    movl %eax,-40(%ebp)
28794 @end example
28795 @end quotation
28797 The compiler generated the store of eax into Flags after
28798 expanding the assembler code.
28800 Actually, there was no need to pop the flags into the eax register;
28801 more simply, we could just pop the flags directly into the program variable:
28803 @quotation
28805 @example
28806 with Interfaces; use Interfaces;
28807 with Ada.Text_IO; use Ada.Text_IO;
28808 with System.Machine_Code; use System.Machine_Code;
28809 procedure Get_Flags_3 is
28810    Flags : Unsigned_32;
28811    use ASCII;
28812 begin
28813    Asm ("pushfl"  & LF & HT & -- push flags on stack
28814         "pop %0",             -- save flags in Flags
28815         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28816    Put_Line ("Flags register:" & Flags'Img);
28817 end Get_Flags_3;
28818 @end example
28819 @end quotation
28821 @node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
28822 @anchor{gnat_ugn/inline_assembler id5}@anchor{23e}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{23f}
28823 @section Input Variables in Inline Assembler
28826 The example in this section illustrates how to specify the source operands
28827 for assembly language statements.
28828 The program simply increments its input value by 1:
28830 @quotation
28832 @example
28833 with Interfaces; use Interfaces;
28834 with Ada.Text_IO; use Ada.Text_IO;
28835 with System.Machine_Code; use System.Machine_Code;
28836 procedure Increment is
28838    function Incr (Value : Unsigned_32) return Unsigned_32 is
28839       Result : Unsigned_32;
28840    begin
28841       Asm ("incl %0",
28842            Outputs => Unsigned_32'Asm_Output ("=a", Result),
28843            Inputs  => Unsigned_32'Asm_Input ("a", Value));
28844       return Result;
28845    end Incr;
28847    Value : Unsigned_32;
28849 begin
28850    Value := 5;
28851    Put_Line ("Value before is" & Value'Img);
28852    Value := Incr (Value);
28853   Put_Line ("Value after is" & Value'Img);
28854 end Increment;
28855 @end example
28856 @end quotation
28858 The @code{Outputs} parameter to @code{Asm} specifies
28859 that the result will be in the eax register and that it is to be stored
28860 in the @code{Result} variable.
28862 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28863 but with an @code{Asm_Input} attribute.
28864 The @code{"="} constraint, indicating an output value, is not present.
28866 You can have multiple input variables, in the same way that you can have more
28867 than one output variable.
28869 The parameter count (%0, %1) etc, still starts at the first output statement,
28870 and continues with the input statements.
28872 Just as the @code{Outputs} parameter causes the register to be stored into the
28873 target variable after execution of the assembler statements, so does the
28874 @code{Inputs} parameter cause its variable to be loaded into the register
28875 before execution of the assembler statements.
28877 Thus the effect of the @code{Asm} invocation is:
28880 @itemize *
28882 @item 
28883 load the 32-bit value of @code{Value} into eax
28885 @item 
28886 execute the @code{incl %eax} instruction
28888 @item 
28889 store the contents of eax into the @code{Result} variable
28890 @end itemize
28892 The resulting assembler file (with @code{-O2} optimization) contains:
28894 @quotation
28896 @example
28897 _increment__incr.1:
28898    subl $4,%esp
28899    movl 8(%esp),%eax
28900 #APP
28901    incl %eax
28902 #NO_APP
28903    movl %eax,%edx
28904    movl %ecx,(%esp)
28905    addl $4,%esp
28906    ret
28907 @end example
28908 @end quotation
28910 @node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
28911 @anchor{gnat_ugn/inline_assembler id6}@anchor{240}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{241}
28912 @section Inlining Inline Assembler Code
28915 For a short subprogram such as the @code{Incr} function in the previous
28916 section, the overhead of the call and return (creating / deleting the stack
28917 frame) can be significant, compared to the amount of code in the subprogram
28918 body.  A solution is to apply Ada’s @code{Inline} pragma to the subprogram,
28919 which directs the compiler to expand invocations of the subprogram at the
28920 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28921 Here is the resulting program:
28923 @quotation
28925 @example
28926 with Interfaces; use Interfaces;
28927 with Ada.Text_IO; use Ada.Text_IO;
28928 with System.Machine_Code; use System.Machine_Code;
28929 procedure Increment_2 is
28931    function Incr (Value : Unsigned_32) return Unsigned_32 is
28932       Result : Unsigned_32;
28933    begin
28934       Asm ("incl %0",
28935            Outputs => Unsigned_32'Asm_Output ("=a", Result),
28936            Inputs  => Unsigned_32'Asm_Input ("a", Value));
28937       return Result;
28938    end Incr;
28939    pragma Inline (Increment);
28941    Value : Unsigned_32;
28943 begin
28944    Value := 5;
28945    Put_Line ("Value before is" & Value'Img);
28946    Value := Increment (Value);
28947    Put_Line ("Value after is" & Value'Img);
28948 end Increment_2;
28949 @end example
28950 @end quotation
28952 Compile the program with both optimization (@code{-O2}) and inlining
28953 (@code{-gnatn}) enabled.
28955 The @code{Incr} function is still compiled as usual, but at the
28956 point in @code{Increment} where our function used to be called:
28958 @quotation
28960 @example
28961 pushl %edi
28962 call _increment__incr.1
28963 @end example
28964 @end quotation
28966 the code for the function body directly appears:
28968 @quotation
28970 @example
28971 movl %esi,%eax
28972 #APP
28973    incl %eax
28974 #NO_APP
28975    movl %eax,%edx
28976 @end example
28977 @end quotation
28979 thus saving the overhead of stack frame setup and an out-of-line call.
28981 @node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
28982 @anchor{gnat_ugn/inline_assembler id7}@anchor{242}@anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{243}
28983 @section Other @code{Asm} Functionality
28986 This section describes two important parameters to the @code{Asm}
28987 procedure: @code{Clobber}, which identifies register usage;
28988 and @code{Volatile}, which inhibits unwanted optimizations.
28990 @menu
28991 * The Clobber Parameter:: 
28992 * The Volatile Parameter:: 
28994 @end menu
28996 @node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
28997 @anchor{gnat_ugn/inline_assembler id8}@anchor{244}@anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{245}
28998 @subsection The @code{Clobber} Parameter
29001 One of the dangers of intermixing assembly language and a compiled language
29002 such as Ada is that the compiler needs to be aware of which registers are
29003 being used by the assembly code.  In some cases, such as the earlier examples,
29004 the constraint string is sufficient to indicate register usage (e.g.,
29005 @code{"a"} for
29006 the eax register).  But more generally, the compiler needs an explicit
29007 identification of the registers that are used by the Inline Assembly
29008 statements.
29010 Using a register that the compiler doesn’t know about
29011 could be a side effect of an instruction (like @code{mull}
29012 storing its result in both eax and edx).
29013 It can also arise from explicit register usage in your
29014 assembly code; for example:
29016 @quotation
29018 @example
29019 Asm ("movl %0, %%ebx" & LF & HT &
29020      "movl %%ebx, %1",
29021      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29022      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
29023 @end example
29024 @end quotation
29026 where the compiler (since it does not analyze the @code{Asm} template string)
29027 does not know you are using the ebx register.
29029 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
29030 to identify the registers that will be used by your assembly code:
29032 @quotation
29034 @example
29035 Asm ("movl %0, %%ebx" & LF & HT &
29036      "movl %%ebx, %1",
29037      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29038      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
29039      Clobber => "ebx");
29040 @end example
29041 @end quotation
29043 The Clobber parameter is a static string expression specifying the
29044 register(s) you are using.  Note that register names are @emph{not} prefixed
29045 by a percent sign. Also, if more than one register is used then their names
29046 are separated by commas; e.g., @code{"eax, ebx"}
29048 The @code{Clobber} parameter has several additional uses:
29051 @itemize *
29053 @item 
29054 Use ‘register’ name @code{cc} to indicate that flags might have changed
29056 @item 
29057 Use ‘register’ name @code{memory} if you changed a memory location
29058 @end itemize
29060 @node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
29061 @anchor{gnat_ugn/inline_assembler id9}@anchor{246}@anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{247}
29062 @subsection The @code{Volatile} Parameter
29065 @geindex Volatile parameter
29067 Compiler optimizations in the presence of Inline Assembler may sometimes have
29068 unwanted effects.  For example, when an @code{Asm} invocation with an input
29069 variable is inside a loop, the compiler might move the loading of the input
29070 variable outside the loop, regarding it as a one-time initialization.
29072 If this effect is not desired, you can disable such optimizations by setting
29073 the @code{Volatile} parameter to @code{True}; for example:
29075 @quotation
29077 @example
29078 Asm ("movl %0, %%ebx" & LF & HT &
29079      "movl %%ebx, %1",
29080      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
29081      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
29082      Clobber  => "ebx",
29083      Volatile => True);
29084 @end example
29085 @end quotation
29087 By default, @code{Volatile} is set to @code{False} unless there is no
29088 @code{Outputs} parameter.
29090 Although setting @code{Volatile} to @code{True} prevents unwanted
29091 optimizations, it will also disable other optimizations that might be
29092 important for efficiency. In general, you should set @code{Volatile}
29093 to @code{True} only if the compiler’s optimizations have created
29094 problems.
29096 @node GNU Free Documentation License,Index,Inline Assembler,Top
29097 @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}
29098 @chapter GNU Free Documentation License
29101 Version 1.3, 3 November 2008
29103 Copyright  2000, 2001, 2002, 2007, 2008  Free Software Foundation, Inc
29104 @indicateurl{https://fsf.org/}
29106 Everyone is permitted to copy and distribute verbatim copies of this
29107 license document, but changing it is not allowed.
29109 @strong{Preamble}
29111 The purpose of this License is to make a manual, textbook, or other
29112 functional and useful document “free” in the sense of freedom: to
29113 assure everyone the effective freedom to copy and redistribute it,
29114 with or without modifying it, either commercially or noncommercially.
29115 Secondarily, this License preserves for the author and publisher a way
29116 to get credit for their work, while not being considered responsible
29117 for modifications made by others.
29119 This License is a kind of “copyleft”, which means that derivative
29120 works of the document must themselves be free in the same sense.  It
29121 complements the GNU General Public License, which is a copyleft
29122 license designed for free software.
29124 We have designed this License in order to use it for manuals for free
29125 software, because free software needs free documentation: a free
29126 program should come with manuals providing the same freedoms that the
29127 software does.  But this License is not limited to software manuals;
29128 it can be used for any textual work, regardless of subject matter or
29129 whether it is published as a printed book.  We recommend this License
29130 principally for works whose purpose is instruction or reference.
29132 @strong{1. APPLICABILITY AND DEFINITIONS}
29134 This License applies to any manual or other work, in any medium, that
29135 contains a notice placed by the copyright holder saying it can be
29136 distributed under the terms of this License.  Such a notice grants a
29137 world-wide, royalty-free license, unlimited in duration, to use that
29138 work under the conditions stated herein.  The @strong{Document}, below,
29139 refers to any such manual or work.  Any member of the public is a
29140 licensee, and is addressed as “@strong{you}”.  You accept the license if you
29141 copy, modify or distribute the work in a way requiring permission
29142 under copyright law.
29144 A “@strong{Modified Version}” of the Document means any work containing the
29145 Document or a portion of it, either copied verbatim, or with
29146 modifications and/or translated into another language.
29148 A “@strong{Secondary Section}” is a named appendix or a front-matter section of
29149 the Document that deals exclusively with the relationship of the
29150 publishers or authors of the Document to the Document’s overall subject
29151 (or to related matters) and contains nothing that could fall directly
29152 within that overall subject.  (Thus, if the Document is in part a
29153 textbook of mathematics, a Secondary Section may not explain any
29154 mathematics.)  The relationship could be a matter of historical
29155 connection with the subject or with related matters, or of legal,
29156 commercial, philosophical, ethical or political position regarding
29157 them.
29159 The “@strong{Invariant Sections}” are certain Secondary Sections whose titles
29160 are designated, as being those of Invariant Sections, in the notice
29161 that says that the Document is released under this License.  If a
29162 section does not fit the above definition of Secondary then it is not
29163 allowed to be designated as Invariant.  The Document may contain zero
29164 Invariant Sections.  If the Document does not identify any Invariant
29165 Sections then there are none.
29167 The “@strong{Cover Texts}” are certain short passages of text that are listed,
29168 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
29169 the Document is released under this License.  A Front-Cover Text may
29170 be at most 5 words, and a Back-Cover Text may be at most 25 words.
29172 A “@strong{Transparent}” copy of the Document means a machine-readable copy,
29173 represented in a format whose specification is available to the
29174 general public, that is suitable for revising the document
29175 straightforwardly with generic text editors or (for images composed of
29176 pixels) generic paint programs or (for drawings) some widely available
29177 drawing editor, and that is suitable for input to text formatters or
29178 for automatic translation to a variety of formats suitable for input
29179 to text formatters.  A copy made in an otherwise Transparent file
29180 format whose markup, or absence of markup, has been arranged to thwart
29181 or discourage subsequent modification by readers is not Transparent.
29182 An image format is not Transparent if used for any substantial amount
29183 of text.  A copy that is not “Transparent” is called @strong{Opaque}.
29185 Examples of suitable formats for Transparent copies include plain
29186 ASCII without markup, Texinfo input format, LaTeX input format, SGML
29187 or XML using a publicly available DTD, and standard-conforming simple
29188 HTML, PostScript or PDF designed for human modification.  Examples of
29189 transparent image formats include PNG, XCF and JPG.  Opaque formats
29190 include proprietary formats that can be read and edited only by
29191 proprietary word processors, SGML or XML for which the DTD and/or
29192 processing tools are not generally available, and the
29193 machine-generated HTML, PostScript or PDF produced by some word
29194 processors for output purposes only.
29196 The “@strong{Title Page}” means, for a printed book, the title page itself,
29197 plus such following pages as are needed to hold, legibly, the material
29198 this License requires to appear in the title page.  For works in
29199 formats which do not have any title page as such, “Title Page” means
29200 the text near the most prominent appearance of the work’s title,
29201 preceding the beginning of the body of the text.
29203 The “@strong{publisher}” means any person or entity that distributes
29204 copies of the Document to the public.
29206 A section “@strong{Entitled XYZ}” means a named subunit of the Document whose
29207 title either is precisely XYZ or contains XYZ in parentheses following
29208 text that translates XYZ in another language.  (Here XYZ stands for a
29209 specific section name mentioned below, such as “@strong{Acknowledgements}”,
29210 “@strong{Dedications}”, “@strong{Endorsements}”, or “@strong{History}”.)
29211 To “@strong{Preserve the Title}”
29212 of such a section when you modify the Document means that it remains a
29213 section “Entitled XYZ” according to this definition.
29215 The Document may include Warranty Disclaimers next to the notice which
29216 states that this License applies to the Document.  These Warranty
29217 Disclaimers are considered to be included by reference in this
29218 License, but only as regards disclaiming warranties: any other
29219 implication that these Warranty Disclaimers may have is void and has
29220 no effect on the meaning of this License.
29222 @strong{2. VERBATIM COPYING}
29224 You may copy and distribute the Document in any medium, either
29225 commercially or noncommercially, provided that this License, the
29226 copyright notices, and the license notice saying this License applies
29227 to the Document are reproduced in all copies, and that you add no other
29228 conditions whatsoever to those of this License.  You may not use
29229 technical measures to obstruct or control the reading or further
29230 copying of the copies you make or distribute.  However, you may accept
29231 compensation in exchange for copies.  If you distribute a large enough
29232 number of copies you must also follow the conditions in section 3.
29234 You may also lend copies, under the same conditions stated above, and
29235 you may publicly display copies.
29237 @strong{3. COPYING IN QUANTITY}
29239 If you publish printed copies (or copies in media that commonly have
29240 printed covers) of the Document, numbering more than 100, and the
29241 Document’s license notice requires Cover Texts, you must enclose the
29242 copies in covers that carry, clearly and legibly, all these Cover
29243 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
29244 the back cover.  Both covers must also clearly and legibly identify
29245 you as the publisher of these copies.  The front cover must present
29246 the full title with all words of the title equally prominent and
29247 visible.  You may add other material on the covers in addition.
29248 Copying with changes limited to the covers, as long as they preserve
29249 the title of the Document and satisfy these conditions, can be treated
29250 as verbatim copying in other respects.
29252 If the required texts for either cover are too voluminous to fit
29253 legibly, you should put the first ones listed (as many as fit
29254 reasonably) on the actual cover, and continue the rest onto adjacent
29255 pages.
29257 If you publish or distribute Opaque copies of the Document numbering
29258 more than 100, you must either include a machine-readable Transparent
29259 copy along with each Opaque copy, or state in or with each Opaque copy
29260 a computer-network location from which the general network-using
29261 public has access to download using public-standard network protocols
29262 a complete Transparent copy of the Document, free of added material.
29263 If you use the latter option, you must take reasonably prudent steps,
29264 when you begin distribution of Opaque copies in quantity, to ensure
29265 that this Transparent copy will remain thus accessible at the stated
29266 location until at least one year after the last time you distribute an
29267 Opaque copy (directly or through your agents or retailers) of that
29268 edition to the public.
29270 It is requested, but not required, that you contact the authors of the
29271 Document well before redistributing any large number of copies, to give
29272 them a chance to provide you with an updated version of the Document.
29274 @strong{4. MODIFICATIONS}
29276 You may copy and distribute a Modified Version of the Document under
29277 the conditions of sections 2 and 3 above, provided that you release
29278 the Modified Version under precisely this License, with the Modified
29279 Version filling the role of the Document, thus licensing distribution
29280 and modification of the Modified Version to whoever possesses a copy
29281 of it.  In addition, you must do these things in the Modified Version:
29284 @enumerate A
29286 @item 
29287 Use in the Title Page (and on the covers, if any) a title distinct
29288 from that of the Document, and from those of previous versions
29289 (which should, if there were any, be listed in the History section
29290 of the Document).  You may use the same title as a previous version
29291 if the original publisher of that version gives permission.
29293 @item 
29294 List on the Title Page, as authors, one or more persons or entities
29295 responsible for authorship of the modifications in the Modified
29296 Version, together with at least five of the principal authors of the
29297 Document (all of its principal authors, if it has fewer than five),
29298 unless they release you from this requirement.
29300 @item 
29301 State on the Title page the name of the publisher of the
29302 Modified Version, as the publisher.
29304 @item 
29305 Preserve all the copyright notices of the Document.
29307 @item 
29308 Add an appropriate copyright notice for your modifications
29309 adjacent to the other copyright notices.
29311 @item 
29312 Include, immediately after the copyright notices, a license notice
29313 giving the public permission to use the Modified Version under the
29314 terms of this License, in the form shown in the Addendum below.
29316 @item 
29317 Preserve in that license notice the full lists of Invariant Sections
29318 and required Cover Texts given in the Document’s license notice.
29320 @item 
29321 Include an unaltered copy of this License.
29323 @item 
29324 Preserve the section Entitled “History”, Preserve its Title, and add
29325 to it an item stating at least the title, year, new authors, and
29326 publisher of the Modified Version as given on the Title Page.  If
29327 there is no section Entitled “History” in the Document, create one
29328 stating the title, year, authors, and publisher of the Document as
29329 given on its Title Page, then add an item describing the Modified
29330 Version as stated in the previous sentence.
29332 @item 
29333 Preserve the network location, if any, given in the Document for
29334 public access to a Transparent copy of the Document, and likewise
29335 the network locations given in the Document for previous versions
29336 it was based on.  These may be placed in the “History” section.
29337 You may omit a network location for a work that was published at
29338 least four years before the Document itself, or if the original
29339 publisher of the version it refers to gives permission.
29341 @item 
29342 For any section Entitled “Acknowledgements” or “Dedications”,
29343 Preserve the Title of the section, and preserve in the section all
29344 the substance and tone of each of the contributor acknowledgements
29345 and/or dedications given therein.
29347 @item 
29348 Preserve all the Invariant Sections of the Document,
29349 unaltered in their text and in their titles.  Section numbers
29350 or the equivalent are not considered part of the section titles.
29352 @item 
29353 Delete any section Entitled “Endorsements”.  Such a section
29354 may not be included in the Modified Version.
29356 @item 
29357 Do not retitle any existing section to be Entitled “Endorsements”
29358 or to conflict in title with any Invariant Section.
29360 @item 
29361 Preserve any Warranty Disclaimers.
29362 @end enumerate
29364 If the Modified Version includes new front-matter sections or
29365 appendices that qualify as Secondary Sections and contain no material
29366 copied from the Document, you may at your option designate some or all
29367 of these sections as invariant.  To do this, add their titles to the
29368 list of Invariant Sections in the Modified Version’s license notice.
29369 These titles must be distinct from any other section titles.
29371 You may add a section Entitled “Endorsements”, provided it contains
29372 nothing but endorsements of your Modified Version by various
29373 parties—for example, statements of peer review or that the text has
29374 been approved by an organization as the authoritative definition of a
29375 standard.
29377 You may add a passage of up to five words as a Front-Cover Text, and a
29378 passage of up to 25 words as a Back-Cover Text, to the end of the list
29379 of Cover Texts in the Modified Version.  Only one passage of
29380 Front-Cover Text and one of Back-Cover Text may be added by (or
29381 through arrangements made by) any one entity.  If the Document already
29382 includes a cover text for the same cover, previously added by you or
29383 by arrangement made by the same entity you are acting on behalf of,
29384 you may not add another; but you may replace the old one, on explicit
29385 permission from the previous publisher that added the old one.
29387 The author(s) and publisher(s) of the Document do not by this License
29388 give permission to use their names for publicity for or to assert or
29389 imply endorsement of any Modified Version.
29391 @strong{5. COMBINING DOCUMENTS}
29393 You may combine the Document with other documents released under this
29394 License, under the terms defined in section 4 above for modified
29395 versions, provided that you include in the combination all of the
29396 Invariant Sections of all of the original documents, unmodified, and
29397 list them all as Invariant Sections of your combined work in its
29398 license notice, and that you preserve all their Warranty Disclaimers.
29400 The combined work need only contain one copy of this License, and
29401 multiple identical Invariant Sections may be replaced with a single
29402 copy.  If there are multiple Invariant Sections with the same name but
29403 different contents, make the title of each such section unique by
29404 adding at the end of it, in parentheses, the name of the original
29405 author or publisher of that section if known, or else a unique number.
29406 Make the same adjustment to the section titles in the list of
29407 Invariant Sections in the license notice of the combined work.
29409 In the combination, you must combine any sections Entitled “History”
29410 in the various original documents, forming one section Entitled
29411 “History”; likewise combine any sections Entitled “Acknowledgements”,
29412 and any sections Entitled “Dedications”.  You must delete all sections
29413 Entitled “Endorsements”.
29415 @strong{6. COLLECTIONS OF DOCUMENTS}
29417 You may make a collection consisting of the Document and other documents
29418 released under this License, and replace the individual copies of this
29419 License in the various documents with a single copy that is included in
29420 the collection, provided that you follow the rules of this License for
29421 verbatim copying of each of the documents in all other respects.
29423 You may extract a single document from such a collection, and distribute
29424 it individually under this License, provided you insert a copy of this
29425 License into the extracted document, and follow this License in all
29426 other respects regarding verbatim copying of that document.
29428 @strong{7. AGGREGATION WITH INDEPENDENT WORKS}
29430 A compilation of the Document or its derivatives with other separate
29431 and independent documents or works, in or on a volume of a storage or
29432 distribution medium, is called an “aggregate” if the copyright
29433 resulting from the compilation is not used to limit the legal rights
29434 of the compilation’s users beyond what the individual works permit.
29435 When the Document is included in an aggregate, this License does not
29436 apply to the other works in the aggregate which are not themselves
29437 derivative works of the Document.
29439 If the Cover Text requirement of section 3 is applicable to these
29440 copies of the Document, then if the Document is less than one half of
29441 the entire aggregate, the Document’s Cover Texts may be placed on
29442 covers that bracket the Document within the aggregate, or the
29443 electronic equivalent of covers if the Document is in electronic form.
29444 Otherwise they must appear on printed covers that bracket the whole
29445 aggregate.
29447 @strong{8. TRANSLATION}
29449 Translation is considered a kind of modification, so you may
29450 distribute translations of the Document under the terms of section 4.
29451 Replacing Invariant Sections with translations requires special
29452 permission from their copyright holders, but you may include
29453 translations of some or all Invariant Sections in addition to the
29454 original versions of these Invariant Sections.  You may include a
29455 translation of this License, and all the license notices in the
29456 Document, and any Warranty Disclaimers, provided that you also include
29457 the original English version of this License and the original versions
29458 of those notices and disclaimers.  In case of a disagreement between
29459 the translation and the original version of this License or a notice
29460 or disclaimer, the original version will prevail.
29462 If a section in the Document is Entitled “Acknowledgements”,
29463 “Dedications”, or “History”, the requirement (section 4) to Preserve
29464 its Title (section 1) will typically require changing the actual
29465 title.
29467 @strong{9. TERMINATION}
29469 You may not copy, modify, sublicense, or distribute the Document
29470 except as expressly provided under this License.  Any attempt
29471 otherwise to copy, modify, sublicense, or distribute it is void, and
29472 will automatically terminate your rights under this License.
29474 However, if you cease all violation of this License, then your license
29475 from a particular copyright holder is reinstated (a) provisionally,
29476 unless and until the copyright holder explicitly and finally
29477 terminates your license, and (b) permanently, if the copyright holder
29478 fails to notify you of the violation by some reasonable means prior to
29479 60 days after the cessation.
29481 Moreover, your license from a particular copyright holder is
29482 reinstated permanently if the copyright holder notifies you of the
29483 violation by some reasonable means, this is the first time you have
29484 received notice of violation of this License (for any work) from that
29485 copyright holder, and you cure the violation prior to 30 days after
29486 your receipt of the notice.
29488 Termination of your rights under this section does not terminate the
29489 licenses of parties who have received copies or rights from you under
29490 this License.  If your rights have been terminated and not permanently
29491 reinstated, receipt of a copy of some or all of the same material does
29492 not give you any rights to use it.
29494 @strong{10. FUTURE REVISIONS OF THIS LICENSE}
29496 The Free Software Foundation may publish new, revised versions
29497 of the GNU Free Documentation License from time to time.  Such new
29498 versions will be similar in spirit to the present version, but may
29499 differ in detail to address new problems or concerns.  See
29500 @indicateurl{https://www.gnu.org/copyleft/}.
29502 Each version of the License is given a distinguishing version number.
29503 If the Document specifies that a particular numbered version of this
29504 License “or any later version” applies to it, you have the option of
29505 following the terms and conditions either of that specified version or
29506 of any later version that has been published (not as a draft) by the
29507 Free Software Foundation.  If the Document does not specify a version
29508 number of this License, you may choose any version ever published (not
29509 as a draft) by the Free Software Foundation.  If the Document
29510 specifies that a proxy can decide which future versions of this
29511 License can be used, that proxy’s public statement of acceptance of a
29512 version permanently authorizes you to choose that version for the
29513 Document.
29515 @strong{11. RELICENSING}
29517 “Massive Multiauthor Collaboration Site” (or “MMC Site”) means any
29518 World Wide Web server that publishes copyrightable works and also
29519 provides prominent facilities for anybody to edit those works.  A
29520 public wiki that anybody can edit is an example of such a server.  A
29521 “Massive Multiauthor Collaboration” (or “MMC”) contained in the
29522 site means any set of copyrightable works thus published on the MMC
29523 site.
29525 “CC-BY-SA” means the Creative Commons Attribution-Share Alike 3.0
29526 license published by Creative Commons Corporation, a not-for-profit
29527 corporation with a principal place of business in San Francisco,
29528 California, as well as future copyleft versions of that license
29529 published by that same organization.
29531 “Incorporate” means to publish or republish a Document, in whole or
29532 in part, as part of another Document.
29534 An MMC is “eligible for relicensing” if it is licensed under this
29535 License, and if all works that were first published under this License
29536 somewhere other than this MMC, and subsequently incorporated in whole
29537 or in part into the MMC, (1) had no cover texts or invariant sections,
29538 and (2) were thus incorporated prior to November 1, 2008.
29540 The operator of an MMC Site may republish an MMC contained in the site
29541 under CC-BY-SA on the same site at any time before August 1, 2009,
29542 provided the MMC is eligible for relicensing.
29544 @strong{ADDENDUM: How to use this License for your documents}
29546 To use this License in a document you have written, include a copy of
29547 the License in the document and put the following copyright and
29548 license notices just after the title page:
29550 @quotation
29552 Copyright © YEAR  YOUR NAME.
29553 Permission is granted to copy, distribute and/or modify this document
29554 under the terms of the GNU Free Documentation License, Version 1.3
29555 or any later version published by the Free Software Foundation;
29556 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
29557 A copy of the license is included in the section entitled “GNU
29558 Free Documentation License”.
29559 @end quotation
29561 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
29562 replace the “with … Texts.” line with this:
29564 @quotation
29566 with the Invariant Sections being LIST THEIR TITLES, with the
29567 Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
29568 @end quotation
29570 If you have Invariant Sections without Cover Texts, or some other
29571 combination of the three, merge those two alternatives to suit the
29572 situation.
29574 If your document contains nontrivial examples of program code, we
29575 recommend releasing these examples in parallel under your choice of
29576 free software license, such as the GNU General Public License,
29577 to permit their use in free software.
29579 @node Index,,GNU Free Documentation License,Top
29580 @unnumbered Index
29583 @printindex ge
29585 @anchor{d1}@w{                              }
29586 @anchor{gnat_ugn/gnat_utility_programs switches-related-to-project-files}@w{                              }
29588 @c %**end of body
29589 @bye