2018-03-02 Richard Biener <rguenther@suse.de>
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blob63361fce1579b2ac7e3e65e6b188e5337cd51538
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 1.4.6.@*
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 15, 2017
26 AdaCore
28 Copyright @copyright{} 2008-2018, 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 * A Note to Readers of Previous Versions of the Manual:: 
89 * Conventions:: 
91 Getting Started with GNAT
93 * Running GNAT:: 
94 * Running a Simple Ada Program:: 
95 * Running a Program with Multiple Units:: 
96 * Using the gnatmake Utility:: 
98 The GNAT Compilation Model
100 * Source Representation:: 
101 * Foreign Language Representation:: 
102 * File Naming Topics and Utilities:: 
103 * Configuration Pragmas:: 
104 * Generating Object Files:: 
105 * Source Dependencies:: 
106 * The Ada Library Information Files:: 
107 * Binding an Ada Program:: 
108 * GNAT and Libraries:: 
109 * Conditional Compilation:: 
110 * Mixed Language Programming:: 
111 * GNAT and Other Compilation Models:: 
112 * Using GNAT Files with External Tools:: 
114 Foreign Language Representation
116 * Latin-1:: 
117 * Other 8-Bit Codes:: 
118 * Wide_Character Encodings:: 
119 * Wide_Wide_Character Encodings:: 
121 File Naming Topics and Utilities
123 * File Naming Rules:: 
124 * Using Other File Names:: 
125 * Alternative File Naming Schemes:: 
126 * Handling Arbitrary File Naming Conventions with gnatname:: 
127 * File Name Krunching with gnatkr:: 
128 * Renaming Files with gnatchop:: 
130 Handling Arbitrary File Naming Conventions with gnatname
132 * Arbitrary File Naming Conventions:: 
133 * Running gnatname:: 
134 * Switches for gnatname:: 
135 * Examples of gnatname Usage:: 
137 File Name Krunching with gnatkr
139 * About gnatkr:: 
140 * Using gnatkr:: 
141 * Krunching Method:: 
142 * Examples of gnatkr Usage:: 
144 Renaming Files with gnatchop
146 * Handling Files with Multiple Units:: 
147 * Operating gnatchop in Compilation Mode:: 
148 * Command Line for gnatchop:: 
149 * Switches for gnatchop:: 
150 * Examples of gnatchop Usage:: 
152 Configuration Pragmas
154 * Handling of Configuration Pragmas:: 
155 * The Configuration Pragmas Files:: 
157 GNAT and Libraries
159 * Introduction to Libraries in GNAT:: 
160 * General Ada Libraries:: 
161 * Stand-alone Ada Libraries:: 
162 * Rebuilding the GNAT Run-Time Library:: 
164 General Ada Libraries
166 * Building a library:: 
167 * Installing a library:: 
168 * Using a library:: 
170 Stand-alone Ada Libraries
172 * Introduction to Stand-alone Libraries:: 
173 * Building a Stand-alone Library:: 
174 * Creating a Stand-alone Library to be used in a non-Ada context:: 
175 * Restrictions in Stand-alone Libraries:: 
177 Conditional Compilation
179 * Modeling Conditional Compilation in Ada:: 
180 * Preprocessing with gnatprep:: 
181 * Integrated Preprocessing:: 
183 Modeling Conditional Compilation in Ada
185 * Use of Boolean Constants:: 
186 * Debugging - A Special Case:: 
187 * Conditionalizing Declarations:: 
188 * Use of Alternative Implementations:: 
189 * Preprocessing:: 
191 Preprocessing with gnatprep
193 * Preprocessing Symbols:: 
194 * Using gnatprep:: 
195 * Switches for gnatprep:: 
196 * Form of Definitions File:: 
197 * Form of Input Text for gnatprep:: 
199 Mixed Language Programming
201 * Interfacing to C:: 
202 * Calling Conventions:: 
203 * Building Mixed Ada and C++ Programs:: 
204 * Generating Ada Bindings for C and C++ headers:: 
205 * Generating C Headers for Ada Specifications:: 
207 Building Mixed Ada and C++ Programs
209 * Interfacing to C++:: 
210 * Linking a Mixed C++ & Ada Program:: 
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:: 
316 * The Cross-Referencing Tools gnatxref and gnatfind:: 
317 * The Ada to HTML Converter gnathtml:: 
319 The File Cleanup Utility gnatclean
321 * Running gnatclean:: 
322 * Switches for gnatclean:: 
324 The GNAT Library Browser gnatls
326 * Running gnatls:: 
327 * Switches for gnatls:: 
328 * Example of gnatls Usage:: 
330 The Cross-Referencing Tools gnatxref and gnatfind
332 * gnatxref Switches:: 
333 * gnatfind Switches:: 
334 * Configuration Files for gnatxref and gnatfind:: 
335 * Regular Expressions in gnatfind and gnatxref:: 
336 * Examples of gnatxref Usage:: 
337 * Examples of gnatfind Usage:: 
339 Examples of gnatxref Usage
341 * General Usage:: 
342 * Using gnatxref with vi:: 
344 The Ada to HTML Converter gnathtml
346 * Invoking gnathtml:: 
347 * Installing gnathtml:: 
349 GNAT and Program Execution
351 * Running and Debugging Ada Programs:: 
352 * Code Coverage and Profiling:: 
353 * Improving Performance:: 
354 * Overflow Check Handling in GNAT:: 
355 * Performing Dimensionality Analysis in GNAT:: 
356 * Stack Related Facilities:: 
357 * Memory Management Issues:: 
359 Running and Debugging Ada Programs
361 * The GNAT Debugger GDB:: 
362 * Running GDB:: 
363 * Introduction to GDB Commands:: 
364 * Using Ada Expressions:: 
365 * Calling User-Defined Subprograms:: 
366 * Using the next Command in a Function:: 
367 * Stopping When Ada Exceptions Are Raised:: 
368 * Ada Tasks:: 
369 * Debugging Generic Units:: 
370 * Remote Debugging with gdbserver:: 
371 * GNAT Abnormal Termination or Failure to Terminate:: 
372 * Naming Conventions for GNAT Source Files:: 
373 * Getting Internal Debugging Information:: 
374 * Stack Traceback:: 
375 * Pretty-Printers for the GNAT runtime:: 
377 Stack Traceback
379 * Non-Symbolic Traceback:: 
380 * Symbolic Traceback:: 
382 Code Coverage and Profiling
384 * Code Coverage of Ada Programs with gcov:: 
385 * Profiling an Ada Program with gprof:: 
387 Code Coverage of Ada Programs with gcov
389 * Quick startup guide:: 
390 * GNAT specifics:: 
392 Profiling an Ada Program with gprof
394 * Compilation for profiling:: 
395 * Program execution:: 
396 * Running gprof:: 
397 * Interpretation of profiling results:: 
399 Improving Performance
401 * Performance Considerations:: 
402 * Text_IO Suggestions:: 
403 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
405 Performance Considerations
407 * Controlling Run-Time Checks:: 
408 * Use of Restrictions:: 
409 * Optimization Levels:: 
410 * Debugging Optimized Code:: 
411 * Inlining of Subprograms:: 
412 * Floating_Point_Operations:: 
413 * Vectorization of loops:: 
414 * Other Optimization Switches:: 
415 * Optimization and Strict Aliasing:: 
416 * Aliased Variables and Optimization:: 
417 * Atomic Variables and Optimization:: 
418 * Passive Task Optimization:: 
420 Reducing Size of Executables with Unused Subprogram/Data Elimination
422 * About unused subprogram/data elimination:: 
423 * Compilation options:: 
424 * Example of unused subprogram/data elimination:: 
426 Overflow Check Handling in GNAT
428 * Background:: 
429 * Management of Overflows in GNAT:: 
430 * Specifying the Desired Mode:: 
431 * Default Settings:: 
432 * Implementation Notes:: 
434 Stack Related Facilities
436 * Stack Overflow Checking:: 
437 * Static Stack Usage Analysis:: 
438 * Dynamic Stack Usage Analysis:: 
440 Memory Management Issues
442 * Some Useful Memory Pools:: 
443 * The GNAT Debug Pool Facility:: 
445 Platform-Specific Information
447 * Run-Time Libraries:: 
448 * Specifying a Run-Time Library:: 
449 * GNU/Linux Topics:: 
450 * Microsoft Windows Topics:: 
451 * Mac OS Topics:: 
453 Run-Time Libraries
455 * Summary of Run-Time Configurations:: 
457 Specifying a Run-Time Library
459 * Choosing the Scheduling Policy:: 
461 GNU/Linux Topics
463 * Required Packages on GNU/Linux:: 
465 Microsoft Windows Topics
467 * Using GNAT on Windows:: 
468 * Using a network installation of GNAT:: 
469 * CONSOLE and WINDOWS subsystems:: 
470 * Temporary Files:: 
471 * Disabling Command Line Argument Expansion:: 
472 * Mixed-Language Programming on Windows:: 
473 * Windows Specific Add-Ons:: 
475 Mixed-Language Programming on Windows
477 * Windows Calling Conventions:: 
478 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
479 * Using DLLs with GNAT:: 
480 * Building DLLs with GNAT Project files:: 
481 * Building DLLs with GNAT:: 
482 * Building DLLs with gnatdll:: 
483 * Ada DLLs and Finalization:: 
484 * Creating a Spec for Ada DLLs:: 
485 * GNAT and Windows Resources:: 
486 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
487 * Debugging a DLL:: 
488 * Setting Stack Size from gnatlink:: 
489 * Setting Heap Size from gnatlink:: 
491 Windows Calling Conventions
493 * C Calling Convention:: 
494 * Stdcall Calling Convention:: 
495 * Win32 Calling Convention:: 
496 * DLL Calling Convention:: 
498 Using DLLs with GNAT
500 * Creating an Ada Spec for the DLL Services:: 
501 * Creating an Import Library:: 
503 Building DLLs with gnatdll
505 * Limitations When Using Ada DLLs from Ada:: 
506 * Exporting Ada Entities:: 
507 * Ada DLLs and Elaboration:: 
509 Creating a Spec for Ada DLLs
511 * Creating the Definition File:: 
512 * Using gnatdll:: 
514 GNAT and Windows Resources
516 * Building Resources:: 
517 * Compiling Resources:: 
518 * Using Resources:: 
520 Debugging a DLL
522 * Program and DLL Both Built with GCC/GNAT:: 
523 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
525 Windows Specific Add-Ons
527 * Win32Ada:: 
528 * wPOSIX:: 
530 Mac OS Topics
532 * Codesigning the Debugger:: 
534 Elaboration Order Handling in GNAT
536 * Elaboration Code:: 
537 * Elaboration Order:: 
538 * Checking the Elaboration Order:: 
539 * Controlling the Elaboration Order in Ada:: 
540 * Controlling the Elaboration Order in GNAT:: 
541 * Common Elaboration-model Traits:: 
542 * Dynamic Elaboration Model in GNAT:: 
543 * Static Elaboration Model in GNAT:: 
544 * SPARK Elaboration Model in GNAT:: 
545 * Legacy Elaboration Model in GNAT:: 
546 * Mixing Elaboration Models:: 
547 * Elaboration Circularities:: 
548 * Resolving Elaboration Circularities:: 
549 * Resolving Task Issues:: 
550 * Elaboration-related Compiler Switches:: 
551 * Summary of Procedures for Elaboration Control:: 
552 * Inspecting the Chosen Elaboration Order:: 
554 Inline Assembler
556 * Basic Assembler Syntax:: 
557 * A Simple Example of Inline Assembler:: 
558 * Output Variables in Inline Assembler:: 
559 * Input Variables in Inline Assembler:: 
560 * Inlining Inline Assembler Code:: 
561 * Other Asm Functionality:: 
563 Other Asm Functionality
565 * The Clobber Parameter:: 
566 * The Volatile Parameter:: 
568 @end detailmenu
569 @end menu
571 @node About This Guide,Getting Started with GNAT,Top,Top
572 @anchor{gnat_ugn/about_this_guide about-this-guide}@anchor{2}@anchor{gnat_ugn/about_this_guide doc}@anchor{3}@anchor{gnat_ugn/about_this_guide gnat-user-s-guide-for-native-platforms}@anchor{4}@anchor{gnat_ugn/about_this_guide id1}@anchor{5}
573 @chapter About This Guide
577 This guide describes the use of GNAT,
578 a compiler and software development
579 toolset for the full Ada programming language.
580 It documents the features of the compiler and tools, and explains
581 how to use them to build Ada applications.
583 GNAT implements Ada 95, Ada 2005 and Ada 2012, and it may also be
584 invoked in Ada 83 compatibility mode.
585 By default, GNAT assumes Ada 2012, but you can override with a
586 compiler switch (@ref{6,,Compiling Different Versions of Ada})
587 to explicitly specify the language version.
588 Throughout this manual, references to 'Ada' without a year suffix
589 apply to all Ada 95/2005/2012 versions of the language.
591 @menu
592 * What This Guide Contains:: 
593 * What You Should Know before Reading This Guide:: 
594 * Related Information:: 
595 * A Note to Readers of Previous Versions of the Manual:: 
596 * Conventions:: 
598 @end menu
600 @node What This Guide Contains,What You Should Know before Reading This Guide,,About This Guide
601 @anchor{gnat_ugn/about_this_guide what-this-guide-contains}@anchor{7}
602 @section What This Guide Contains
605 This guide contains the following chapters:
608 @itemize *
610 @item 
611 @ref{8,,Getting Started with GNAT} describes how to get started compiling
612 and running Ada programs with the GNAT Ada programming environment.
614 @item 
615 @ref{9,,The GNAT Compilation Model} describes the compilation model used
616 by GNAT.
618 @item 
619 @ref{a,,Building Executable Programs with GNAT} describes how to use the
620 main GNAT tools to build executable programs, and it also gives examples of
621 using the GNU make utility with GNAT.
623 @item 
624 @ref{b,,GNAT Utility Programs} explains the various utility programs that
625 are included in the GNAT environment
627 @item 
628 @ref{c,,GNAT and Program Execution} covers a number of topics related to
629 running, debugging, and tuning the performace of programs developed
630 with GNAT
631 @end itemize
633 Appendices cover several additional topics:
636 @itemize *
638 @item 
639 @ref{d,,Platform-Specific Information} describes the different run-time
640 library implementations and also presents information on how to use
641 GNAT on several specific platforms
643 @item 
644 @ref{e,,Example of Binder Output File} shows the source code for the binder
645 output file for a sample program.
647 @item 
648 @ref{f,,Elaboration Order Handling in GNAT} describes how GNAT helps
649 you deal with elaboration order issues.
651 @item 
652 @ref{10,,Inline Assembler} shows how to use the inline assembly facility
653 in an Ada program.
654 @end itemize
656 @node What You Should Know before Reading This Guide,Related Information,What This Guide Contains,About This Guide
657 @anchor{gnat_ugn/about_this_guide what-you-should-know-before-reading-this-guide}@anchor{11}
658 @section What You Should Know before Reading This Guide
661 @geindex Ada 95 Language Reference Manual
663 @geindex Ada 2005 Language Reference Manual
665 This guide assumes a basic familiarity with the Ada 95 language, as
666 described in the International Standard ANSI/ISO/IEC-8652:1995, January
667 1995.
668 It does not require knowledge of the features introduced by Ada 2005
669 or Ada 2012.
670 Reference manuals for Ada 95, Ada 2005, and Ada 2012 are included in
671 the GNAT documentation package.
673 @node Related Information,A Note to Readers of Previous Versions of the Manual,What You Should Know before Reading This Guide,About This Guide
674 @anchor{gnat_ugn/about_this_guide related-information}@anchor{12}
675 @section Related Information
678 For further information about Ada and related tools, please refer to the
679 following documents:
682 @itemize *
684 @item 
685 @cite{Ada 95 Reference Manual}, @cite{Ada 2005 Reference Manual}, and
686 @cite{Ada 2012 Reference Manual}, which contain reference
687 material for the several revisions of the Ada language standard.
689 @item 
690 @cite{GNAT Reference_Manual}, which contains all reference material for the GNAT
691 implementation of Ada.
693 @item 
694 @cite{Using the GNAT Programming Studio}, which describes the GPS
695 Integrated Development Environment.
697 @item 
698 @cite{GNAT Programming Studio Tutorial}, which introduces the
699 main GPS features through examples.
701 @item 
702 @cite{Debugging with GDB},
703 for all details on the use of the GNU source-level debugger.
705 @item 
706 @cite{GNU Emacs Manual},
707 for full information on the extensible editor and programming
708 environment Emacs.
709 @end itemize
711 @node A Note to Readers of Previous Versions of the Manual,Conventions,Related Information,About This Guide
712 @anchor{gnat_ugn/about_this_guide a-note-to-readers-of-previous-versions-of-the-manual}@anchor{13}
713 @section A Note to Readers of Previous Versions of the Manual
716 In early 2015 the GNAT manuals were transitioned to the
717 reStructuredText (rst) / Sphinx documentation generator technology.
718 During that process the @cite{GNAT User's Guide} was reorganized
719 so that related topics would be described together in the same chapter
720 or appendix.  Here's a summary of the major changes realized in
721 the new document structure.
724 @itemize *
726 @item 
727 @ref{9,,The GNAT Compilation Model} has been extended so that it now covers
728 the following material:
731 @itemize -
733 @item 
734 The @code{gnatname}, @code{gnatkr}, and @code{gnatchop} tools
736 @item 
737 @ref{14,,Configuration Pragmas}
739 @item 
740 @ref{15,,GNAT and Libraries}
742 @item 
743 @ref{16,,Conditional Compilation} including @ref{17,,Preprocessing with gnatprep}
744 and @ref{18,,Integrated Preprocessing}
746 @item 
747 @ref{19,,Generating Ada Bindings for C and C++ headers}
749 @item 
750 @ref{1a,,Using GNAT Files with External Tools}
751 @end itemize
753 @item 
754 @ref{a,,Building Executable Programs with GNAT} is a new chapter consolidating
755 the following content:
758 @itemize -
760 @item 
761 @ref{1b,,Building with gnatmake}
763 @item 
764 @ref{1c,,Compiling with gcc}
766 @item 
767 @ref{1d,,Binding with gnatbind}
769 @item 
770 @ref{1e,,Linking with gnatlink}
772 @item 
773 @ref{1f,,Using the GNU make Utility}
774 @end itemize
776 @item 
777 @ref{b,,GNAT Utility Programs} is a new chapter consolidating the information about several
778 GNAT tools:
782 @itemize -
784 @item 
785 @ref{20,,The File Cleanup Utility gnatclean}
787 @item 
788 @ref{21,,The GNAT Library Browser gnatls}
790 @item 
791 @ref{22,,The Cross-Referencing Tools gnatxref and gnatfind}
793 @item 
794 @ref{23,,The Ada to HTML Converter gnathtml}
795 @end itemize
797 @item 
798 @ref{c,,GNAT and Program Execution} is a new chapter consolidating the following:
801 @itemize -
803 @item 
804 @ref{24,,Running and Debugging Ada Programs}
806 @item 
807 @ref{25,,Code Coverage and Profiling}
809 @item 
810 @ref{26,,Improving Performance}
812 @item 
813 @ref{27,,Overflow Check Handling in GNAT}
815 @item 
816 @ref{28,,Performing Dimensionality Analysis in GNAT}
818 @item 
819 @ref{29,,Stack Related Facilities}
821 @item 
822 @ref{2a,,Memory Management Issues}
823 @end itemize
825 @item 
826 @ref{d,,Platform-Specific Information} is a new appendix consolidating the following:
829 @itemize -
831 @item 
832 @ref{2b,,Run-Time Libraries}
834 @item 
835 @ref{2c,,Microsoft Windows Topics}
837 @item 
838 @ref{2d,,Mac OS Topics}
839 @end itemize
841 @item 
842 The @emph{Compatibility and Porting Guide} appendix has been moved to the
843 @cite{GNAT Reference Manual}. It now includes a section
844 @emph{Writing Portable Fixed-Point Declarations} which was previously
845 a separate chapter in the @cite{GNAT User's Guide}.
846 @end itemize
848 @node Conventions,,A Note to Readers of Previous Versions of the Manual,About This Guide
849 @anchor{gnat_ugn/about_this_guide conventions}@anchor{2e}
850 @section Conventions
853 @geindex Conventions
854 @geindex typographical
856 @geindex Typographical conventions
858 Following are examples of the typographical and graphic conventions used
859 in this guide:
862 @itemize *
864 @item 
865 @code{Functions}, @code{utility program names}, @code{standard names},
866 and @code{classes}.
868 @item 
869 @code{Option flags}
871 @item 
872 @code{File names}
874 @item 
875 @code{Variables}
877 @item 
878 @emph{Emphasis}
880 @item 
881 [optional information or parameters]
883 @item 
884 Examples are described by text
886 @example
887 and then shown this way.
888 @end example
890 @item 
891 Commands that are entered by the user are shown as preceded by a prompt string
892 comprising the @code{$} character followed by a space.
894 @item 
895 Full file names are shown with the '/' character
896 as the directory separator; e.g., @code{parent-dir/subdir/myfile.adb}.
897 If you are using GNAT on a Windows platform, please note that
898 the '\' character should be used instead.
899 @end itemize
901 @node Getting Started with GNAT,The GNAT Compilation Model,About This Guide,Top
902 @anchor{gnat_ugn/getting_started_with_gnat getting-started-with-gnat}@anchor{8}@anchor{gnat_ugn/getting_started_with_gnat doc}@anchor{2f}@anchor{gnat_ugn/getting_started_with_gnat id1}@anchor{30}
903 @chapter Getting Started with GNAT
906 This chapter describes how to use GNAT's command line interface to build
907 executable Ada programs.
908 On most platforms a visually oriented Integrated Development Environment
909 is also available, the GNAT Programming Studio (GPS).
910 GPS offers a graphical "look and feel", support for development in
911 other programming languages, comprehensive browsing features, and
912 many other capabilities.
913 For information on GPS please refer to
914 @cite{Using the GNAT Programming Studio}.
916 @menu
917 * Running GNAT:: 
918 * Running a Simple Ada Program:: 
919 * Running a Program with Multiple Units:: 
920 * Using the gnatmake Utility:: 
922 @end menu
924 @node Running GNAT,Running a Simple Ada Program,,Getting Started with GNAT
925 @anchor{gnat_ugn/getting_started_with_gnat running-gnat}@anchor{31}@anchor{gnat_ugn/getting_started_with_gnat id2}@anchor{32}
926 @section Running GNAT
929 Three steps are needed to create an executable file from an Ada source
930 file:
933 @itemize *
935 @item 
936 The source file(s) must be compiled.
938 @item 
939 The file(s) must be bound using the GNAT binder.
941 @item 
942 All appropriate object files must be linked to produce an executable.
943 @end itemize
945 All three steps are most commonly handled by using the @code{gnatmake}
946 utility program that, given the name of the main program, automatically
947 performs the necessary compilation, binding and linking steps.
949 @node Running a Simple Ada Program,Running a Program with Multiple Units,Running GNAT,Getting Started with GNAT
950 @anchor{gnat_ugn/getting_started_with_gnat running-a-simple-ada-program}@anchor{33}@anchor{gnat_ugn/getting_started_with_gnat id3}@anchor{34}
951 @section Running a Simple Ada Program
954 Any text editor may be used to prepare an Ada program.
955 (If Emacs is used, the optional Ada mode may be helpful in laying out the
956 program.)
957 The program text is a normal text file. We will assume in our initial
958 example that you have used your editor to prepare the following
959 standard format text file:
961 @example
962 with Ada.Text_IO; use Ada.Text_IO;
963 procedure Hello is
964 begin
965    Put_Line ("Hello WORLD!");
966 end Hello;
967 @end example
969 This file should be named @code{hello.adb}.
970 With the normal default file naming conventions, GNAT requires
971 that each file
972 contain a single compilation unit whose file name is the
973 unit name,
974 with periods replaced by hyphens; the
975 extension is @code{ads} for a
976 spec and @code{adb} for a body.
977 You can override this default file naming convention by use of the
978 special pragma @code{Source_File_Name} (for further information please
979 see @ref{35,,Using Other File Names}).
980 Alternatively, if you want to rename your files according to this default
981 convention, which is probably more convenient if you will be using GNAT
982 for all your compilations, then the @code{gnatchop} utility
983 can be used to generate correctly-named source files
984 (see @ref{36,,Renaming Files with gnatchop}).
986 You can compile the program using the following command (@code{$} is used
987 as the command prompt in the examples in this document):
989 @example
990 $ gcc -c hello.adb
991 @end example
993 @code{gcc} is the command used to run the compiler. This compiler is
994 capable of compiling programs in several languages, including Ada and
995 C. It assumes that you have given it an Ada program if the file extension is
996 either @code{.ads} or @code{.adb}, and it will then call
997 the GNAT compiler to compile the specified file.
999 The @code{-c} switch is required. It tells @code{gcc} to only do a
1000 compilation. (For C programs, @code{gcc} can also do linking, but this
1001 capability is not used directly for Ada programs, so the @code{-c}
1002 switch must always be present.)
1004 This compile command generates a file
1005 @code{hello.o}, which is the object
1006 file corresponding to your Ada program. It also generates
1007 an 'Ada Library Information' file @code{hello.ali},
1008 which contains additional information used to check
1009 that an Ada program is consistent.
1010 To build an executable file,
1011 use @code{gnatbind} to bind the program
1012 and @code{gnatlink} to link it. The
1013 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1014 @code{ALI} file, but the default extension of @code{.ali} can
1015 be omitted. This means that in the most common case, the argument
1016 is simply the name of the main program:
1018 @example
1019 $ gnatbind hello
1020 $ gnatlink hello
1021 @end example
1023 A simpler method of carrying out these steps is to use @code{gnatmake},
1024 a master program that invokes all the required
1025 compilation, binding and linking tools in the correct order. In particular,
1026 @code{gnatmake} automatically recompiles any sources that have been
1027 modified since they were last compiled, or sources that depend
1028 on such modified sources, so that 'version skew' is avoided.
1030 @geindex Version skew (avoided by `@w{`}gnatmake`@w{`})
1032 @example
1033 $ gnatmake hello.adb
1034 @end example
1036 The result is an executable program called @code{hello}, which can be
1037 run by entering:
1039 @example
1040 $ hello
1041 @end example
1043 assuming that the current directory is on the search path
1044 for executable programs.
1046 and, if all has gone well, you will see:
1048 @example
1049 Hello WORLD!
1050 @end example
1052 appear in response to this command.
1054 @node Running a Program with Multiple Units,Using the gnatmake Utility,Running a Simple Ada Program,Getting Started with GNAT
1055 @anchor{gnat_ugn/getting_started_with_gnat id4}@anchor{37}@anchor{gnat_ugn/getting_started_with_gnat running-a-program-with-multiple-units}@anchor{38}
1056 @section Running a Program with Multiple Units
1059 Consider a slightly more complicated example that has three files: a
1060 main program, and the spec and body of a package:
1062 @example
1063 package Greetings is
1064    procedure Hello;
1065    procedure Goodbye;
1066 end Greetings;
1068 with Ada.Text_IO; use Ada.Text_IO;
1069 package body Greetings is
1070    procedure Hello is
1071    begin
1072       Put_Line ("Hello WORLD!");
1073    end Hello;
1075    procedure Goodbye is
1076    begin
1077       Put_Line ("Goodbye WORLD!");
1078    end Goodbye;
1079 end Greetings;
1081 with Greetings;
1082 procedure Gmain is
1083 begin
1084    Greetings.Hello;
1085    Greetings.Goodbye;
1086 end Gmain;
1087 @end example
1089 Following the one-unit-per-file rule, place this program in the
1090 following three separate files:
1093 @table @asis
1095 @item @emph{greetings.ads}
1097 spec of package @code{Greetings}
1099 @item @emph{greetings.adb}
1101 body of package @code{Greetings}
1103 @item @emph{gmain.adb}
1105 body of main program
1106 @end table
1108 To build an executable version of
1109 this program, we could use four separate steps to compile, bind, and link
1110 the program, as follows:
1112 @example
1113 $ gcc -c gmain.adb
1114 $ gcc -c greetings.adb
1115 $ gnatbind gmain
1116 $ gnatlink gmain
1117 @end example
1119 Note that there is no required order of compilation when using GNAT.
1120 In particular it is perfectly fine to compile the main program first.
1121 Also, it is not necessary to compile package specs in the case where
1122 there is an accompanying body; you only need to compile the body. If you want
1123 to submit these files to the compiler for semantic checking and not code
1124 generation, then use the @code{-gnatc} switch:
1126 @example
1127 $ gcc -c greetings.ads -gnatc
1128 @end example
1130 Although the compilation can be done in separate steps as in the
1131 above example, in practice it is almost always more convenient
1132 to use the @code{gnatmake} tool. All you need to know in this case
1133 is the name of the main program's source file. The effect of the above four
1134 commands can be achieved with a single one:
1136 @example
1137 $ gnatmake gmain.adb
1138 @end example
1140 In the next section we discuss the advantages of using @code{gnatmake} in
1141 more detail.
1143 @node Using the gnatmake Utility,,Running a Program with Multiple Units,Getting Started with GNAT
1144 @anchor{gnat_ugn/getting_started_with_gnat using-the-gnatmake-utility}@anchor{39}@anchor{gnat_ugn/getting_started_with_gnat id5}@anchor{3a}
1145 @section Using the @code{gnatmake} Utility
1148 If you work on a program by compiling single components at a time using
1149 @code{gcc}, you typically keep track of the units you modify. In order to
1150 build a consistent system, you compile not only these units, but also any
1151 units that depend on the units you have modified.
1152 For example, in the preceding case,
1153 if you edit @code{gmain.adb}, you only need to recompile that file. But if
1154 you edit @code{greetings.ads}, you must recompile both
1155 @code{greetings.adb} and @code{gmain.adb}, because both files contain
1156 units that depend on @code{greetings.ads}.
1158 @code{gnatbind} will warn you if you forget one of these compilation
1159 steps, so that it is impossible to generate an inconsistent program as a
1160 result of forgetting to do a compilation. Nevertheless it is tedious and
1161 error-prone to keep track of dependencies among units.
1162 One approach to handle the dependency-bookkeeping is to use a
1163 makefile. However, makefiles present maintenance problems of their own:
1164 if the dependencies change as you change the program, you must make
1165 sure that the makefile is kept up-to-date manually, which is also an
1166 error-prone process.
1168 The @code{gnatmake} utility takes care of these details automatically.
1169 Invoke it using either one of the following forms:
1171 @example
1172 $ gnatmake gmain.adb
1173 $ gnatmake gmain
1174 @end example
1176 The argument is the name of the file containing the main program;
1177 you may omit the extension. @code{gnatmake}
1178 examines the environment, automatically recompiles any files that need
1179 recompiling, and binds and links the resulting set of object files,
1180 generating the executable file, @code{gmain}.
1181 In a large program, it
1182 can be extremely helpful to use @code{gnatmake}, because working out by hand
1183 what needs to be recompiled can be difficult.
1185 Note that @code{gnatmake} takes into account all the Ada rules that
1186 establish dependencies among units. These include dependencies that result
1187 from inlining subprogram bodies, and from
1188 generic instantiation. Unlike some other
1189 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1190 found by the compiler on a previous compilation, which may possibly
1191 be wrong when sources change. @code{gnatmake} determines the exact set of
1192 dependencies from scratch each time it is run.
1194 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
1196 @node The GNAT Compilation Model,Building Executable Programs with GNAT,Getting Started with GNAT,Top
1197 @anchor{gnat_ugn/the_gnat_compilation_model doc}@anchor{3b}@anchor{gnat_ugn/the_gnat_compilation_model the-gnat-compilation-model}@anchor{9}@anchor{gnat_ugn/the_gnat_compilation_model id1}@anchor{3c}
1198 @chapter The GNAT Compilation Model
1201 @geindex GNAT compilation model
1203 @geindex Compilation model
1205 This chapter describes the compilation model used by GNAT. Although
1206 similar to that used by other languages such as C and C++, this model
1207 is substantially different from the traditional Ada compilation models,
1208 which are based on a centralized program library. The chapter covers
1209 the following material:
1212 @itemize *
1214 @item 
1215 Topics related to source file makeup and naming
1218 @itemize *
1220 @item 
1221 @ref{3d,,Source Representation}
1223 @item 
1224 @ref{3e,,Foreign Language Representation}
1226 @item 
1227 @ref{3f,,File Naming Topics and Utilities}
1228 @end itemize
1230 @item 
1231 @ref{14,,Configuration Pragmas}
1233 @item 
1234 @ref{40,,Generating Object Files}
1236 @item 
1237 @ref{41,,Source Dependencies}
1239 @item 
1240 @ref{42,,The Ada Library Information Files}
1242 @item 
1243 @ref{43,,Binding an Ada Program}
1245 @item 
1246 @ref{15,,GNAT and Libraries}
1248 @item 
1249 @ref{16,,Conditional Compilation}
1251 @item 
1252 @ref{44,,Mixed Language Programming}
1254 @item 
1255 @ref{45,,GNAT and Other Compilation Models}
1257 @item 
1258 @ref{1a,,Using GNAT Files with External Tools}
1259 @end itemize
1261 @menu
1262 * Source Representation:: 
1263 * Foreign Language Representation:: 
1264 * File Naming Topics and Utilities:: 
1265 * Configuration Pragmas:: 
1266 * Generating Object Files:: 
1267 * Source Dependencies:: 
1268 * The Ada Library Information Files:: 
1269 * Binding an Ada Program:: 
1270 * GNAT and Libraries:: 
1271 * Conditional Compilation:: 
1272 * Mixed Language Programming:: 
1273 * GNAT and Other Compilation Models:: 
1274 * Using GNAT Files with External Tools:: 
1276 @end menu
1278 @node Source Representation,Foreign Language Representation,,The GNAT Compilation Model
1279 @anchor{gnat_ugn/the_gnat_compilation_model source-representation}@anchor{3d}@anchor{gnat_ugn/the_gnat_compilation_model id2}@anchor{46}
1280 @section Source Representation
1283 @geindex Latin-1
1285 @geindex VT
1286 @geindex HT
1287 @geindex CR
1288 @geindex LF
1289 @geindex FF
1291 Ada source programs are represented in standard text files, using
1292 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1293 7-bit ASCII set, plus additional characters used for
1294 representing foreign languages (see @ref{3e,,Foreign Language Representation}
1295 for support of non-USA character sets). The format effector characters
1296 are represented using their standard ASCII encodings, as follows:
1298 @quotation
1301 @multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxx} 
1302 @item
1304 Character
1306 @tab
1308 Effect
1310 @tab
1312 Code
1314 @item
1316 @code{VT}
1318 @tab
1320 Vertical tab
1322 @tab
1324 @code{16#0B#}
1326 @item
1328 @code{HT}
1330 @tab
1332 Horizontal tab
1334 @tab
1336 @code{16#09#}
1338 @item
1340 @code{CR}
1342 @tab
1344 Carriage return
1346 @tab
1348 @code{16#0D#}
1350 @item
1352 @code{LF}
1354 @tab
1356 Line feed
1358 @tab
1360 @code{16#0A#}
1362 @item
1364 @code{FF}
1366 @tab
1368 Form feed
1370 @tab
1372 @code{16#0C#}
1374 @end multitable
1376 @end quotation
1378 Source files are in standard text file format. In addition, GNAT will
1379 recognize a wide variety of stream formats, in which the end of
1380 physical lines is marked by any of the following sequences:
1381 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1382 in accommodating files that are imported from other operating systems.
1384 @geindex End of source file; Source file@comma{} end
1386 @geindex SUB (control character)
1388 The end of a source file is normally represented by the physical end of
1389 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1390 recognized as signalling the end of the source file. Again, this is
1391 provided for compatibility with other operating systems where this
1392 code is used to represent the end of file.
1394 @geindex spec (definition)
1395 @geindex compilation (definition)
1397 Each file contains a single Ada compilation unit, including any pragmas
1398 associated with the unit. For example, this means you must place a
1399 package declaration (a package @emph{spec}) and the corresponding body in
1400 separate files. An Ada @emph{compilation} (which is a sequence of
1401 compilation units) is represented using a sequence of files. Similarly,
1402 you will place each subunit or child unit in a separate file.
1404 @node Foreign Language Representation,File Naming Topics and Utilities,Source Representation,The GNAT Compilation Model
1405 @anchor{gnat_ugn/the_gnat_compilation_model foreign-language-representation}@anchor{3e}@anchor{gnat_ugn/the_gnat_compilation_model id3}@anchor{47}
1406 @section Foreign Language Representation
1409 GNAT supports the standard character sets defined in Ada as well as
1410 several other non-standard character sets for use in localized versions
1411 of the compiler (@ref{48,,Character Set Control}).
1413 @menu
1414 * Latin-1:: 
1415 * Other 8-Bit Codes:: 
1416 * Wide_Character Encodings:: 
1417 * Wide_Wide_Character Encodings:: 
1419 @end menu
1421 @node Latin-1,Other 8-Bit Codes,,Foreign Language Representation
1422 @anchor{gnat_ugn/the_gnat_compilation_model id4}@anchor{49}@anchor{gnat_ugn/the_gnat_compilation_model latin-1}@anchor{4a}
1423 @subsection Latin-1
1426 @geindex Latin-1
1428 The basic character set is Latin-1. This character set is defined by ISO
1429 standard 8859, part 1. The lower half (character codes @code{16#00#}
1430 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper
1431 half is used to represent additional characters. These include extended letters
1432 used by European languages, such as French accents, the vowels with umlauts
1433 used in German, and the extra letter A-ring used in Swedish.
1435 @geindex Ada.Characters.Latin_1
1437 For a complete list of Latin-1 codes and their encodings, see the source
1438 file of library unit @code{Ada.Characters.Latin_1} in file
1439 @code{a-chlat1.ads}.
1440 You may use any of these extended characters freely in character or
1441 string literals. In addition, the extended characters that represent
1442 letters can be used in identifiers.
1444 @node Other 8-Bit Codes,Wide_Character Encodings,Latin-1,Foreign Language Representation
1445 @anchor{gnat_ugn/the_gnat_compilation_model other-8-bit-codes}@anchor{4b}@anchor{gnat_ugn/the_gnat_compilation_model id5}@anchor{4c}
1446 @subsection Other 8-Bit Codes
1449 GNAT also supports several other 8-bit coding schemes:
1451 @geindex Latin-2
1453 @geindex ISO 8859-2
1456 @table @asis
1458 @item @emph{ISO 8859-2 (Latin-2)}
1460 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1461 equivalence.
1462 @end table
1464 @geindex Latin-3
1466 @geindex ISO 8859-3
1469 @table @asis
1471 @item @emph{ISO 8859-3 (Latin-3)}
1473 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1474 equivalence.
1475 @end table
1477 @geindex Latin-4
1479 @geindex ISO 8859-4
1482 @table @asis
1484 @item @emph{ISO 8859-4 (Latin-4)}
1486 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1487 equivalence.
1488 @end table
1490 @geindex ISO 8859-5
1492 @geindex Cyrillic
1495 @table @asis
1497 @item @emph{ISO 8859-5 (Cyrillic)}
1499 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1500 lowercase equivalence.
1501 @end table
1503 @geindex ISO 8859-15
1505 @geindex Latin-9
1508 @table @asis
1510 @item @emph{ISO 8859-15 (Latin-9)}
1512 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1513 lowercase equivalence
1514 @end table
1516 @geindex code page 437 (IBM PC)
1519 @table @asis
1521 @item @emph{IBM PC (code page 437)}
1523 This code page is the normal default for PCs in the U.S. It corresponds
1524 to the original IBM PC character set. This set has some, but not all, of
1525 the extended Latin-1 letters, but these letters do not have the same
1526 encoding as Latin-1. In this mode, these letters are allowed in
1527 identifiers with uppercase and lowercase equivalence.
1528 @end table
1530 @geindex code page 850 (IBM PC)
1533 @table @asis
1535 @item @emph{IBM PC (code page 850)}
1537 This code page is a modification of 437 extended to include all the
1538 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1539 mode, all these letters are allowed in identifiers with uppercase and
1540 lowercase equivalence.
1542 @item @emph{Full Upper 8-bit}
1544 Any character in the range 80-FF allowed in identifiers, and all are
1545 considered distinct. In other words, there are no uppercase and lowercase
1546 equivalences in this range. This is useful in conjunction with
1547 certain encoding schemes used for some foreign character sets (e.g.,
1548 the typical method of representing Chinese characters on the PC).
1550 @item @emph{No Upper-Half}
1552 No upper-half characters in the range 80-FF are allowed in identifiers.
1553 This gives Ada 83 compatibility for identifier names.
1554 @end table
1556 For precise data on the encodings permitted, and the uppercase and lowercase
1557 equivalences that are recognized, see the file @code{csets.adb} in
1558 the GNAT compiler sources. You will need to obtain a full source release
1559 of GNAT to obtain this file.
1561 @node Wide_Character Encodings,Wide_Wide_Character Encodings,Other 8-Bit Codes,Foreign Language Representation
1562 @anchor{gnat_ugn/the_gnat_compilation_model id6}@anchor{4d}@anchor{gnat_ugn/the_gnat_compilation_model wide-character-encodings}@anchor{4e}
1563 @subsection Wide_Character Encodings
1566 GNAT allows wide character codes to appear in character and string
1567 literals, and also optionally in identifiers, by means of the following
1568 possible encoding schemes:
1571 @table @asis
1573 @item @emph{Hex Coding}
1575 In this encoding, a wide character is represented by the following five
1576 character sequence:
1578 @example
1579 ESC a b c d
1580 @end example
1582 where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1583 characters (using uppercase letters) of the wide character code. For
1584 example, ESC A345 is used to represent the wide character with code
1585 @code{16#A345#}.
1586 This scheme is compatible with use of the full Wide_Character set.
1588 @item @emph{Upper-Half Coding}
1590 @geindex Upper-Half Coding
1592 The wide character with encoding @code{16#abcd#} where the upper bit is on
1593 (in other words, 'a' is in the range 8-F) is represented as two bytes,
1594 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1595 character, but is not required to be in the upper half. This method can
1596 be also used for shift-JIS or EUC, where the internal coding matches the
1597 external coding.
1599 @item @emph{Shift JIS Coding}
1601 @geindex Shift JIS Coding
1603 A wide character is represented by a two-character sequence,
1604 @code{16#ab#} and
1605 @code{16#cd#}, with the restrictions described for upper-half encoding as
1606 described above. The internal character code is the corresponding JIS
1607 character according to the standard algorithm for Shift-JIS
1608 conversion. Only characters defined in the JIS code set table can be
1609 used with this encoding method.
1611 @item @emph{EUC Coding}
1613 @geindex EUC Coding
1615 A wide character is represented by a two-character sequence
1616 @code{16#ab#} and
1617 @code{16#cd#}, with both characters being in the upper half. The internal
1618 character code is the corresponding JIS character according to the EUC
1619 encoding algorithm. Only characters defined in the JIS code set table
1620 can be used with this encoding method.
1622 @item @emph{UTF-8 Coding}
1624 A wide character is represented using
1625 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1626 10646-1/Am.2. Depending on the character value, the representation
1627 is a one, two, or three byte sequence:
1629 @example
1630 16#0000#-16#007f#: 2#0xxxxxxx#
1631 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1632 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1633 @end example
1635 where the @code{xxx} bits correspond to the left-padded bits of the
1636 16-bit character value. Note that all lower half ASCII characters
1637 are represented as ASCII bytes and all upper half characters and
1638 other wide characters are represented as sequences of upper-half
1639 (The full UTF-8 scheme allows for encoding 31-bit characters as
1640 6-byte sequences, and in the following section on wide wide
1641 characters, the use of these sequences is documented).
1643 @item @emph{Brackets Coding}
1645 In this encoding, a wide character is represented by the following eight
1646 character sequence:
1648 @example
1649 [ " a b c d " ]
1650 @end example
1652 where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1653 characters (using uppercase letters) of the wide character code. For
1654 example, ['A345'] is used to represent the wide character with code
1655 @code{16#A345#}. It is also possible (though not required) to use the
1656 Brackets coding for upper half characters. For example, the code
1657 @code{16#A3#} can be represented as @code{['A3']}.
1659 This scheme is compatible with use of the full Wide_Character set,
1660 and is also the method used for wide character encoding in some standard
1661 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1662 @end table
1664 @cartouche
1665 @quotation Note 
1666 Some of these coding schemes do not permit the full use of the
1667 Ada character set. For example, neither Shift JIS nor EUC allow the
1668 use of the upper half of the Latin-1 set.
1669 @end quotation
1670 @end cartouche
1672 @node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1673 @anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{4f}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{50}
1674 @subsection Wide_Wide_Character Encodings
1677 GNAT allows wide wide character codes to appear in character and string
1678 literals, and also optionally in identifiers, by means of the following
1679 possible encoding schemes:
1682 @table @asis
1684 @item @emph{UTF-8 Coding}
1686 A wide character is represented using
1687 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1688 10646-1/Am.2. Depending on the character value, the representation
1689 of character codes with values greater than 16#FFFF# is a
1690 is a four, five, or six byte sequence:
1692 @example
1693 16#01_0000#-16#10_FFFF#:     11110xxx 10xxxxxx 10xxxxxx
1694                              10xxxxxx
1695 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1696                              10xxxxxx 10xxxxxx
1697 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1698                              10xxxxxx 10xxxxxx 10xxxxxx
1699 @end example
1701 where the @code{xxx} bits correspond to the left-padded bits of the
1702 32-bit character value.
1704 @item @emph{Brackets Coding}
1706 In this encoding, a wide wide character is represented by the following ten or
1707 twelve byte character sequence:
1709 @example
1710 [ " a b c d e f " ]
1711 [ " a b c d e f g h " ]
1712 @end example
1714 where @code{a-h} are the six or eight hexadecimal
1715 characters (using uppercase letters) of the wide wide character code. For
1716 example, ["1F4567"] is used to represent the wide wide character with code
1717 @code{16#001F_4567#}.
1719 This scheme is compatible with use of the full Wide_Wide_Character set,
1720 and is also the method used for wide wide character encoding in some standard
1721 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1722 @end table
1724 @node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1725 @anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{3f}
1726 @section File Naming Topics and Utilities
1729 GNAT has a default file naming scheme and also provides the user with
1730 a high degree of control over how the names and extensions of the
1731 source files correspond to the Ada compilation units that they contain.
1733 @menu
1734 * File Naming Rules:: 
1735 * Using Other File Names:: 
1736 * Alternative File Naming Schemes:: 
1737 * Handling Arbitrary File Naming Conventions with gnatname:: 
1738 * File Name Krunching with gnatkr:: 
1739 * Renaming Files with gnatchop:: 
1741 @end menu
1743 @node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1744 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{52}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{53}
1745 @subsection File Naming Rules
1748 The default file name is determined by the name of the unit that the
1749 file contains. The name is formed by taking the full expanded name of
1750 the unit and replacing the separating dots with hyphens and using
1751 lowercase for all letters.
1753 An exception arises if the file name generated by the above rules starts
1754 with one of the characters
1755 @code{a}, @code{g}, @code{i}, or @code{s}, and the second character is a
1756 minus. In this case, the character tilde is used in place
1757 of the minus. The reason for this special rule is to avoid clashes with
1758 the standard names for child units of the packages System, Ada,
1759 Interfaces, and GNAT, which use the prefixes
1760 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
1761 respectively.
1763 The file extension is @code{.ads} for a spec and
1764 @code{.adb} for a body. The following table shows some
1765 examples of these rules.
1767 @quotation
1770 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
1771 @item
1773 Source File
1775 @tab
1777 Ada Compilation Unit
1779 @item
1781 @code{main.ads}
1783 @tab
1785 Main (spec)
1787 @item
1789 @code{main.adb}
1791 @tab
1793 Main (body)
1795 @item
1797 @code{arith_functions.ads}
1799 @tab
1801 Arith_Functions (package spec)
1803 @item
1805 @code{arith_functions.adb}
1807 @tab
1809 Arith_Functions (package body)
1811 @item
1813 @code{func-spec.ads}
1815 @tab
1817 Func.Spec (child package spec)
1819 @item
1821 @code{func-spec.adb}
1823 @tab
1825 Func.Spec (child package body)
1827 @item
1829 @code{main-sub.adb}
1831 @tab
1833 Sub (subunit of Main)
1835 @item
1837 @code{a~bad.adb}
1839 @tab
1841 A.Bad (child package body)
1843 @end multitable
1845 @end quotation
1847 Following these rules can result in excessively long
1848 file names if corresponding
1849 unit names are long (for example, if child units or subunits are
1850 heavily nested). An option is available to shorten such long file names
1851 (called file name 'krunching'). This may be particularly useful when
1852 programs being developed with GNAT are to be used on operating systems
1853 with limited file name lengths. @ref{54,,Using gnatkr}.
1855 Of course, no file shortening algorithm can guarantee uniqueness over
1856 all possible unit names; if file name krunching is used, it is your
1857 responsibility to ensure no name clashes occur. Alternatively you
1858 can specify the exact file names that you want used, as described
1859 in the next section. Finally, if your Ada programs are migrating from a
1860 compiler with a different naming convention, you can use the gnatchop
1861 utility to produce source files that follow the GNAT naming conventions.
1862 (For details see @ref{36,,Renaming Files with gnatchop}.)
1864 Note: in the case of Windows or Mac OS operating systems, case is not
1865 significant. So for example on Windows if the canonical name is
1866 @code{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1867 However, case is significant for other operating systems, so for example,
1868 if you want to use other than canonically cased file names on a Unix system,
1869 you need to follow the procedures described in the next section.
1871 @node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1872 @anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{55}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{35}
1873 @subsection Using Other File Names
1876 @geindex File names
1878 In the previous section, we have described the default rules used by
1879 GNAT to determine the file name in which a given unit resides. It is
1880 often convenient to follow these default rules, and if you follow them,
1881 the compiler knows without being explicitly told where to find all
1882 the files it needs.
1884 @geindex Source_File_Name pragma
1886 However, in some cases, particularly when a program is imported from
1887 another Ada compiler environment, it may be more convenient for the
1888 programmer to specify which file names contain which units. GNAT allows
1889 arbitrary file names to be used by means of the Source_File_Name pragma.
1890 The form of this pragma is as shown in the following examples:
1892 @example
1893 pragma Source_File_Name (My_Utilities.Stacks,
1894   Spec_File_Name => "myutilst_a.ada");
1895 pragma Source_File_name (My_Utilities.Stacks,
1896   Body_File_Name => "myutilst.ada");
1897 @end example
1899 As shown in this example, the first argument for the pragma is the unit
1900 name (in this example a child unit). The second argument has the form
1901 of a named association. The identifier
1902 indicates whether the file name is for a spec or a body;
1903 the file name itself is given by a string literal.
1905 The source file name pragma is a configuration pragma, which means that
1906 normally it will be placed in the @code{gnat.adc}
1907 file used to hold configuration
1908 pragmas that apply to a complete compilation environment.
1909 For more details on how the @code{gnat.adc} file is created and used
1910 see @ref{56,,Handling of Configuration Pragmas}.
1912 @geindex gnat.adc
1914 GNAT allows completely arbitrary file names to be specified using the
1915 source file name pragma. However, if the file name specified has an
1916 extension other than @code{.ads} or @code{.adb} it is necessary to use
1917 a special syntax when compiling the file. The name in this case must be
1918 preceded by the special sequence @code{-x} followed by a space and the name
1919 of the language, here @code{ada}, as in:
1921 @example
1922 $ gcc -c -x ada peculiar_file_name.sim
1923 @end example
1925 @code{gnatmake} handles non-standard file names in the usual manner (the
1926 non-standard file name for the main program is simply used as the
1927 argument to gnatmake). Note that if the extension is also non-standard,
1928 then it must be included in the @code{gnatmake} command, it may not
1929 be omitted.
1931 @node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
1932 @anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{57}@anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{58}
1933 @subsection Alternative File Naming Schemes
1936 @geindex File naming schemes
1937 @geindex alternative
1939 @geindex File names
1941 The previous section described the use of the @code{Source_File_Name}
1942 pragma to allow arbitrary names to be assigned to individual source files.
1943 However, this approach requires one pragma for each file, and especially in
1944 large systems can result in very long @code{gnat.adc} files, and also create
1945 a maintenance problem.
1947 @geindex Source_File_Name pragma
1949 GNAT also provides a facility for specifying systematic file naming schemes
1950 other than the standard default naming scheme previously described. An
1951 alternative scheme for naming is specified by the use of
1952 @code{Source_File_Name} pragmas having the following format:
1954 @example
1955 pragma Source_File_Name (
1956    Spec_File_Name  => FILE_NAME_PATTERN
1957  [ , Casing          => CASING_SPEC]
1958  [ , Dot_Replacement => STRING_LITERAL ] );
1960 pragma Source_File_Name (
1961    Body_File_Name  => FILE_NAME_PATTERN
1962  [ , Casing          => CASING_SPEC ]
1963  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1965 pragma Source_File_Name (
1966    Subunit_File_Name  => FILE_NAME_PATTERN
1967  [ , Casing          => CASING_SPEC ]
1968  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1970 FILE_NAME_PATTERN ::= STRING_LITERAL
1971 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1972 @end example
1974 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1975 It contains a single asterisk character, and the unit name is substituted
1976 systematically for this asterisk. The optional parameter
1977 @code{Casing} indicates
1978 whether the unit name is to be all upper-case letters, all lower-case letters,
1979 or mixed-case. If no
1980 @code{Casing} parameter is used, then the default is all
1981 lower-case.
1983 The optional @code{Dot_Replacement} string is used to replace any periods
1984 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1985 argument is used then separating dots appear unchanged in the resulting
1986 file name.
1987 Although the above syntax indicates that the
1988 @code{Casing} argument must appear
1989 before the @code{Dot_Replacement} argument, but it
1990 is also permissible to write these arguments in the opposite order.
1992 As indicated, it is possible to specify different naming schemes for
1993 bodies, specs, and subunits. Quite often the rule for subunits is the
1994 same as the rule for bodies, in which case, there is no need to give
1995 a separate @code{Subunit_File_Name} rule, and in this case the
1996 @code{Body_File_name} rule is used for subunits as well.
1998 The separate rule for subunits can also be used to implement the rather
1999 unusual case of a compilation environment (e.g., a single directory) which
2000 contains a subunit and a child unit with the same unit name. Although
2001 both units cannot appear in the same partition, the Ada Reference Manual
2002 allows (but does not require) the possibility of the two units coexisting
2003 in the same environment.
2005 The file name translation works in the following steps:
2008 @itemize *
2010 @item 
2011 If there is a specific @code{Source_File_Name} pragma for the given unit,
2012 then this is always used, and any general pattern rules are ignored.
2014 @item 
2015 If there is a pattern type @code{Source_File_Name} pragma that applies to
2016 the unit, then the resulting file name will be used if the file exists. If
2017 more than one pattern matches, the latest one will be tried first, and the
2018 first attempt resulting in a reference to a file that exists will be used.
2020 @item 
2021 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2022 for which the corresponding file exists, then the standard GNAT default
2023 naming rules are used.
2024 @end itemize
2026 As an example of the use of this mechanism, consider a commonly used scheme
2027 in which file names are all lower case, with separating periods copied
2028 unchanged to the resulting file name, and specs end with @code{.1.ada}, and
2029 bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
2030 two pragmas appear:
2032 @example
2033 pragma Source_File_Name
2034   (Spec_File_Name => ".1.ada");
2035 pragma Source_File_Name
2036   (Body_File_Name => ".2.ada");
2037 @end example
2039 The default GNAT scheme is actually implemented by providing the following
2040 default pragmas internally:
2042 @example
2043 pragma Source_File_Name
2044   (Spec_File_Name => ".ads", Dot_Replacement => "-");
2045 pragma Source_File_Name
2046   (Body_File_Name => ".adb", Dot_Replacement => "-");
2047 @end example
2049 Our final example implements a scheme typically used with one of the
2050 Ada 83 compilers, where the separator character for subunits was '__'
2051 (two underscores), specs were identified by adding @code{_.ADA}, bodies
2052 by adding @code{.ADA}, and subunits by
2053 adding @code{.SEP}. All file names were
2054 upper case. Child units were not present of course since this was an
2055 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2056 the same double underscore separator for child units.
2058 @example
2059 pragma Source_File_Name
2060   (Spec_File_Name => "_.ADA",
2061    Dot_Replacement => "__",
2062    Casing = Uppercase);
2063 pragma Source_File_Name
2064   (Body_File_Name => ".ADA",
2065    Dot_Replacement => "__",
2066    Casing = Uppercase);
2067 pragma Source_File_Name
2068   (Subunit_File_Name => ".SEP",
2069    Dot_Replacement => "__",
2070    Casing = Uppercase);
2071 @end example
2073 @geindex gnatname
2075 @node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
2076 @anchor{gnat_ugn/the_gnat_compilation_model handling-arbitrary-file-naming-conventions-with-gnatname}@anchor{59}@anchor{gnat_ugn/the_gnat_compilation_model id12}@anchor{5a}
2077 @subsection Handling Arbitrary File Naming Conventions with @code{gnatname}
2080 @geindex File Naming Conventions
2082 @menu
2083 * Arbitrary File Naming Conventions:: 
2084 * Running gnatname:: 
2085 * Switches for gnatname:: 
2086 * Examples of gnatname Usage:: 
2088 @end menu
2090 @node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
2091 @anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{5b}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{5c}
2092 @subsubsection Arbitrary File Naming Conventions
2095 The GNAT compiler must be able to know the source file name of a compilation
2096 unit.  When using the standard GNAT default file naming conventions
2097 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
2098 does not need additional information.
2100 When the source file names do not follow the standard GNAT default file naming
2101 conventions, the GNAT compiler must be given additional information through
2102 a configuration pragmas file (@ref{14,,Configuration Pragmas})
2103 or a project file.
2104 When the non-standard file naming conventions are well-defined,
2105 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
2106 (@ref{58,,Alternative File Naming Schemes}) may be sufficient. However,
2107 if the file naming conventions are irregular or arbitrary, a number
2108 of pragma @code{Source_File_Name} for individual compilation units
2109 must be defined.
2110 To help maintain the correspondence between compilation unit names and
2111 source file names within the compiler,
2112 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
2113 set of files.
2115 @node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
2116 @anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{5d}@anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{5e}
2117 @subsubsection Running @code{gnatname}
2120 The usual form of the @code{gnatname} command is:
2122 @example
2123 $ gnatname [ switches ]  naming_pattern  [ naming_patterns ]
2124     [--and [ switches ]  naming_pattern  [ naming_patterns ]]
2125 @end example
2127 All of the arguments are optional. If invoked without any argument,
2128 @code{gnatname} will display its usage.
2130 When used with at least one naming pattern, @code{gnatname} will attempt to
2131 find all the compilation units in files that follow at least one of the
2132 naming patterns. To find these compilation units,
2133 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
2134 regular files.
2136 One or several Naming Patterns may be given as arguments to @code{gnatname}.
2137 Each Naming Pattern is enclosed between double quotes (or single
2138 quotes on Windows).
2139 A Naming Pattern is a regular expression similar to the wildcard patterns
2140 used in file names by the Unix shells or the DOS prompt.
2142 @code{gnatname} may be called with several sections of directories/patterns.
2143 Sections are separated by the switch @code{--and}. In each section, there must be
2144 at least one pattern. If no directory is specified in a section, the current
2145 directory (or the project directory if @code{-P} is used) is implied.
2146 The options other that the directory switches and the patterns apply globally
2147 even if they are in different sections.
2149 Examples of Naming Patterns are:
2151 @example
2152 "*.[12].ada"
2153 "*.ad[sb]*"
2154 "body_*"    "spec_*"
2155 @end example
2157 For a more complete description of the syntax of Naming Patterns,
2158 see the second kind of regular expressions described in @code{g-regexp.ads}
2159 (the 'Glob' regular expressions).
2161 When invoked without the switch @code{-P}, @code{gnatname} will create a
2162 configuration pragmas file @code{gnat.adc} in the current working directory,
2163 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
2164 unit.
2166 @node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
2167 @anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{5f}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{60}
2168 @subsubsection Switches for @code{gnatname}
2171 Switches for @code{gnatname} must precede any specified Naming Pattern.
2173 You may specify any of the following switches to @code{gnatname}:
2175 @geindex --version (gnatname)
2178 @table @asis
2180 @item @code{--version}
2182 Display Copyright and version, then exit disregarding all other options.
2183 @end table
2185 @geindex --help (gnatname)
2188 @table @asis
2190 @item @code{--help}
2192 If @code{--version} was not used, display usage, then exit disregarding
2193 all other options.
2195 @item @code{--subdirs=@emph{dir}}
2197 Real object, library or exec directories are subdirectories <dir> of the
2198 specified ones.
2200 @item @code{--no-backup}
2202 Do not create a backup copy of an existing project file.
2204 @item @code{--and}
2206 Start another section of directories/patterns.
2207 @end table
2209 @geindex -c (gnatname)
2212 @table @asis
2214 @item @code{-c@emph{filename}}
2216 Create a configuration pragmas file @code{filename} (instead of the default
2217 @code{gnat.adc}).
2218 There may be zero, one or more space between @code{-c} and
2219 @code{filename}.
2220 @code{filename} may include directory information. @code{filename} must be
2221 writable. There may be only one switch @code{-c}.
2222 When a switch @code{-c} is
2223 specified, no switch @code{-P} may be specified (see below).
2224 @end table
2226 @geindex -d (gnatname)
2229 @table @asis
2231 @item @code{-d@emph{dir}}
2233 Look for source files in directory @code{dir}. There may be zero, one or more
2234 spaces between @code{-d} and @code{dir}.
2235 @code{dir} may end with @code{/**}, that is it may be of the form
2236 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
2237 subdirectories, recursively, have to be searched for sources.
2238 When a switch @code{-d}
2239 is specified, the current working directory will not be searched for source
2240 files, unless it is explicitly specified with a @code{-d}
2241 or @code{-D} switch.
2242 Several switches @code{-d} may be specified.
2243 If @code{dir} is a relative path, it is relative to the directory of
2244 the configuration pragmas file specified with switch
2245 @code{-c},
2246 or to the directory of the project file specified with switch
2247 @code{-P} or,
2248 if neither switch @code{-c}
2249 nor switch @code{-P} are specified, it is relative to the
2250 current working directory. The directory
2251 specified with switch @code{-d} must exist and be readable.
2252 @end table
2254 @geindex -D (gnatname)
2257 @table @asis
2259 @item @code{-D@emph{filename}}
2261 Look for source files in all directories listed in text file @code{filename}.
2262 There may be zero, one or more spaces between @code{-D}
2263 and @code{filename}.
2264 @code{filename} must be an existing, readable text file.
2265 Each nonempty line in @code{filename} must be a directory.
2266 Specifying switch @code{-D} is equivalent to specifying as many
2267 switches @code{-d} as there are nonempty lines in
2268 @code{file}.
2270 @item @code{-eL}
2272 Follow symbolic links when processing project files.
2274 @geindex -f (gnatname)
2276 @item @code{-f@emph{pattern}}
2278 Foreign patterns. Using this switch, it is possible to add sources of languages
2279 other than Ada to the list of sources of a project file.
2280 It is only useful if a -P switch is used.
2281 For example,
2283 @example
2284 gnatname -Pprj -f"*.c" "*.ada"
2285 @end example
2287 will look for Ada units in all files with the @code{.ada} extension,
2288 and will add to the list of file for project @code{prj.gpr} the C files
2289 with extension @code{.c}.
2291 @geindex -h (gnatname)
2293 @item @code{-h}
2295 Output usage (help) information. The output is written to @code{stdout}.
2297 @geindex -P (gnatname)
2299 @item @code{-P@emph{proj}}
2301 Create or update project file @code{proj}. There may be zero, one or more space
2302 between @code{-P} and @code{proj}. @code{proj} may include directory
2303 information. @code{proj} must be writable.
2304 There may be only one switch @code{-P}.
2305 When a switch @code{-P} is specified,
2306 no switch @code{-c} may be specified.
2307 On all platforms, except on VMS, when @code{gnatname} is invoked for an
2308 existing project file <proj>.gpr, a backup copy of the project file is created
2309 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
2310 non negative number that makes this backup copy a new file.
2312 @geindex -v (gnatname)
2314 @item @code{-v}
2316 Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2317 This includes name of the file written, the name of the directories to search
2318 and, for each file in those directories whose name matches at least one of
2319 the Naming Patterns, an indication of whether the file contains a unit,
2320 and if so the name of the unit.
2321 @end table
2323 @geindex -v -v (gnatname)
2326 @table @asis
2328 @item @code{-v -v}
2330 Very Verbose mode. In addition to the output produced in verbose mode,
2331 for each file in the searched directories whose name matches none of
2332 the Naming Patterns, an indication is given that there is no match.
2334 @geindex -x (gnatname)
2336 @item @code{-x@emph{pattern}}
2338 Excluded patterns. Using this switch, it is possible to exclude some files
2339 that would match the name patterns. For example,
2341 @example
2342 gnatname -x "*_nt.ada" "*.ada"
2343 @end example
2345 will look for Ada units in all files with the @code{.ada} extension,
2346 except those whose names end with @code{_nt.ada}.
2347 @end table
2349 @node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2350 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{61}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{62}
2351 @subsubsection Examples of @code{gnatname} Usage
2354 @example
2355 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2356 @end example
2358 In this example, the directory @code{/home/me} must already exist
2359 and be writable. In addition, the directory
2360 @code{/home/me/sources} (specified by
2361 @code{-d sources}) must exist and be readable.
2363 Note the optional spaces after @code{-c} and @code{-d}.
2365 @example
2366 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
2367 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2368 @end example
2370 Note that several switches @code{-d} may be used,
2371 even in conjunction with one or several switches
2372 @code{-D}. Several Naming Patterns and one excluded pattern
2373 are used in this example.
2375 @node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2376 @anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{63}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{64}
2377 @subsection File Name Krunching with @code{gnatkr}
2380 @geindex gnatkr
2382 This section discusses the method used by the compiler to shorten
2383 the default file names chosen for Ada units so that they do not
2384 exceed the maximum length permitted. It also describes the
2385 @code{gnatkr} utility that can be used to determine the result of
2386 applying this shortening.
2388 @menu
2389 * About gnatkr:: 
2390 * Using gnatkr:: 
2391 * Krunching Method:: 
2392 * Examples of gnatkr Usage:: 
2394 @end menu
2396 @node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2397 @anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{66}
2398 @subsubsection About @code{gnatkr}
2401 The default file naming rule in GNAT
2402 is that the file name must be derived from
2403 the unit name. The exact default rule is as follows:
2406 @itemize *
2408 @item 
2409 Take the unit name and replace all dots by hyphens.
2411 @item 
2412 If such a replacement occurs in the
2413 second character position of a name, and the first character is
2414 @code{a}, @code{g}, @code{s}, or @code{i},
2415 then replace the dot by the character
2416 @code{~} (tilde)
2417 instead of a minus.
2419 The reason for this exception is to avoid clashes
2420 with the standard names for children of System, Ada, Interfaces,
2421 and GNAT, which use the prefixes
2422 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
2423 respectively.
2424 @end itemize
2426 The @code{-gnatk@emph{nn}}
2427 switch of the compiler activates a 'krunching'
2428 circuit that limits file names to nn characters (where nn is a decimal
2429 integer).
2431 The @code{gnatkr} utility can be used to determine the krunched name for
2432 a given file, when krunched to a specified maximum length.
2434 @node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2435 @anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{67}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{54}
2436 @subsubsection Using @code{gnatkr}
2439 The @code{gnatkr} command has the form:
2441 @example
2442 $ gnatkr name [ length ]
2443 @end example
2445 @code{name} is the uncrunched file name, derived from the name of the unit
2446 in the standard manner described in the previous section (i.e., in particular
2447 all dots are replaced by hyphens). The file name may or may not have an
2448 extension (defined as a suffix of the form period followed by arbitrary
2449 characters other than period). If an extension is present then it will
2450 be preserved in the output. For example, when krunching @code{hellofile.ads}
2451 to eight characters, the result will be hellofil.ads.
2453 Note: for compatibility with previous versions of @code{gnatkr} dots may
2454 appear in the name instead of hyphens, but the last dot will always be
2455 taken as the start of an extension. So if @code{gnatkr} is given an argument
2456 such as @code{Hello.World.adb} it will be treated exactly as if the first
2457 period had been a hyphen, and for example krunching to eight characters
2458 gives the result @code{hellworl.adb}.
2460 Note that the result is always all lower case.
2461 Characters of the other case are folded as required.
2463 @code{length} represents the length of the krunched name. The default
2464 when no argument is given is 8 characters. A length of zero stands for
2465 unlimited, in other words do not chop except for system files where the
2466 implied crunching length is always eight characters.
2468 The output is the krunched name. The output has an extension only if the
2469 original argument was a file name with an extension.
2471 @node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2472 @anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{68}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{69}
2473 @subsubsection Krunching Method
2476 The initial file name is determined by the name of the unit that the file
2477 contains. The name is formed by taking the full expanded name of the
2478 unit and replacing the separating dots with hyphens and
2479 using lowercase
2480 for all letters, except that a hyphen in the second character position is
2481 replaced by a tilde if the first character is
2482 @code{a}, @code{i}, @code{g}, or @code{s}.
2483 The extension is @code{.ads} for a
2484 spec and @code{.adb} for a body.
2485 Krunching does not affect the extension, but the file name is shortened to
2486 the specified length by following these rules:
2489 @itemize *
2491 @item 
2492 The name is divided into segments separated by hyphens, tildes or
2493 underscores and all hyphens, tildes, and underscores are
2494 eliminated. If this leaves the name short enough, we are done.
2496 @item 
2497 If the name is too long, the longest segment is located (left-most
2498 if there are two of equal length), and shortened by dropping
2499 its last character. This is repeated until the name is short enough.
2501 As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2502 to fit the name into 8 characters as required by some operating systems:
2504 @example
2505 our-strings-wide_fixed 22
2506 our strings wide fixed 19
2507 our string  wide fixed 18
2508 our strin   wide fixed 17
2509 our stri    wide fixed 16
2510 our stri    wide fixe  15
2511 our str     wide fixe  14
2512 our str     wid  fixe  13
2513 our str     wid  fix   12
2514 ou  str     wid  fix   11
2515 ou  st      wid  fix   10
2516 ou  st      wi   fix   9
2517 ou  st      wi   fi    8
2518 Final file name: oustwifi.adb
2519 @end example
2521 @item 
2522 The file names for all predefined units are always krunched to eight
2523 characters. The krunching of these predefined units uses the following
2524 special prefix replacements:
2527 @multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} 
2528 @item
2530 Prefix
2532 @tab
2534 Replacement
2536 @item
2538 @code{ada-}
2540 @tab
2542 @code{a-}
2544 @item
2546 @code{gnat-}
2548 @tab
2550 @code{g-}
2552 @item
2554 @code{interfac es-}
2556 @tab
2558 @code{i-}
2560 @item
2562 @code{system-}
2564 @tab
2566 @code{s-}
2568 @end multitable
2571 These system files have a hyphen in the second character position. That
2572 is why normal user files replace such a character with a
2573 tilde, to avoid confusion with system file names.
2575 As an example of this special rule, consider
2576 @code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2578 @example
2579 ada-strings-wide_fixed 22
2580 a-  strings wide fixed 18
2581 a-  string  wide fixed 17
2582 a-  strin   wide fixed 16
2583 a-  stri    wide fixed 15
2584 a-  stri    wide fixe  14
2585 a-  str     wide fixe  13
2586 a-  str     wid  fixe  12
2587 a-  str     wid  fix   11
2588 a-  st      wid  fix   10
2589 a-  st      wi   fix   9
2590 a-  st      wi   fi    8
2591 Final file name: a-stwifi.adb
2592 @end example
2593 @end itemize
2595 Of course no file shortening algorithm can guarantee uniqueness over all
2596 possible unit names, and if file name krunching is used then it is your
2597 responsibility to ensure that no name clashes occur. The utility
2598 program @code{gnatkr} is supplied for conveniently determining the
2599 krunched name of a file.
2601 @node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2602 @anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{6a}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{6b}
2603 @subsubsection Examples of @code{gnatkr} Usage
2606 @example
2607 $ gnatkr very_long_unit_name.ads      --> velounna.ads
2608 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
2609 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2610 $ gnatkr grandparent-parent-child     --> grparchi
2611 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2612 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2613 @end example
2615 @node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2616 @anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{36}
2617 @subsection Renaming Files with @code{gnatchop}
2620 @geindex gnatchop
2622 This section discusses how to handle files with multiple units by using
2623 the @code{gnatchop} utility. This utility is also useful in renaming
2624 files to meet the standard GNAT default file naming conventions.
2626 @menu
2627 * Handling Files with Multiple Units:: 
2628 * Operating gnatchop in Compilation Mode:: 
2629 * Command Line for gnatchop:: 
2630 * Switches for gnatchop:: 
2631 * Examples of gnatchop Usage:: 
2633 @end menu
2635 @node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2636 @anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{6d}@anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{6e}
2637 @subsubsection Handling Files with Multiple Units
2640 The basic compilation model of GNAT requires that a file submitted to the
2641 compiler have only one unit and there be a strict correspondence
2642 between the file name and the unit name.
2644 The @code{gnatchop} utility allows both of these rules to be relaxed,
2645 allowing GNAT to process files which contain multiple compilation units
2646 and files with arbitrary file names. @code{gnatchop}
2647 reads the specified file and generates one or more output files,
2648 containing one unit per file. The unit and the file name correspond,
2649 as required by GNAT.
2651 If you want to permanently restructure a set of 'foreign' files so that
2652 they match the GNAT rules, and do the remaining development using the
2653 GNAT structure, you can simply use @code{gnatchop} once, generate the
2654 new set of files and work with them from that point on.
2656 Alternatively, if you want to keep your files in the 'foreign' format,
2657 perhaps to maintain compatibility with some other Ada compilation
2658 system, you can set up a procedure where you use @code{gnatchop} each
2659 time you compile, regarding the source files that it writes as temporary
2660 files that you throw away.
2662 Note that if your file containing multiple units starts with a byte order
2663 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2664 will each start with a copy of this BOM, meaning that they can be compiled
2665 automatically in UTF-8 mode without needing to specify an explicit encoding.
2667 @node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2668 @anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{6f}@anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{70}
2669 @subsubsection Operating gnatchop in Compilation Mode
2672 The basic function of @code{gnatchop} is to take a file with multiple units
2673 and split it into separate files. The boundary between files is reasonably
2674 clear, except for the issue of comments and pragmas. In default mode, the
2675 rule is that any pragmas between units belong to the previous unit, except
2676 that configuration pragmas always belong to the following unit. Any comments
2677 belong to the following unit. These rules
2678 almost always result in the right choice of
2679 the split point without needing to mark it explicitly and most users will
2680 find this default to be what they want. In this default mode it is incorrect to
2681 submit a file containing only configuration pragmas, or one that ends in
2682 configuration pragmas, to @code{gnatchop}.
2684 However, using a special option to activate 'compilation mode',
2685 @code{gnatchop}
2686 can perform another function, which is to provide exactly the semantics
2687 required by the RM for handling of configuration pragmas in a compilation.
2688 In the absence of configuration pragmas (at the main file level), this
2689 option has no effect, but it causes such configuration pragmas to be handled
2690 in a quite different manner.
2692 First, in compilation mode, if @code{gnatchop} is given a file that consists of
2693 only configuration pragmas, then this file is appended to the
2694 @code{gnat.adc} file in the current directory. This behavior provides
2695 the required behavior described in the RM for the actions to be taken
2696 on submitting such a file to the compiler, namely that these pragmas
2697 should apply to all subsequent compilations in the same compilation
2698 environment. Using GNAT, the current directory, possibly containing a
2699 @code{gnat.adc} file is the representation
2700 of a compilation environment. For more information on the
2701 @code{gnat.adc} file, see @ref{56,,Handling of Configuration Pragmas}.
2703 Second, in compilation mode, if @code{gnatchop}
2704 is given a file that starts with
2705 configuration pragmas, and contains one or more units, then these
2706 configuration pragmas are prepended to each of the chopped files. This
2707 behavior provides the required behavior described in the RM for the
2708 actions to be taken on compiling such a file, namely that the pragmas
2709 apply to all units in the compilation, but not to subsequently compiled
2710 units.
2712 Finally, if configuration pragmas appear between units, they are appended
2713 to the previous unit. This results in the previous unit being illegal,
2714 since the compiler does not accept configuration pragmas that follow
2715 a unit. This provides the required RM behavior that forbids configuration
2716 pragmas other than those preceding the first compilation unit of a
2717 compilation.
2719 For most purposes, @code{gnatchop} will be used in default mode. The
2720 compilation mode described above is used only if you need exactly
2721 accurate behavior with respect to compilations, and you have files
2722 that contain multiple units and configuration pragmas. In this
2723 circumstance the use of @code{gnatchop} with the compilation mode
2724 switch provides the required behavior, and is for example the mode
2725 in which GNAT processes the ACVC tests.
2727 @node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2728 @anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{72}
2729 @subsubsection Command Line for @code{gnatchop}
2732 The @code{gnatchop} command has the form:
2734 @example
2735 $ gnatchop switches file_name [file_name ...]
2736       [directory]
2737 @end example
2739 The only required argument is the file name of the file to be chopped.
2740 There are no restrictions on the form of this file name. The file itself
2741 contains one or more Ada units, in normal GNAT format, concatenated
2742 together. As shown, more than one file may be presented to be chopped.
2744 When run in default mode, @code{gnatchop} generates one output file in
2745 the current directory for each unit in each of the files.
2747 @code{directory}, if specified, gives the name of the directory to which
2748 the output files will be written. If it is not specified, all files are
2749 written to the current directory.
2751 For example, given a
2752 file called @code{hellofiles} containing
2754 @example
2755 procedure Hello;
2757 with Ada.Text_IO; use Ada.Text_IO;
2758 procedure Hello is
2759 begin
2760    Put_Line ("Hello");
2761 end Hello;
2762 @end example
2764 the command
2766 @example
2767 $ gnatchop hellofiles
2768 @end example
2770 generates two files in the current directory, one called
2771 @code{hello.ads} containing the single line that is the procedure spec,
2772 and the other called @code{hello.adb} containing the remaining text. The
2773 original file is not affected. The generated files can be compiled in
2774 the normal manner.
2776 When gnatchop is invoked on a file that is empty or that contains only empty
2777 lines and/or comments, gnatchop will not fail, but will not produce any
2778 new sources.
2780 For example, given a
2781 file called @code{toto.txt} containing
2783 @example
2784 --  Just a comment
2785 @end example
2787 the command
2789 @example
2790 $ gnatchop toto.txt
2791 @end example
2793 will not produce any new file and will result in the following warnings:
2795 @example
2796 toto.txt:1:01: warning: empty file, contains no compilation units
2797 no compilation units found
2798 no source files written
2799 @end example
2801 @node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2802 @anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{73}@anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{74}
2803 @subsubsection Switches for @code{gnatchop}
2806 @code{gnatchop} recognizes the following switches:
2808 @geindex --version (gnatchop)
2811 @table @asis
2813 @item @code{--version}
2815 Display Copyright and version, then exit disregarding all other options.
2816 @end table
2818 @geindex --help (gnatchop)
2821 @table @asis
2823 @item @code{--help}
2825 If @code{--version} was not used, display usage, then exit disregarding
2826 all other options.
2827 @end table
2829 @geindex -c (gnatchop)
2832 @table @asis
2834 @item @code{-c}
2836 Causes @code{gnatchop} to operate in compilation mode, in which
2837 configuration pragmas are handled according to strict RM rules. See
2838 previous section for a full description of this mode.
2840 @item @code{-gnat@emph{xxx}}
2842 This passes the given @code{-gnat@emph{xxx}} switch to @code{gnat} which is
2843 used to parse the given file. Not all @emph{xxx} options make sense,
2844 but for example, the use of @code{-gnati2} allows @code{gnatchop} to
2845 process a source file that uses Latin-2 coding for identifiers.
2847 @item @code{-h}
2849 Causes @code{gnatchop} to generate a brief help summary to the standard
2850 output file showing usage information.
2851 @end table
2853 @geindex -k (gnatchop)
2856 @table @asis
2858 @item @code{-k@emph{mm}}
2860 Limit generated file names to the specified number @code{mm}
2861 of characters.
2862 This is useful if the
2863 resulting set of files is required to be interoperable with systems
2864 which limit the length of file names.
2865 No space is allowed between the @code{-k} and the numeric value. The numeric
2866 value may be omitted in which case a default of @code{-k8},
2867 suitable for use
2868 with DOS-like file systems, is used. If no @code{-k} switch
2869 is present then
2870 there is no limit on the length of file names.
2871 @end table
2873 @geindex -p (gnatchop)
2876 @table @asis
2878 @item @code{-p}
2880 Causes the file modification time stamp of the input file to be
2881 preserved and used for the time stamp of the output file(s). This may be
2882 useful for preserving coherency of time stamps in an environment where
2883 @code{gnatchop} is used as part of a standard build process.
2884 @end table
2886 @geindex -q (gnatchop)
2889 @table @asis
2891 @item @code{-q}
2893 Causes output of informational messages indicating the set of generated
2894 files to be suppressed. Warnings and error messages are unaffected.
2895 @end table
2897 @geindex -r (gnatchop)
2899 @geindex Source_Reference pragmas
2902 @table @asis
2904 @item @code{-r}
2906 Generate @code{Source_Reference} pragmas. Use this switch if the output
2907 files are regarded as temporary and development is to be done in terms
2908 of the original unchopped file. This switch causes
2909 @code{Source_Reference} pragmas to be inserted into each of the
2910 generated files to refers back to the original file name and line number.
2911 The result is that all error messages refer back to the original
2912 unchopped file.
2913 In addition, the debugging information placed into the object file (when
2914 the @code{-g} switch of @code{gcc} or @code{gnatmake} is
2915 specified)
2916 also refers back to this original file so that tools like profilers and
2917 debuggers will give information in terms of the original unchopped file.
2919 If the original file to be chopped itself contains
2920 a @code{Source_Reference}
2921 pragma referencing a third file, then gnatchop respects
2922 this pragma, and the generated @code{Source_Reference} pragmas
2923 in the chopped file refer to the original file, with appropriate
2924 line numbers. This is particularly useful when @code{gnatchop}
2925 is used in conjunction with @code{gnatprep} to compile files that
2926 contain preprocessing statements and multiple units.
2927 @end table
2929 @geindex -v (gnatchop)
2932 @table @asis
2934 @item @code{-v}
2936 Causes @code{gnatchop} to operate in verbose mode. The version
2937 number and copyright notice are output, as well as exact copies of
2938 the gnat1 commands spawned to obtain the chop control information.
2939 @end table
2941 @geindex -w (gnatchop)
2944 @table @asis
2946 @item @code{-w}
2948 Overwrite existing file names. Normally @code{gnatchop} regards it as a
2949 fatal error if there is already a file with the same name as a
2950 file it would otherwise output, in other words if the files to be
2951 chopped contain duplicated units. This switch bypasses this
2952 check, and causes all but the last instance of such duplicated
2953 units to be skipped.
2954 @end table
2956 @geindex --GCC= (gnatchop)
2959 @table @asis
2961 @item @code{--GCC=@emph{xxxx}}
2963 Specify the path of the GNAT parser to be used. When this switch is used,
2964 no attempt is made to add the prefix to the GNAT parser executable.
2965 @end table
2967 @node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
2968 @anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{75}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{76}
2969 @subsubsection Examples of @code{gnatchop} Usage
2972 @example
2973 $ gnatchop -w hello_s.ada prerelease/files
2974 @end example
2976 Chops the source file @code{hello_s.ada}. The output files will be
2977 placed in the directory @code{prerelease/files},
2978 overwriting any
2979 files with matching names in that directory (no files in the current
2980 directory are modified).
2982 @example
2983 $ gnatchop archive
2984 @end example
2986 Chops the source file @code{archive}
2987 into the current directory. One
2988 useful application of @code{gnatchop} is in sending sets of sources
2989 around, for example in email messages. The required sources are simply
2990 concatenated (for example, using a Unix @code{cat}
2991 command), and then
2992 @code{gnatchop} is used at the other end to reconstitute the original
2993 file names.
2995 @example
2996 $ gnatchop file1 file2 file3 direc
2997 @end example
2999 Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
3000 the resulting files in the directory @code{direc}. Note that if any units
3001 occur more than once anywhere within this set of files, an error message
3002 is generated, and no files are written. To override this check, use the
3003 @code{-w} switch,
3004 in which case the last occurrence in the last file will
3005 be the one that is output, and earlier duplicate occurrences for a given
3006 unit will be skipped.
3008 @node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
3009 @anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{14}
3010 @section Configuration Pragmas
3013 @geindex Configuration pragmas
3015 @geindex Pragmas
3016 @geindex configuration
3018 Configuration pragmas include those pragmas described as
3019 such in the Ada Reference Manual, as well as
3020 implementation-dependent pragmas that are configuration pragmas.
3021 See the @code{Implementation_Defined_Pragmas} chapter in the
3022 @cite{GNAT_Reference_Manual} for details on these
3023 additional GNAT-specific configuration pragmas.
3024 Most notably, the pragma @code{Source_File_Name}, which allows
3025 specifying non-default names for source files, is a configuration
3026 pragma. The following is a complete list of configuration pragmas
3027 recognized by GNAT:
3029 @example
3030 Ada_83
3031 Ada_95
3032 Ada_05
3033 Ada_2005
3034 Ada_12
3035 Ada_2012
3036 Allow_Integer_Address
3037 Annotate
3038 Assertion_Policy
3039 Assume_No_Invalid_Values
3040 C_Pass_By_Copy
3041 Check_Float_Overflow
3042 Check_Name
3043 Check_Policy
3044 Compile_Time_Error
3045 Compile_Time_Warning
3046 Compiler_Unit
3047 Compiler_Unit_Warning
3048 Component_Alignment
3049 Convention_Identifier
3050 Debug_Policy
3051 Detect_Blocking
3052 Default_Scalar_Storage_Order
3053 Default_Storage_Pool
3054 Disable_Atomic_Synchronization
3055 Discard_Names
3056 Elaboration_Checks
3057 Eliminate
3058 Enable_Atomic_Synchronization
3059 Extend_System
3060 Extensions_Allowed
3061 External_Name_Casing
3062 Fast_Math
3063 Favor_Top_Level
3064 Ignore_Pragma
3065 Implicit_Packing
3066 Initialize_Scalars
3067 Interrupt_State
3068 License
3069 Locking_Policy
3070 No_Component_Reordering
3071 No_Heap_Finalization
3072 No_Run_Time
3073 No_Strict_Aliasing
3074 Normalize_Scalars
3075 Optimize_Alignment
3076 Overflow_Mode
3077 Overriding_Renamings
3078 Partition_Elaboration_Policy
3079 Persistent_BSS
3080 Polling
3081 Prefix_Exception_Messages
3082 Priority_Specific_Dispatching
3083 Profile
3084 Profile_Warnings
3085 Propagate_Exceptions
3086 Queuing_Policy
3087 Rational
3088 Ravenscar
3089 Rename_Pragma
3090 Restricted_Run_Time
3091 Restrictions
3092 Restrictions_Warnings
3093 Reviewable
3094 Short_Circuit_And_Or
3095 Short_Descriptors
3096 Source_File_Name
3097 Source_File_Name_Project
3098 SPARK_Mode
3099 Style_Checks
3100 Suppress
3101 Suppress_Exception_Locations
3102 Task_Dispatching_Policy
3103 Unevaluated_Use_Of_Old
3104 Universal_Data
3105 Unsuppress
3106 Use_VADS_Size
3107 Validity_Checks
3108 Warning_As_Error
3109 Warnings
3110 Wide_Character_Encoding
3111 @end example
3113 @menu
3114 * Handling of Configuration Pragmas:: 
3115 * The Configuration Pragmas Files:: 
3117 @end menu
3119 @node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
3120 @anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{78}@anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{56}
3121 @subsection Handling of Configuration Pragmas
3124 Configuration pragmas may either appear at the start of a compilation
3125 unit, or they can appear in a configuration pragma file to apply to
3126 all compilations performed in a given compilation environment.
3128 GNAT also provides the @code{gnatchop} utility to provide an automatic
3129 way to handle configuration pragmas following the semantics for
3130 compilations (that is, files with multiple units), described in the RM.
3131 See @ref{6f,,Operating gnatchop in Compilation Mode} for details.
3132 However, for most purposes, it will be more convenient to edit the
3133 @code{gnat.adc} file that contains configuration pragmas directly,
3134 as described in the following section.
3136 In the case of @code{Restrictions} pragmas appearing as configuration
3137 pragmas in individual compilation units, the exact handling depends on
3138 the type of restriction.
3140 Restrictions that require partition-wide consistency (like
3141 @code{No_Tasking}) are
3142 recognized wherever they appear
3143 and can be freely inherited, e.g. from a @emph{with}ed unit to the @emph{with}ing
3144 unit. This makes sense since the binder will in any case insist on seeing
3145 consistent use, so any unit not conforming to any restrictions that are
3146 anywhere in the partition will be rejected, and you might as well find
3147 that out at compile time rather than at bind time.
3149 For restrictions that do not require partition-wide consistency, e.g.
3150 SPARK or No_Implementation_Attributes, in general the restriction applies
3151 only to the unit in which the pragma appears, and not to any other units.
3153 The exception is No_Elaboration_Code which always applies to the entire
3154 object file from a compilation, i.e. to the body, spec, and all subunits.
3155 This restriction can be specified in a configuration pragma file, or it
3156 can be on the body and/or the spec (in eithe case it applies to all the
3157 relevant units). It can appear on a subunit only if it has previously
3158 appeared in the body of spec.
3160 @node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
3161 @anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{79}@anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{7a}
3162 @subsection The Configuration Pragmas Files
3165 @geindex gnat.adc
3167 In GNAT a compilation environment is defined by the current
3168 directory at the time that a compile command is given. This current
3169 directory is searched for a file whose name is @code{gnat.adc}. If
3170 this file is present, it is expected to contain one or more
3171 configuration pragmas that will be applied to the current compilation.
3172 However, if the switch @code{-gnatA} is used, @code{gnat.adc} is not
3173 considered. When taken into account, @code{gnat.adc} is added to the
3174 dependencies, so that if @code{gnat.adc} is modified later, an invocation of
3175 @code{gnatmake} will recompile the source.
3177 Configuration pragmas may be entered into the @code{gnat.adc} file
3178 either by running @code{gnatchop} on a source file that consists only of
3179 configuration pragmas, or more conveniently by direct editing of the
3180 @code{gnat.adc} file, which is a standard format source file.
3182 Besides @code{gnat.adc}, additional files containing configuration
3183 pragmas may be applied to the current compilation using the switch
3184 @code{-gnatec=@emph{path}} where @code{path} must designate an existing file that
3185 contains only configuration pragmas. These configuration pragmas are
3186 in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
3187 is present and switch @code{-gnatA} is not used).
3189 It is allowable to specify several switches @code{-gnatec=}, all of which
3190 will be taken into account.
3192 Files containing configuration pragmas specified with switches
3193 @code{-gnatec=} are added to the dependencies, unless they are
3194 temporary files. A file is considered temporary if its name ends in
3195 @code{.tmp} or @code{.TMP}. Certain tools follow this naming
3196 convention because they pass information to @code{gcc} via
3197 temporary files that are immediately deleted; it doesn't make sense to
3198 depend on a file that no longer exists. Such tools include
3199 @code{gprbuild}, @code{gnatmake}, and @code{gnatcheck}.
3201 If you are using project file, a separate mechanism is provided using
3202 project attributes.
3204 @c --Comment
3205 @c See :ref:`Specifying_Configuration_Pragmas` for more details.
3207 @node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
3208 @anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{7b}
3209 @section Generating Object Files
3212 An Ada program consists of a set of source files, and the first step in
3213 compiling the program is to generate the corresponding object files.
3214 These are generated by compiling a subset of these source files.
3215 The files you need to compile are the following:
3218 @itemize *
3220 @item 
3221 If a package spec has no body, compile the package spec to produce the
3222 object file for the package.
3224 @item 
3225 If a package has both a spec and a body, compile the body to produce the
3226 object file for the package. The source file for the package spec need
3227 not be compiled in this case because there is only one object file, which
3228 contains the code for both the spec and body of the package.
3230 @item 
3231 For a subprogram, compile the subprogram body to produce the object file
3232 for the subprogram. The spec, if one is present, is as usual in a
3233 separate file, and need not be compiled.
3234 @end itemize
3236 @geindex Subunits
3239 @itemize *
3241 @item 
3242 In the case of subunits, only compile the parent unit. A single object
3243 file is generated for the entire subunit tree, which includes all the
3244 subunits.
3246 @item 
3247 Compile child units independently of their parent units
3248 (though, of course, the spec of all the ancestor unit must be present in order
3249 to compile a child unit).
3251 @geindex Generics
3253 @item 
3254 Compile generic units in the same manner as any other units. The object
3255 files in this case are small dummy files that contain at most the
3256 flag used for elaboration checking. This is because GNAT always handles generic
3257 instantiation by means of macro expansion. However, it is still necessary to
3258 compile generic units, for dependency checking and elaboration purposes.
3259 @end itemize
3261 The preceding rules describe the set of files that must be compiled to
3262 generate the object files for a program. Each object file has the same
3263 name as the corresponding source file, except that the extension is
3264 @code{.o} as usual.
3266 You may wish to compile other files for the purpose of checking their
3267 syntactic and semantic correctness. For example, in the case where a
3268 package has a separate spec and body, you would not normally compile the
3269 spec. However, it is convenient in practice to compile the spec to make
3270 sure it is error-free before compiling clients of this spec, because such
3271 compilations will fail if there is an error in the spec.
3273 GNAT provides an option for compiling such files purely for the
3274 purposes of checking correctness; such compilations are not required as
3275 part of the process of building a program. To compile a file in this
3276 checking mode, use the @code{-gnatc} switch.
3278 @node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3279 @anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{7c}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{41}
3280 @section Source Dependencies
3283 A given object file clearly depends on the source file which is compiled
3284 to produce it. Here we are using "depends" in the sense of a typical
3285 @code{make} utility; in other words, an object file depends on a source
3286 file if changes to the source file require the object file to be
3287 recompiled.
3288 In addition to this basic dependency, a given object may depend on
3289 additional source files as follows:
3292 @itemize *
3294 @item 
3295 If a file being compiled @emph{with}s a unit @code{X}, the object file
3296 depends on the file containing the spec of unit @code{X}. This includes
3297 files that are @emph{with}ed implicitly either because they are parents
3298 of @emph{with}ed child units or they are run-time units required by the
3299 language constructs used in a particular unit.
3301 @item 
3302 If a file being compiled instantiates a library level generic unit, the
3303 object file depends on both the spec and body files for this generic
3304 unit.
3306 @item 
3307 If a file being compiled instantiates a generic unit defined within a
3308 package, the object file depends on the body file for the package as
3309 well as the spec file.
3310 @end itemize
3312 @geindex Inline
3314 @geindex -gnatn switch
3317 @itemize *
3319 @item 
3320 If a file being compiled contains a call to a subprogram for which
3321 pragma @code{Inline} applies and inlining is activated with the
3322 @code{-gnatn} switch, the object file depends on the file containing the
3323 body of this subprogram as well as on the file containing the spec. Note
3324 that for inlining to actually occur as a result of the use of this switch,
3325 it is necessary to compile in optimizing mode.
3327 @geindex -gnatN switch
3329 The use of @code{-gnatN} activates  inlining optimization
3330 that is performed by the front end of the compiler. This inlining does
3331 not require that the code generation be optimized. Like @code{-gnatn},
3332 the use of this switch generates additional dependencies.
3334 When using a gcc-based back end (in practice this means using any version
3335 of GNAT other than for the JVM, .NET or GNAAMP platforms), then the use of
3336 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
3337 Historically front end inlining was more extensive than the gcc back end
3338 inlining, but that is no longer the case.
3340 @item 
3341 If an object file @code{O} depends on the proper body of a subunit through
3342 inlining or instantiation, it depends on the parent unit of the subunit.
3343 This means that any modification of the parent unit or one of its subunits
3344 affects the compilation of @code{O}.
3346 @item 
3347 The object file for a parent unit depends on all its subunit body files.
3349 @item 
3350 The previous two rules meant that for purposes of computing dependencies and
3351 recompilation, a body and all its subunits are treated as an indivisible whole.
3353 These rules are applied transitively: if unit @code{A} @emph{with}s
3354 unit @code{B}, whose elaboration calls an inlined procedure in package
3355 @code{C}, the object file for unit @code{A} will depend on the body of
3356 @code{C}, in file @code{c.adb}.
3358 The set of dependent files described by these rules includes all the
3359 files on which the unit is semantically dependent, as dictated by the
3360 Ada language standard. However, it is a superset of what the
3361 standard describes, because it includes generic, inline, and subunit
3362 dependencies.
3364 An object file must be recreated by recompiling the corresponding source
3365 file if any of the source files on which it depends are modified. For
3366 example, if the @code{make} utility is used to control compilation,
3367 the rule for an Ada object file must mention all the source files on
3368 which the object file depends, according to the above definition.
3369 The determination of the necessary
3370 recompilations is done automatically when one uses @code{gnatmake}.
3371 @end itemize
3373 @node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3374 @anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{7d}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{42}
3375 @section The Ada Library Information Files
3378 @geindex Ada Library Information files
3380 @geindex ALI files
3382 Each compilation actually generates two output files. The first of these
3383 is the normal object file that has a @code{.o} extension. The second is a
3384 text file containing full dependency information. It has the same
3385 name as the source file, but an @code{.ali} extension.
3386 This file is known as the Ada Library Information (@code{ALI}) file.
3387 The following information is contained in the @code{ALI} file.
3390 @itemize *
3392 @item 
3393 Version information (indicates which version of GNAT was used to compile
3394 the unit(s) in question)
3396 @item 
3397 Main program information (including priority and time slice settings,
3398 as well as the wide character encoding used during compilation).
3400 @item 
3401 List of arguments used in the @code{gcc} command for the compilation
3403 @item 
3404 Attributes of the unit, including configuration pragmas used, an indication
3405 of whether the compilation was successful, exception model used etc.
3407 @item 
3408 A list of relevant restrictions applying to the unit (used for consistency)
3409 checking.
3411 @item 
3412 Categorization information (e.g., use of pragma @code{Pure}).
3414 @item 
3415 Information on all @emph{with}ed units, including presence of
3416 @code{Elaborate} or @code{Elaborate_All} pragmas.
3418 @item 
3419 Information from any @code{Linker_Options} pragmas used in the unit
3421 @item 
3422 Information on the use of @code{Body_Version} or @code{Version}
3423 attributes in the unit.
3425 @item 
3426 Dependency information. This is a list of files, together with
3427 time stamp and checksum information. These are files on which
3428 the unit depends in the sense that recompilation is required
3429 if any of these units are modified.
3431 @item 
3432 Cross-reference data. Contains information on all entities referenced
3433 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
3434 provide cross-reference information.
3435 @end itemize
3437 For a full detailed description of the format of the @code{ALI} file,
3438 see the source of the body of unit @code{Lib.Writ}, contained in file
3439 @code{lib-writ.adb} in the GNAT compiler sources.
3441 @node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3442 @anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{7e}@anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{43}
3443 @section Binding an Ada Program
3446 When using languages such as C and C++, once the source files have been
3447 compiled the only remaining step in building an executable program
3448 is linking the object modules together. This means that it is possible to
3449 link an inconsistent version of a program, in which two units have
3450 included different versions of the same header.
3452 The rules of Ada do not permit such an inconsistent program to be built.
3453 For example, if two clients have different versions of the same package,
3454 it is illegal to build a program containing these two clients.
3455 These rules are enforced by the GNAT binder, which also determines an
3456 elaboration order consistent with the Ada rules.
3458 The GNAT binder is run after all the object files for a program have
3459 been created. It is given the name of the main program unit, and from
3460 this it determines the set of units required by the program, by reading the
3461 corresponding ALI files. It generates error messages if the program is
3462 inconsistent or if no valid order of elaboration exists.
3464 If no errors are detected, the binder produces a main program, in Ada by
3465 default, that contains calls to the elaboration procedures of those
3466 compilation unit that require them, followed by
3467 a call to the main program. This Ada program is compiled to generate the
3468 object file for the main program. The name of
3469 the Ada file is @code{b~xxx}.adb` (with the corresponding spec
3470 @code{b~xxx}.ads`) where @code{xxx} is the name of the
3471 main program unit.
3473 Finally, the linker is used to build the resulting executable program,
3474 using the object from the main program from the bind step as well as the
3475 object files for the Ada units of the program.
3477 @node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3478 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{15}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{7f}
3479 @section GNAT and Libraries
3482 @geindex Library building and using
3484 This section describes how to build and use libraries with GNAT, and also shows
3485 how to recompile the GNAT run-time library. You should be familiar with the
3486 Project Manager facility (see the @emph{GNAT_Project_Manager} chapter of the
3487 @emph{GPRbuild User's Guide}) before reading this chapter.
3489 @menu
3490 * Introduction to Libraries in GNAT:: 
3491 * General Ada Libraries:: 
3492 * Stand-alone Ada Libraries:: 
3493 * Rebuilding the GNAT Run-Time Library:: 
3495 @end menu
3497 @node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3498 @anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{80}@anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{81}
3499 @subsection Introduction to Libraries in GNAT
3502 A library is, conceptually, a collection of objects which does not have its
3503 own main thread of execution, but rather provides certain services to the
3504 applications that use it. A library can be either statically linked with the
3505 application, in which case its code is directly included in the application,
3506 or, on platforms that support it, be dynamically linked, in which case
3507 its code is shared by all applications making use of this library.
3509 GNAT supports both types of libraries.
3510 In the static case, the compiled code can be provided in different ways. The
3511 simplest approach is to provide directly the set of objects resulting from
3512 compilation of the library source files. Alternatively, you can group the
3513 objects into an archive using whatever commands are provided by the operating
3514 system. For the latter case, the objects are grouped into a shared library.
3516 In the GNAT environment, a library has three types of components:
3519 @itemize *
3521 @item 
3522 Source files,
3524 @item 
3525 @code{ALI} files (see @ref{42,,The Ada Library Information Files}), and
3527 @item 
3528 Object files, an archive or a shared library.
3529 @end itemize
3531 A GNAT library may expose all its source files, which is useful for
3532 documentation purposes. Alternatively, it may expose only the units needed by
3533 an external user to make use of the library. That is to say, the specs
3534 reflecting the library services along with all the units needed to compile
3535 those specs, which can include generic bodies or any body implementing an
3536 inlined routine. In the case of @emph{stand-alone libraries} those exposed
3537 units are called @emph{interface units} (@ref{82,,Stand-alone Ada Libraries}).
3539 All compilation units comprising an application, including those in a library,
3540 need to be elaborated in an order partially defined by Ada's semantics. GNAT
3541 computes the elaboration order from the @code{ALI} files and this is why they
3542 constitute a mandatory part of GNAT libraries.
3543 @emph{Stand-alone libraries} are the exception to this rule because a specific
3544 library elaboration routine is produced independently of the application(s)
3545 using the library.
3547 @node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3548 @anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{83}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{84}
3549 @subsection General Ada Libraries
3552 @menu
3553 * Building a library:: 
3554 * Installing a library:: 
3555 * Using a library:: 
3557 @end menu
3559 @node Building a library,Installing a library,,General Ada Libraries
3560 @anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{85}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{86}
3561 @subsubsection Building a library
3564 The easiest way to build a library is to use the Project Manager,
3565 which supports a special type of project called a @emph{Library Project}
3566 (see the @emph{Library Projects} section in the @emph{GNAT Project Manager}
3567 chapter of the @emph{GPRbuild User's Guide}).
3569 A project is considered a library project, when two project-level attributes
3570 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
3571 control different aspects of library configuration, additional optional
3572 project-level attributes can be specified:
3575 @itemize *
3577 @item 
3579 @table @asis
3581 @item @code{Library_Kind}
3583 This attribute controls whether the library is to be static or dynamic
3584 @end table
3586 @item 
3588 @table @asis
3590 @item @code{Library_Version}
3592 This attribute specifies the library version; this value is used
3593 during dynamic linking of shared libraries to determine if the currently
3594 installed versions of the binaries are compatible.
3595 @end table
3597 @item 
3598 @code{Library_Options}
3600 @item 
3602 @table @asis
3604 @item @code{Library_GCC}
3606 These attributes specify additional low-level options to be used during
3607 library generation, and redefine the actual application used to generate
3608 library.
3609 @end table
3610 @end itemize
3612 The GNAT Project Manager takes full care of the library maintenance task,
3613 including recompilation of the source files for which objects do not exist
3614 or are not up to date, assembly of the library archive, and installation of
3615 the library (i.e., copying associated source, object and @code{ALI} files
3616 to the specified location).
3618 Here is a simple library project file:
3620 @example
3621 project My_Lib is
3622   for Source_Dirs use ("src1", "src2");
3623   for Object_Dir use "obj";
3624   for Library_Name use "mylib";
3625   for Library_Dir use "lib";
3626   for Library_Kind use "dynamic";
3627 end My_lib;
3628 @end example
3630 and the compilation command to build and install the library:
3632 @example
3633 $ gnatmake -Pmy_lib
3634 @end example
3636 It is not entirely trivial to perform manually all the steps required to
3637 produce a library. We recommend that you use the GNAT Project Manager
3638 for this task. In special cases where this is not desired, the necessary
3639 steps are discussed below.
3641 There are various possibilities for compiling the units that make up the
3642 library: for example with a Makefile (@ref{1f,,Using the GNU make Utility}) or
3643 with a conventional script. For simple libraries, it is also possible to create
3644 a dummy main program which depends upon all the packages that comprise the
3645 interface of the library. This dummy main program can then be given to
3646 @code{gnatmake}, which will ensure that all necessary objects are built.
3648 After this task is accomplished, you should follow the standard procedure
3649 of the underlying operating system to produce the static or shared library.
3651 Here is an example of such a dummy program:
3653 @example
3654 with My_Lib.Service1;
3655 with My_Lib.Service2;
3656 with My_Lib.Service3;
3657 procedure My_Lib_Dummy is
3658 begin
3659    null;
3660 end;
3661 @end example
3663 Here are the generic commands that will build an archive or a shared library.
3665 @example
3666 # compiling the library
3667 $ gnatmake -c my_lib_dummy.adb
3669 # we don't need the dummy object itself
3670 $ rm my_lib_dummy.o my_lib_dummy.ali
3672 # create an archive with the remaining objects
3673 $ ar rc libmy_lib.a *.o
3674 # some systems may require "ranlib" to be run as well
3676 # or create a shared library
3677 $ gcc -shared -o libmy_lib.so *.o
3678 # some systems may require the code to have been compiled with -fPIC
3680 # remove the object files that are now in the library
3681 $ rm *.o
3683 # Make the ALI files read-only so that gnatmake will not try to
3684 # regenerate the objects that are in the library
3685 $ chmod -w *.ali
3686 @end example
3688 Please note that the library must have a name of the form @code{lib@emph{xxx}.a}
3689 or @code{lib@emph{xxx}.so} (or @code{lib@emph{xxx}.dll} on Windows) in order to
3690 be accessed by the directive @code{-l@emph{xxx}} at link time.
3692 @node Installing a library,Using a library,Building a library,General Ada Libraries
3693 @anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{87}@anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{88}
3694 @subsubsection Installing a library
3697 @geindex ADA_PROJECT_PATH
3699 @geindex GPR_PROJECT_PATH
3701 If you use project files, library installation is part of the library build
3702 process (see the @emph{Installing a Library with Project Files} section of the
3703 @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}).
3705 When project files are not an option, it is also possible, but not recommended,
3706 to install the library so that the sources needed to use the library are on the
3707 Ada source path and the ALI files & libraries be on the Ada Object path (see
3708 @ref{89,,Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
3709 administrator can place general-purpose libraries in the default compiler
3710 paths, by specifying the libraries' location in the configuration files
3711 @code{ada_source_path} and @code{ada_object_path}. These configuration files
3712 must be located in the GNAT installation tree at the same place as the gcc spec
3713 file. The location of the gcc spec file can be determined as follows:
3715 @example
3716 $ gcc -v
3717 @end example
3719 The configuration files mentioned above have a simple format: each line
3720 must contain one unique directory name.
3721 Those names are added to the corresponding path
3722 in their order of appearance in the file. The names can be either absolute
3723 or relative; in the latter case, they are relative to where theses files
3724 are located.
3726 The files @code{ada_source_path} and @code{ada_object_path} might not be
3727 present in a
3728 GNAT installation, in which case, GNAT will look for its run-time library in
3729 the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3730 objects and @code{ALI} files). When the files exist, the compiler does not
3731 look in @code{adainclude} and @code{adalib}, and thus the
3732 @code{ada_source_path} file
3733 must contain the location for the GNAT run-time sources (which can simply
3734 be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3735 contain the location for the GNAT run-time objects (which can simply
3736 be @code{adalib}).
3738 You can also specify a new default path to the run-time library at compilation
3739 time with the switch @code{--RTS=rts-path}. You can thus choose / change
3740 the run-time library you want your program to be compiled with. This switch is
3741 recognized by @code{gcc}, @code{gnatmake}, @code{gnatbind},
3742 @code{gnatls}, @code{gnatfind} and @code{gnatxref}.
3744 It is possible to install a library before or after the standard GNAT
3745 library, by reordering the lines in the configuration files. In general, a
3746 library must be installed before the GNAT library if it redefines
3747 any part of it.
3749 @node Using a library,,Installing a library,General Ada Libraries
3750 @anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{8a}@anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{8b}
3751 @subsubsection Using a library
3754 Once again, the project facility greatly simplifies the use of
3755 libraries. In this context, using a library is just a matter of adding a
3756 @emph{with} clause in the user project. For instance, to make use of the
3757 library @code{My_Lib} shown in examples in earlier sections, you can
3758 write:
3760 @example
3761 with "my_lib";
3762 project My_Proj is
3763   ...
3764 end My_Proj;
3765 @end example
3767 Even if you have a third-party, non-Ada library, you can still use GNAT's
3768 Project Manager facility to provide a wrapper for it. For example, the
3769 following project, when @emph{with}ed by your main project, will link with the
3770 third-party library @code{liba.a}:
3772 @example
3773 project Liba is
3774    for Externally_Built use "true";
3775    for Source_Files use ();
3776    for Library_Dir use "lib";
3777    for Library_Name use "a";
3778    for Library_Kind use "static";
3779 end Liba;
3780 @end example
3782 This is an alternative to the use of @code{pragma Linker_Options}. It is
3783 especially interesting in the context of systems with several interdependent
3784 static libraries where finding a proper linker order is not easy and best be
3785 left to the tools having visibility over project dependence information.
3787 In order to use an Ada library manually, you need to make sure that this
3788 library is on both your source and object path
3789 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}
3790 and @ref{8c,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3791 in an archive or a shared library, you need to specify the desired
3792 library at link time.
3794 For example, you can use the library @code{mylib} installed in
3795 @code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3797 @example
3798 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3799   -largs -lmy_lib
3800 @end example
3802 This can be expressed more simply:
3804 @example
3805 $ gnatmake my_appl
3806 @end example
3808 when the following conditions are met:
3811 @itemize *
3813 @item 
3814 @code{/dir/my_lib_src} has been added by the user to the environment
3815 variable 
3816 @geindex ADA_INCLUDE_PATH
3817 @geindex environment variable; ADA_INCLUDE_PATH
3818 @code{ADA_INCLUDE_PATH}, or by the administrator to the file
3819 @code{ada_source_path}
3821 @item 
3822 @code{/dir/my_lib_obj} has been added by the user to the environment
3823 variable 
3824 @geindex ADA_OBJECTS_PATH
3825 @geindex environment variable; ADA_OBJECTS_PATH
3826 @code{ADA_OBJECTS_PATH}, or by the administrator to the file
3827 @code{ada_object_path}
3829 @item 
3830 a pragma @code{Linker_Options} has been added to one of the sources.
3831 For example:
3833 @example
3834 pragma Linker_Options ("-lmy_lib");
3835 @end example
3836 @end itemize
3838 Note that you may also load a library dynamically at
3839 run time given its filename, as illustrated in the GNAT @code{plugins} example
3840 in the directory @code{share/examples/gnat/plugins} within the GNAT
3841 install area.
3843 @node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3844 @anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{82}@anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{8d}
3845 @subsection Stand-alone Ada Libraries
3848 @geindex Stand-alone libraries
3850 @menu
3851 * Introduction to Stand-alone Libraries:: 
3852 * Building a Stand-alone Library:: 
3853 * Creating a Stand-alone Library to be used in a non-Ada context:: 
3854 * Restrictions in Stand-alone Libraries:: 
3856 @end menu
3858 @node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3859 @anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{8e}@anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{8f}
3860 @subsubsection Introduction to Stand-alone Libraries
3863 A Stand-alone Library (abbreviated 'SAL') is a library that contains the
3864 necessary code to
3865 elaborate the Ada units that are included in the library. In contrast with
3866 an ordinary library, which consists of all sources, objects and @code{ALI}
3867 files of the
3868 library, a SAL may specify a restricted subset of compilation units
3869 to serve as a library interface. In this case, the fully
3870 self-sufficient set of files will normally consist of an objects
3871 archive, the sources of interface units' specs, and the @code{ALI}
3872 files of interface units.
3873 If an interface spec contains a generic unit or an inlined subprogram,
3874 the body's
3875 source must also be provided; if the units that must be provided in the source
3876 form depend on other units, the source and @code{ALI} files of those must
3877 also be provided.
3879 The main purpose of a SAL is to minimize the recompilation overhead of client
3880 applications when a new version of the library is installed. Specifically,
3881 if the interface sources have not changed, client applications do not need to
3882 be recompiled. If, furthermore, a SAL is provided in the shared form and its
3883 version, controlled by @code{Library_Version} attribute, is not changed,
3884 then the clients do not need to be relinked.
3886 SALs also allow the library providers to minimize the amount of library source
3887 text exposed to the clients.  Such 'information hiding' might be useful or
3888 necessary for various reasons.
3890 Stand-alone libraries are also well suited to be used in an executable whose
3891 main routine is not written in Ada.
3893 @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
3894 @anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{90}@anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{91}
3895 @subsubsection Building a Stand-alone Library
3898 GNAT's Project facility provides a simple way of building and installing
3899 stand-alone libraries; see the @emph{Stand-alone Library Projects} section
3900 in the @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}.
3901 To be a Stand-alone Library Project, in addition to the two attributes
3902 that make a project a Library Project (@code{Library_Name} and
3903 @code{Library_Dir}; see the @emph{Library Projects} section in the
3904 @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}),
3905 the attribute @code{Library_Interface} must be defined.  For example:
3907 @example
3908 for Library_Dir use "lib_dir";
3909 for Library_Name use "dummy";
3910 for Library_Interface use ("int1", "int1.child");
3911 @end example
3913 Attribute @code{Library_Interface} has a non-empty string list value,
3914 each string in the list designating a unit contained in an immediate source
3915 of the project file.
3917 When a Stand-alone Library is built, first the binder is invoked to build
3918 a package whose name depends on the library name
3919 (@code{b~dummy.ads/b} in the example above).
3920 This binder-generated package includes initialization and
3921 finalization procedures whose
3922 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
3923 in the example
3924 above). The object corresponding to this package is included in the library.
3926 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
3927 calling of these procedures if a static SAL is built, or if a shared SAL
3928 is built
3929 with the project-level attribute @code{Library_Auto_Init} set to
3930 @code{"false"}.
3932 For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
3933 (those that are listed in attribute @code{Library_Interface}) are copied to
3934 the Library Directory. As a consequence, only the Interface Units may be
3935 imported from Ada units outside of the library. If other units are imported,
3936 the binding phase will fail.
3938 It is also possible to build an encapsulated library where not only
3939 the code to elaborate and finalize the library is embedded but also
3940 ensuring that the library is linked only against static
3941 libraries. So an encapsulated library only depends on system
3942 libraries, all other code, including the GNAT runtime, is embedded. To
3943 build an encapsulated library the attribute
3944 @code{Library_Standalone} must be set to @code{encapsulated}:
3946 @example
3947 for Library_Dir use "lib_dir";
3948 for Library_Name use "dummy";
3949 for Library_Kind use "dynamic";
3950 for Library_Interface use ("int1", "int1.child");
3951 for Library_Standalone use "encapsulated";
3952 @end example
3954 The default value for this attribute is @code{standard} in which case
3955 a stand-alone library is built.
3957 The attribute @code{Library_Src_Dir} may be specified for a
3958 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
3959 single string value. Its value must be the path (absolute or relative to the
3960 project directory) of an existing directory. This directory cannot be the
3961 object directory or one of the source directories, but it can be the same as
3962 the library directory. The sources of the Interface
3963 Units of the library that are needed by an Ada client of the library will be
3964 copied to the designated directory, called the Interface Copy directory.
3965 These sources include the specs of the Interface Units, but they may also
3966 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
3967 are used, or when there is a generic unit in the spec. Before the sources
3968 are copied to the Interface Copy directory, an attempt is made to delete all
3969 files in the Interface Copy directory.
3971 Building stand-alone libraries by hand is somewhat tedious, but for those
3972 occasions when it is necessary here are the steps that you need to perform:
3975 @itemize *
3977 @item 
3978 Compile all library sources.
3980 @item 
3981 Invoke the binder with the switch @code{-n} (No Ada main program),
3982 with all the @code{ALI} files of the interfaces, and
3983 with the switch @code{-L} to give specific names to the @code{init}
3984 and @code{final} procedures.  For example:
3986 @example
3987 $ gnatbind -n int1.ali int2.ali -Lsal1
3988 @end example
3990 @item 
3991 Compile the binder generated file:
3993 @example
3994 $ gcc -c b~int2.adb
3995 @end example
3997 @item 
3998 Link the dynamic library with all the necessary object files,
3999 indicating to the linker the names of the @code{init} (and possibly
4000 @code{final}) procedures for automatic initialization (and finalization).
4001 The built library should be placed in a directory different from
4002 the object directory.
4004 @item 
4005 Copy the @code{ALI} files of the interface to the library directory,
4006 add in this copy an indication that it is an interface to a SAL
4007 (i.e., add a word @code{SL} on the line in the @code{ALI} file that starts
4008 with letter 'P') and make the modified copy of the @code{ALI} file
4009 read-only.
4010 @end itemize
4012 Using SALs is not different from using other libraries
4013 (see @ref{8a,,Using a library}).
4015 @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
4016 @anchor{gnat_ugn/the_gnat_compilation_model creating-a-stand-alone-library-to-be-used-in-a-non-ada-context}@anchor{92}@anchor{gnat_ugn/the_gnat_compilation_model id44}@anchor{93}
4017 @subsubsection Creating a Stand-alone Library to be used in a non-Ada context
4020 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
4021 a non-Ada context.
4023 The only extra step required is to ensure that library interface subprograms
4024 are compatible with the main program, by means of @code{pragma Export}
4025 or @code{pragma Convention}.
4027 Here is an example of simple library interface for use with C main program:
4029 @example
4030 package My_Package is
4032    procedure Do_Something;
4033    pragma Export (C, Do_Something, "do_something");
4035    procedure Do_Something_Else;
4036    pragma Export (C, Do_Something_Else, "do_something_else");
4038 end My_Package;
4039 @end example
4041 On the foreign language side, you must provide a 'foreign' view of the
4042 library interface; remember that it should contain elaboration routines in
4043 addition to interface subprograms.
4045 The example below shows the content of @code{mylib_interface.h} (note
4046 that there is no rule for the naming of this file, any name can be used)
4048 @example
4049 /* the library elaboration procedure */
4050 extern void mylibinit (void);
4052 /* the library finalization procedure */
4053 extern void mylibfinal (void);
4055 /* the interface exported by the library */
4056 extern void do_something (void);
4057 extern void do_something_else (void);
4058 @end example
4060 Libraries built as explained above can be used from any program, provided
4061 that the elaboration procedures (named @code{mylibinit} in the previous
4062 example) are called before the library services are used. Any number of
4063 libraries can be used simultaneously, as long as the elaboration
4064 procedure of each library is called.
4066 Below is an example of a C program that uses the @code{mylib} library.
4068 @example
4069 #include "mylib_interface.h"
4072 main (void)
4074    /* First, elaborate the library before using it */
4075    mylibinit ();
4077    /* Main program, using the library exported entities */
4078    do_something ();
4079    do_something_else ();
4081    /* Library finalization at the end of the program */
4082    mylibfinal ();
4083    return 0;
4085 @end example
4087 Note that invoking any library finalization procedure generated by
4088 @code{gnatbind} shuts down the Ada run-time environment.
4089 Consequently, the
4090 finalization of all Ada libraries must be performed at the end of the program.
4091 No call to these libraries or to the Ada run-time library should be made
4092 after the finalization phase.
4094 Note also that special care must be taken with multi-tasks
4095 applications. The initialization and finalization routines are not
4096 protected against concurrent access. If such requirement is needed it
4097 must be ensured at the application level using a specific operating
4098 system services like a mutex or a critical-section.
4100 @node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
4101 @anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{94}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{95}
4102 @subsubsection Restrictions in Stand-alone Libraries
4105 The pragmas listed below should be used with caution inside libraries,
4106 as they can create incompatibilities with other Ada libraries:
4109 @itemize *
4111 @item 
4112 pragma @code{Locking_Policy}
4114 @item 
4115 pragma @code{Partition_Elaboration_Policy}
4117 @item 
4118 pragma @code{Queuing_Policy}
4120 @item 
4121 pragma @code{Task_Dispatching_Policy}
4123 @item 
4124 pragma @code{Unreserve_All_Interrupts}
4125 @end itemize
4127 When using a library that contains such pragmas, the user must make sure
4128 that all libraries use the same pragmas with the same values. Otherwise,
4129 @code{Program_Error} will
4130 be raised during the elaboration of the conflicting
4131 libraries. The usage of these pragmas and its consequences for the user
4132 should therefore be well documented.
4134 Similarly, the traceback in the exception occurrence mechanism should be
4135 enabled or disabled in a consistent manner across all libraries.
4136 Otherwise, Program_Error will be raised during the elaboration of the
4137 conflicting libraries.
4139 If the @code{Version} or @code{Body_Version}
4140 attributes are used inside a library, then you need to
4141 perform a @code{gnatbind} step that specifies all @code{ALI} files in all
4142 libraries, so that version identifiers can be properly computed.
4143 In practice these attributes are rarely used, so this is unlikely
4144 to be a consideration.
4146 @node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
4147 @anchor{gnat_ugn/the_gnat_compilation_model id46}@anchor{96}@anchor{gnat_ugn/the_gnat_compilation_model rebuilding-the-gnat-run-time-library}@anchor{97}
4148 @subsection Rebuilding the GNAT Run-Time Library
4151 @geindex GNAT Run-Time Library
4152 @geindex rebuilding
4154 @geindex Building the GNAT Run-Time Library
4156 @geindex Rebuilding the GNAT Run-Time Library
4158 @geindex Run-Time Library
4159 @geindex rebuilding
4161 It may be useful to recompile the GNAT library in various contexts, the
4162 most important one being the use of partition-wide configuration pragmas
4163 such as @code{Normalize_Scalars}. A special Makefile called
4164 @code{Makefile.adalib} is provided to that effect and can be found in
4165 the directory containing the GNAT library. The location of this
4166 directory depends on the way the GNAT environment has been installed and can
4167 be determined by means of the command:
4169 @example
4170 $ gnatls -v
4171 @end example
4173 The last entry in the object search path usually contains the
4174 gnat library. This Makefile contains its own documentation and in
4175 particular the set of instructions needed to rebuild a new library and
4176 to use it.
4178 @geindex Conditional compilation
4180 @node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
4181 @anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{98}@anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{16}
4182 @section Conditional Compilation
4185 This section presents some guidelines for modeling conditional compilation in Ada and describes the
4186 gnatprep preprocessor utility.
4188 @geindex Conditional compilation
4190 @menu
4191 * Modeling Conditional Compilation in Ada:: 
4192 * Preprocessing with gnatprep:: 
4193 * Integrated Preprocessing:: 
4195 @end menu
4197 @node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
4198 @anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{99}@anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{9a}
4199 @subsection Modeling Conditional Compilation in Ada
4202 It is often necessary to arrange for a single source program
4203 to serve multiple purposes, where it is compiled in different
4204 ways to achieve these different goals. Some examples of the
4205 need for this feature are
4208 @itemize *
4210 @item 
4211 Adapting a program to a different hardware environment
4213 @item 
4214 Adapting a program to a different target architecture
4216 @item 
4217 Turning debugging features on and off
4219 @item 
4220 Arranging for a program to compile with different compilers
4221 @end itemize
4223 In C, or C++, the typical approach would be to use the preprocessor
4224 that is defined as part of the language. The Ada language does not
4225 contain such a feature. This is not an oversight, but rather a very
4226 deliberate design decision, based on the experience that overuse of
4227 the preprocessing features in C and C++ can result in programs that
4228 are extremely difficult to maintain. For example, if we have ten
4229 switches that can be on or off, this means that there are a thousand
4230 separate programs, any one of which might not even be syntactically
4231 correct, and even if syntactically correct, the resulting program
4232 might not work correctly. Testing all combinations can quickly become
4233 impossible.
4235 Nevertheless, the need to tailor programs certainly exists, and in
4236 this section we will discuss how this can
4237 be achieved using Ada in general, and GNAT in particular.
4239 @menu
4240 * Use of Boolean Constants:: 
4241 * Debugging - A Special Case:: 
4242 * Conditionalizing Declarations:: 
4243 * Use of Alternative Implementations:: 
4244 * Preprocessing:: 
4246 @end menu
4248 @node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4249 @anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{9b}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{9c}
4250 @subsubsection Use of Boolean Constants
4253 In the case where the difference is simply which code
4254 sequence is executed, the cleanest solution is to use Boolean
4255 constants to control which code is executed.
4257 @example
4258 FP_Initialize_Required : constant Boolean := True;
4260 if FP_Initialize_Required then
4262 end if;
4263 @end example
4265 Not only will the code inside the @code{if} statement not be executed if
4266 the constant Boolean is @code{False}, but it will also be completely
4267 deleted from the program.
4268 However, the code is only deleted after the @code{if} statement
4269 has been checked for syntactic and semantic correctness.
4270 (In contrast, with preprocessors the code is deleted before the
4271 compiler ever gets to see it, so it is not checked until the switch
4272 is turned on.)
4274 @geindex Preprocessors (contrasted with conditional compilation)
4276 Typically the Boolean constants will be in a separate package,
4277 something like:
4279 @example
4280 package Config is
4281    FP_Initialize_Required : constant Boolean := True;
4282    Reset_Available        : constant Boolean := False;
4283    ...
4284 end Config;
4285 @end example
4287 The @code{Config} package exists in multiple forms for the various targets,
4288 with an appropriate script selecting the version of @code{Config} needed.
4289 Then any other unit requiring conditional compilation can do a @emph{with}
4290 of @code{Config} to make the constants visible.
4292 @node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4293 @anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{9d}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{9e}
4294 @subsubsection Debugging - A Special Case
4297 A common use of conditional code is to execute statements (for example
4298 dynamic checks, or output of intermediate results) under control of a
4299 debug switch, so that the debugging behavior can be turned on and off.
4300 This can be done using a Boolean constant to control whether the code
4301 is active:
4303 @example
4304 if Debugging then
4305    Put_Line ("got to the first stage!");
4306 end if;
4307 @end example
4311 @example
4312 if Debugging and then Temperature > 999.0 then
4313    raise Temperature_Crazy;
4314 end if;
4315 @end example
4317 @geindex pragma Assert
4319 Since this is a common case, there are special features to deal with
4320 this in a convenient manner. For the case of tests, Ada 2005 has added
4321 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
4322 on the @code{Assert} pragma that has always been available in GNAT, so this
4323 feature may be used with GNAT even if you are not using Ada 2005 features.
4324 The use of pragma @code{Assert} is described in the
4325 @cite{GNAT_Reference_Manual}, but as an
4326 example, the last test could be written:
4328 @example
4329 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4330 @end example
4332 or simply
4334 @example
4335 pragma Assert (Temperature <= 999.0);
4336 @end example
4338 In both cases, if assertions are active and the temperature is excessive,
4339 the exception @code{Assert_Failure} will be raised, with the given string in
4340 the first case or a string indicating the location of the pragma in the second
4341 case used as the exception message.
4343 @geindex pragma Assertion_Policy
4345 You can turn assertions on and off by using the @code{Assertion_Policy}
4346 pragma.
4348 @geindex -gnata switch
4350 This is an Ada 2005 pragma which is implemented in all modes by
4351 GNAT. Alternatively, you can use the @code{-gnata} switch
4352 to enable assertions from the command line, which applies to
4353 all versions of Ada.
4355 @geindex pragma Debug
4357 For the example above with the @code{Put_Line}, the GNAT-specific pragma
4358 @code{Debug} can be used:
4360 @example
4361 pragma Debug (Put_Line ("got to the first stage!"));
4362 @end example
4364 If debug pragmas are enabled, the argument, which must be of the form of
4365 a procedure call, is executed (in this case, @code{Put_Line} will be called).
4366 Only one call can be present, but of course a special debugging procedure
4367 containing any code you like can be included in the program and then
4368 called in a pragma @code{Debug} argument as needed.
4370 One advantage of pragma @code{Debug} over the @code{if Debugging then}
4371 construct is that pragma @code{Debug} can appear in declarative contexts,
4372 such as at the very beginning of a procedure, before local declarations have
4373 been elaborated.
4375 @geindex pragma Debug_Policy
4377 Debug pragmas are enabled using either the @code{-gnata} switch that also
4378 controls assertions, or with a separate Debug_Policy pragma.
4380 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4381 in Ada 95 and Ada 83 programs as well), and is analogous to
4382 pragma @code{Assertion_Policy} to control assertions.
4384 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
4385 and thus they can appear in @code{gnat.adc} if you are not using a
4386 project file, or in the file designated to contain configuration pragmas
4387 in a project file.
4388 They then apply to all subsequent compilations. In practice the use of
4389 the @code{-gnata} switch is often the most convenient method of controlling
4390 the status of these pragmas.
4392 Note that a pragma is not a statement, so in contexts where a statement
4393 sequence is required, you can't just write a pragma on its own. You have
4394 to add a @code{null} statement.
4396 @example
4397 if ... then
4398    ... -- some statements
4399 else
4400    pragma Assert (Num_Cases < 10);
4401    null;
4402 end if;
4403 @end example
4405 @node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4406 @anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{9f}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{a0}
4407 @subsubsection Conditionalizing Declarations
4410 In some cases it may be necessary to conditionalize declarations to meet
4411 different requirements. For example we might want a bit string whose length
4412 is set to meet some hardware message requirement.
4414 This may be possible using declare blocks controlled
4415 by conditional constants:
4417 @example
4418 if Small_Machine then
4419    declare
4420       X : Bit_String (1 .. 10);
4421    begin
4422       ...
4423    end;
4424 else
4425    declare
4426       X : Large_Bit_String (1 .. 1000);
4427    begin
4428       ...
4429    end;
4430 end if;
4431 @end example
4433 Note that in this approach, both declarations are analyzed by the
4434 compiler so this can only be used where both declarations are legal,
4435 even though one of them will not be used.
4437 Another approach is to define integer constants, e.g., @code{Bits_Per_Word},
4438 or Boolean constants, e.g., @code{Little_Endian}, and then write declarations
4439 that are parameterized by these constants. For example
4441 @example
4442 for Rec use
4443   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4444 end record;
4445 @end example
4447 If @code{Bits_Per_Word} is set to 32, this generates either
4449 @example
4450 for Rec use
4451   Field1 at 0 range 0 .. 32;
4452 end record;
4453 @end example
4455 for the big endian case, or
4457 @example
4458 for Rec use record
4459     Field1 at 0 range 10 .. 32;
4460 end record;
4461 @end example
4463 for the little endian case. Since a powerful subset of Ada expression
4464 notation is usable for creating static constants, clever use of this
4465 feature can often solve quite difficult problems in conditionalizing
4466 compilation (note incidentally that in Ada 95, the little endian
4467 constant was introduced as @code{System.Default_Bit_Order}, so you do not
4468 need to define this one yourself).
4470 @node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4471 @anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{a2}
4472 @subsubsection Use of Alternative Implementations
4475 In some cases, none of the approaches described above are adequate. This
4476 can occur for example if the set of declarations required is radically
4477 different for two different configurations.
4479 In this situation, the official Ada way of dealing with conditionalizing
4480 such code is to write separate units for the different cases. As long as
4481 this does not result in excessive duplication of code, this can be done
4482 without creating maintenance problems. The approach is to share common
4483 code as far as possible, and then isolate the code and declarations
4484 that are different. Subunits are often a convenient method for breaking
4485 out a piece of a unit that is to be conditionalized, with separate files
4486 for different versions of the subunit for different targets, where the
4487 build script selects the right one to give to the compiler.
4489 @geindex Subunits (and conditional compilation)
4491 As an example, consider a situation where a new feature in Ada 2005
4492 allows something to be done in a really nice way. But your code must be able
4493 to compile with an Ada 95 compiler. Conceptually you want to say:
4495 @example
4496 if Ada_2005 then
4497    ... neat Ada 2005 code
4498 else
4499    ... not quite as neat Ada 95 code
4500 end if;
4501 @end example
4503 where @code{Ada_2005} is a Boolean constant.
4505 But this won't work when @code{Ada_2005} is set to @code{False},
4506 since the @code{then} clause will be illegal for an Ada 95 compiler.
4507 (Recall that although such unreachable code would eventually be deleted
4508 by the compiler, it still needs to be legal.  If it uses features
4509 introduced in Ada 2005, it will be illegal in Ada 95.)
4511 So instead we write
4513 @example
4514 procedure Insert is separate;
4515 @end example
4517 Then we have two files for the subunit @code{Insert}, with the two sets of
4518 code.
4519 If the package containing this is called @code{File_Queries}, then we might
4520 have two files
4523 @itemize *
4525 @item 
4526 @code{file_queries-insert-2005.adb}
4528 @item 
4529 @code{file_queries-insert-95.adb}
4530 @end itemize
4532 and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4534 This can also be done with project files' naming schemes. For example:
4536 @example
4537 for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4538 @end example
4540 Note also that with project files it is desirable to use a different extension
4541 than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4542 conflict may arise through another commonly used feature: to declare as part
4543 of the project a set of directories containing all the sources obeying the
4544 default naming scheme.
4546 The use of alternative units is certainly feasible in all situations,
4547 and for example the Ada part of the GNAT run-time is conditionalized
4548 based on the target architecture using this approach. As a specific example,
4549 consider the implementation of the AST feature in VMS. There is one
4550 spec: @code{s-asthan.ads} which is the same for all architectures, and three
4551 bodies:
4554 @itemize *
4556 @item 
4558 @table @asis
4560 @item @code{s-asthan.adb}
4562 used for all non-VMS operating systems
4563 @end table
4565 @item 
4567 @table @asis
4569 @item @code{s-asthan-vms-alpha.adb}
4571 used for VMS on the Alpha
4572 @end table
4574 @item 
4576 @table @asis
4578 @item @code{s-asthan-vms-ia64.adb}
4580 used for VMS on the ia64
4581 @end table
4582 @end itemize
4584 The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4585 this operating system feature is not available, and the two remaining
4586 versions interface with the corresponding versions of VMS to provide
4587 VMS-compatible AST handling. The GNAT build script knows the architecture
4588 and operating system, and automatically selects the right version,
4589 renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4591 Another style for arranging alternative implementations is through Ada's
4592 access-to-subprogram facility.
4593 In case some functionality is to be conditionally included,
4594 you can declare an access-to-procedure variable @code{Ref} that is initialized
4595 to designate a 'do nothing' procedure, and then invoke @code{Ref.all}
4596 when appropriate.
4597 In some library package, set @code{Ref} to @code{Proc'Access} for some
4598 procedure @code{Proc} that performs the relevant processing.
4599 The initialization only occurs if the library package is included in the
4600 program.
4601 The same idea can also be implemented using tagged types and dispatching
4602 calls.
4604 @node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4605 @anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{a3}@anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{a4}
4606 @subsubsection Preprocessing
4609 @geindex Preprocessing
4611 Although it is quite possible to conditionalize code without the use of
4612 C-style preprocessing, as described earlier in this section, it is
4613 nevertheless convenient in some cases to use the C approach. Moreover,
4614 older Ada compilers have often provided some preprocessing capability,
4615 so legacy code may depend on this approach, even though it is not
4616 standard.
4618 To accommodate such use, GNAT provides a preprocessor (modeled to a large
4619 extent on the various preprocessors that have been used
4620 with legacy code on other compilers, to enable easier transition).
4622 @geindex gnatprep
4624 The preprocessor may be used in two separate modes. It can be used quite
4625 separately from the compiler, to generate a separate output source file
4626 that is then fed to the compiler as a separate step. This is the
4627 @code{gnatprep} utility, whose use is fully described in
4628 @ref{17,,Preprocessing with gnatprep}.
4630 The preprocessing language allows such constructs as
4632 @example
4633 #if DEBUG or else (PRIORITY > 4) then
4634    sequence of declarations
4635 #else
4636    completely different sequence of declarations
4637 #end if;
4638 @end example
4640 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
4641 defined either on the command line or in a separate file.
4643 The other way of running the preprocessor is even closer to the C style and
4644 often more convenient. In this approach the preprocessing is integrated into
4645 the compilation process. The compiler is given the preprocessor input which
4646 includes @code{#if} lines etc, and then the compiler carries out the
4647 preprocessing internally and processes the resulting output.
4648 For more details on this approach, see @ref{18,,Integrated Preprocessing}.
4650 @node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4651 @anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{17}
4652 @subsection Preprocessing with @code{gnatprep}
4655 @geindex gnatprep
4657 @geindex Preprocessing (gnatprep)
4659 This section discusses how to use GNAT's @code{gnatprep} utility for simple
4660 preprocessing.
4661 Although designed for use with GNAT, @code{gnatprep} does not depend on any
4662 special GNAT features.
4663 For further discussion of conditional compilation in general, see
4664 @ref{16,,Conditional Compilation}.
4666 @menu
4667 * Preprocessing Symbols:: 
4668 * Using gnatprep:: 
4669 * Switches for gnatprep:: 
4670 * Form of Definitions File:: 
4671 * Form of Input Text for gnatprep:: 
4673 @end menu
4675 @node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4676 @anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{a6}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{a7}
4677 @subsubsection Preprocessing Symbols
4680 Preprocessing symbols are defined in @emph{definition files} and referenced in the
4681 sources to be preprocessed. A preprocessing symbol is an identifier, following
4682 normal Ada (case-insensitive) rules for its syntax, with the restriction that
4683 all characters need to be in the ASCII set (no accented letters).
4685 @node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4686 @anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{a8}@anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{a9}
4687 @subsubsection Using @code{gnatprep}
4690 To call @code{gnatprep} use:
4692 @example
4693 $ gnatprep [ switches ] infile outfile [ deffile ]
4694 @end example
4696 where
4699 @itemize *
4701 @item 
4703 @table @asis
4705 @item @emph{switches}
4707 is an optional sequence of switches as described in the next section.
4708 @end table
4710 @item 
4712 @table @asis
4714 @item @emph{infile}
4716 is the full name of the input file, which is an Ada source
4717 file containing preprocessor directives.
4718 @end table
4720 @item 
4722 @table @asis
4724 @item @emph{outfile}
4726 is the full name of the output file, which is an Ada source
4727 in standard Ada form. When used with GNAT, this file name will
4728 normally have an @code{ads} or @code{adb} suffix.
4729 @end table
4731 @item 
4733 @table @asis
4735 @item @code{deffile}
4737 is the full name of a text file containing definitions of
4738 preprocessing symbols to be referenced by the preprocessor. This argument is
4739 optional, and can be replaced by the use of the @code{-D} switch.
4740 @end table
4741 @end itemize
4743 @node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4744 @anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{aa}@anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{ab}
4745 @subsubsection Switches for @code{gnatprep}
4748 @geindex --version (gnatprep)
4751 @table @asis
4753 @item @code{--version}
4755 Display Copyright and version, then exit disregarding all other options.
4756 @end table
4758 @geindex --help (gnatprep)
4761 @table @asis
4763 @item @code{--help}
4765 If @code{--version} was not used, display usage and then exit disregarding
4766 all other options.
4767 @end table
4769 @geindex -b (gnatprep)
4772 @table @asis
4774 @item @code{-b}
4776 Causes both preprocessor lines and the lines deleted by
4777 preprocessing to be replaced by blank lines in the output source file,
4778 preserving line numbers in the output file.
4779 @end table
4781 @geindex -c (gnatprep)
4784 @table @asis
4786 @item @code{-c}
4788 Causes both preprocessor lines and the lines deleted
4789 by preprocessing to be retained in the output source as comments marked
4790 with the special string @code{"--! "}. This option will result in line numbers
4791 being preserved in the output file.
4792 @end table
4794 @geindex -C (gnatprep)
4797 @table @asis
4799 @item @code{-C}
4801 Causes comments to be scanned. Normally comments are ignored by gnatprep.
4802 If this option is specified, then comments are scanned and any $symbol
4803 substitutions performed as in program text. This is particularly useful
4804 when structured comments are used (e.g., for programs written in a
4805 pre-2014 version of the SPARK Ada subset). Note that this switch is not
4806 available when  doing integrated preprocessing (it would be useless in
4807 this context since comments are ignored by the compiler in any case).
4808 @end table
4810 @geindex -D (gnatprep)
4813 @table @asis
4815 @item @code{-D@emph{symbol}[=@emph{value}]}
4817 Defines a new preprocessing symbol with the specified value. If no value is given
4818 on the command line, then symbol is considered to be @code{True}. This switch
4819 can be used in place of a definition file.
4820 @end table
4822 @geindex -r (gnatprep)
4825 @table @asis
4827 @item @code{-r}
4829 Causes a @code{Source_Reference} pragma to be generated that
4830 references the original input file, so that error messages will use
4831 the file name of this original file. The use of this switch implies
4832 that preprocessor lines are not to be removed from the file, so its
4833 use will force @code{-b} mode if @code{-c}
4834 has not been specified explicitly.
4836 Note that if the file to be preprocessed contains multiple units, then
4837 it will be necessary to @code{gnatchop} the output file from
4838 @code{gnatprep}. If a @code{Source_Reference} pragma is present
4839 in the preprocessed file, it will be respected by
4840 @code{gnatchop -r}
4841 so that the final chopped files will correctly refer to the original
4842 input source file for @code{gnatprep}.
4843 @end table
4845 @geindex -s (gnatprep)
4848 @table @asis
4850 @item @code{-s}
4852 Causes a sorted list of symbol names and values to be
4853 listed on the standard output file.
4854 @end table
4856 @geindex -T (gnatprep)
4859 @table @asis
4861 @item @code{-T}
4863 Use LF as line terminators when writing files. By default the line terminator
4864 of the host (LF under unix, CR/LF under Windows) is used.
4865 @end table
4867 @geindex -u (gnatprep)
4870 @table @asis
4872 @item @code{-u}
4874 Causes undefined symbols to be treated as having the value FALSE in the context
4875 of a preprocessor test. In the absence of this option, an undefined symbol in
4876 a @code{#if} or @code{#elsif} test will be treated as an error.
4877 @end table
4879 @geindex -v (gnatprep)
4882 @table @asis
4884 @item @code{-v}
4886 Verbose mode: generates more output about work done.
4887 @end table
4889 Note: if neither @code{-b} nor @code{-c} is present,
4890 then preprocessor lines and
4891 deleted lines are completely removed from the output, unless -r is
4892 specified, in which case -b is assumed.
4894 @node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4895 @anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{ad}
4896 @subsubsection Form of Definitions File
4899 The definitions file contains lines of the form:
4901 @example
4902 symbol := value
4903 @end example
4905 where @code{symbol} is a preprocessing symbol, and @code{value} is one of the following:
4908 @itemize *
4910 @item 
4911 Empty, corresponding to a null substitution,
4913 @item 
4914 A string literal using normal Ada syntax, or
4916 @item 
4917 Any sequence of characters from the set @{letters, digits, period, underline@}.
4918 @end itemize
4920 Comment lines may also appear in the definitions file, starting with
4921 the usual @code{--},
4922 and comments may be added to the definitions lines.
4924 @node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4925 @anchor{gnat_ugn/the_gnat_compilation_model id59}@anchor{ae}@anchor{gnat_ugn/the_gnat_compilation_model form-of-input-text-for-gnatprep}@anchor{af}
4926 @subsubsection Form of Input Text for @code{gnatprep}
4929 The input text may contain preprocessor conditional inclusion lines,
4930 as well as general symbol substitution sequences.
4932 The preprocessor conditional inclusion commands have the form:
4934 @example
4935 #if <expression> [then]
4936    lines
4937 #elsif <expression> [then]
4938    lines
4939 #elsif <expression> [then]
4940    lines
4942 #else
4943    lines
4944 #end if;
4945 @end example
4947 In this example, <expression> is defined by the following grammar:
4949 @example
4950 <expression> ::=  <symbol>
4951 <expression> ::=  <symbol> = "<value>"
4952 <expression> ::=  <symbol> = <symbol>
4953 <expression> ::=  <symbol> = <integer>
4954 <expression> ::=  <symbol> > <integer>
4955 <expression> ::=  <symbol> >= <integer>
4956 <expression> ::=  <symbol> < <integer>
4957 <expression> ::=  <symbol> <= <integer>
4958 <expression> ::=  <symbol> 'Defined
4959 <expression> ::=  not <expression>
4960 <expression> ::=  <expression> and <expression>
4961 <expression> ::=  <expression> or <expression>
4962 <expression> ::=  <expression> and then <expression>
4963 <expression> ::=  <expression> or else <expression>
4964 <expression> ::=  ( <expression> )
4965 @end example
4967 Note the following restriction: it is not allowed to have "and" or "or"
4968 following "not" in the same expression without parentheses. For example, this
4969 is not allowed:
4971 @example
4972 not X or Y
4973 @end example
4975 This can be expressed instead as one of the following forms:
4977 @example
4978 (not X) or Y
4979 not (X or Y)
4980 @end example
4982 For the first test (<expression> ::= <symbol>) the symbol must have
4983 either the value true or false, that is to say the right-hand of the
4984 symbol definition must be one of the (case-insensitive) literals
4985 @code{True} or @code{False}. If the value is true, then the
4986 corresponding lines are included, and if the value is false, they are
4987 excluded.
4989 When comparing a symbol to an integer, the integer is any non negative
4990 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
4991 2#11#. The symbol value must also be a non negative integer. Integer values
4992 in the range 0 .. 2**31-1 are supported.
4994 The test (<expression> ::= <symbol>'Defined) is true only if
4995 the symbol has been defined in the definition file or by a @code{-D}
4996 switch on the command line. Otherwise, the test is false.
4998 The equality tests are case insensitive, as are all the preprocessor lines.
5000 If the symbol referenced is not defined in the symbol definitions file,
5001 then the effect depends on whether or not switch @code{-u}
5002 is specified. If so, then the symbol is treated as if it had the value
5003 false and the test fails. If this switch is not specified, then
5004 it is an error to reference an undefined symbol. It is also an error to
5005 reference a symbol that is defined with a value other than @code{True}
5006 or @code{False}.
5008 The use of the @code{not} operator inverts the sense of this logical test.
5009 The @code{not} operator cannot be combined with the @code{or} or @code{and}
5010 operators, without parentheses. For example, "if not X or Y then" is not
5011 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
5013 The @code{then} keyword is optional as shown
5015 The @code{#} must be the first non-blank character on a line, but
5016 otherwise the format is free form. Spaces or tabs may appear between
5017 the @code{#} and the keyword. The keywords and the symbols are case
5018 insensitive as in normal Ada code. Comments may be used on a
5019 preprocessor line, but other than that, no other tokens may appear on a
5020 preprocessor line. Any number of @code{elsif} clauses can be present,
5021 including none at all. The @code{else} is optional, as in Ada.
5023 The @code{#} marking the start of a preprocessor line must be the first
5024 non-blank character on the line, i.e., it must be preceded only by
5025 spaces or horizontal tabs.
5027 Symbol substitution outside of preprocessor lines is obtained by using
5028 the sequence:
5030 @example
5031 $symbol
5032 @end example
5034 anywhere within a source line, except in a comment or within a
5035 string literal. The identifier
5036 following the @code{$} must match one of the symbols defined in the symbol
5037 definition file, and the result is to substitute the value of the
5038 symbol in place of @code{$symbol} in the output file.
5040 Note that although the substitution of strings within a string literal
5041 is not possible, it is possible to have a symbol whose defined value is
5042 a string literal. So instead of setting XYZ to @code{hello} and writing:
5044 @example
5045 Header : String := "$XYZ";
5046 @end example
5048 you should set XYZ to @code{"hello"} and write:
5050 @example
5051 Header : String := $XYZ;
5052 @end example
5054 and then the substitution will occur as desired.
5056 @node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
5057 @anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{b0}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{18}
5058 @subsection Integrated Preprocessing
5061 As noted above, a file to be preprocessed consists of Ada source code
5062 in which preprocessing lines have been inserted. However,
5063 instead of using @code{gnatprep} to explicitly preprocess a file as a separate
5064 step before compilation, you can carry out the preprocessing implicitly
5065 as part of compilation. Such @emph{integrated preprocessing}, which is the common
5066 style with C, is performed when either or both of the following switches
5067 are passed to the compiler:
5069 @quotation
5072 @itemize *
5074 @item 
5075 @code{-gnatep}, which specifies the @emph{preprocessor data file}.
5076 This file dictates how the source files will be preprocessed (e.g., which
5077 symbol definition files apply to which sources).
5079 @item 
5080 @code{-gnateD}, which defines values for preprocessing symbols.
5081 @end itemize
5082 @end quotation
5084 Integrated preprocessing applies only to Ada source files, it is
5085 not available for configuration pragma files.
5087 With integrated preprocessing, the output from the preprocessor is not,
5088 by default, written to any external file. Instead it is passed
5089 internally to the compiler. To preserve the result of
5090 preprocessing in a file, either run @code{gnatprep}
5091 in standalone mode or else supply the @code{-gnateG} switch
5092 (described below) to the compiler.
5094 When using project files:
5096 @quotation
5099 @itemize *
5101 @item 
5102 the builder switch @code{-x} should be used if any Ada source is
5103 compiled with @code{gnatep=}, so that the compiler finds the
5104 @emph{preprocessor data file}.
5106 @item 
5107 the preprocessing data file and the symbol definition files should be
5108 located in the source directories of the project.
5109 @end itemize
5110 @end quotation
5112 Note that the @code{gnatmake} switch @code{-m} will almost
5113 always trigger recompilation for sources that are preprocessed,
5114 because @code{gnatmake} cannot compute the checksum of the source after
5115 preprocessing.
5117 The actual preprocessing function is described in detail in
5118 @ref{17,,Preprocessing with gnatprep}. This section explains the switches
5119 that relate to integrated preprocessing.
5121 @geindex -gnatep (gcc)
5124 @table @asis
5126 @item @code{-gnatep=@emph{preprocessor_data_file}}
5128 This switch specifies the file name (without directory
5129 information) of the preprocessor data file. Either place this file
5130 in one of the source directories, or, when using project
5131 files, reference the project file's directory via the
5132 @code{project_name'Project_Dir} project attribute; e.g:
5134 @quotation
5136 @example
5137 project Prj is
5138    package Compiler is
5139       for Switches ("Ada") use
5140         ("-gnatep=" & Prj'Project_Dir & "prep.def");
5141    end Compiler;
5142 end Prj;
5143 @end example
5144 @end quotation
5146 A preprocessor data file is a text file that contains @emph{preprocessor
5147 control lines}.  A preprocessor control line directs the preprocessing of
5148 either a particular source file, or, analogous to @code{others} in Ada,
5149 all sources not specified elsewhere in  the preprocessor data file.
5150 A preprocessor control line
5151 can optionally identify a @emph{definition file} that assigns values to
5152 preprocessor symbols, as well as a list of switches that relate to
5153 preprocessing.
5154 Empty lines and comments (using Ada syntax) are also permitted, with no
5155 semantic effect.
5157 Here's an example of a preprocessor data file:
5159 @quotation
5161 @example
5162 "toto.adb"  "prep.def" -u
5163 --  Preprocess toto.adb, using definition file prep.def
5164 --  Undefined symbols are treated as False
5166 * -c -DVERSION=V101
5167 --  Preprocess all other sources without using a definition file
5168 --  Suppressed lined are commented
5169 --  Symbol VERSION has the value V101
5171 "tata.adb" "prep2.def" -s
5172 --  Preprocess tata.adb, using definition file prep2.def
5173 --  List all symbols with their values
5174 @end example
5175 @end quotation
5177 A preprocessor control line has the following syntax:
5179 @quotation
5181 @example
5182 <preprocessor_control_line> ::=
5183    <preprocessor_input> [ <definition_file_name> ] @{ <switch> @}
5185 <preprocessor_input> ::= <source_file_name> | '*'
5187 <definition_file_name> ::= <string_literal>
5189 <source_file_name> := <string_literal>
5191 <switch> := (See below for list)
5192 @end example
5193 @end quotation
5195 Thus  each preprocessor control line starts with either a literal string or
5196 the character '*':
5199 @itemize *
5201 @item 
5202 A literal string is the file name (without directory information) of the source
5203 file that will be input to the preprocessor.
5205 @item 
5206 The character '*' is a wild-card indicator; the additional parameters on the line
5207 indicate the preprocessing for all the sources
5208 that are not specified explicitly on other lines (the order of the lines is not
5209 significant).
5210 @end itemize
5212 It is an error to have two lines with the same file name or two
5213 lines starting with the character '*'.
5215 After the file name or '*', an optional literal string specifies the name of
5216 the definition file to be used for preprocessing
5217 (@ref{ac,,Form of Definitions File}). The definition files are found by the
5218 compiler in one of the source directories. In some cases, when compiling
5219 a source in a directory other than the current directory, if the definition
5220 file is in the current directory, it may be necessary to add the current
5221 directory as a source directory through the @code{-I} switch; otherwise
5222 the compiler would not find the definition file.
5224 Finally, switches similar to those of @code{gnatprep} may optionally appear:
5227 @table @asis
5229 @item @code{-b}
5231 Causes both preprocessor lines and the lines deleted by
5232 preprocessing to be replaced by blank lines, preserving the line number.
5233 This switch is always implied; however, if specified after @code{-c}
5234 it cancels the effect of @code{-c}.
5236 @item @code{-c}
5238 Causes both preprocessor lines and the lines deleted
5239 by preprocessing to be retained as comments marked
5240 with the special string '@cite{--!}'.
5242 @item @code{-D@emph{symbol}=@emph{new_value}}
5244 Define or redefine @code{symbol} to have @code{new_value} as its value.
5245 The permitted form for @code{symbol} is either an Ada identifier, or any Ada reserved word
5246 aside from @code{if},
5247 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5248 The permitted form for @code{new_value} is a literal string, an Ada identifier or any Ada reserved
5249 word. A symbol declared with this switch replaces a symbol with the
5250 same name defined in a definition file.
5252 @item @code{-s}
5254 Causes a sorted list of symbol names and values to be
5255 listed on the standard output file.
5257 @item @code{-u}
5259 Causes undefined symbols to be treated as having the value @code{FALSE}
5260 in the context
5261 of a preprocessor test. In the absence of this option, an undefined symbol in
5262 a @code{#if} or @code{#elsif} test will be treated as an error.
5263 @end table
5264 @end table
5266 @geindex -gnateD (gcc)
5269 @table @asis
5271 @item @code{-gnateD@emph{symbol}[=@emph{new_value}]}
5273 Define or redefine @code{symbol} to have @code{new_value} as its value. If no value
5274 is supplied, then the value of @code{symbol} is @code{True}.
5275 The form of @code{symbol} is an identifier, following normal Ada (case-insensitive)
5276 rules for its syntax, and @code{new_value} is either an arbitrary string between double
5277 quotes or any sequence (including an empty sequence) of characters from the
5278 set (letters, digits, period, underline).
5279 Ada reserved words may be used as symbols, with the exceptions of @code{if},
5280 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5282 Examples:
5284 @quotation
5286 @example
5287 -gnateDToto=Tata
5288 -gnateDFoo
5289 -gnateDFoo=\"Foo-Bar\"
5290 @end example
5291 @end quotation
5293 A symbol declared with this switch on the command line replaces a
5294 symbol with the same name either in a definition file or specified with a
5295 switch @code{-D} in the preprocessor data file.
5297 This switch is similar to switch @code{-D} of @code{gnatprep}.
5299 @item @code{-gnateG}
5301 When integrated preprocessing is performed on source file @code{filename.extension},
5302 create or overwrite @code{filename.extension.prep} to contain
5303 the result of the preprocessing.
5304 For example if the source file is @code{foo.adb} then
5305 the output file will be @code{foo.adb.prep}.
5306 @end table
5308 @node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5309 @anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{44}@anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{b1}
5310 @section Mixed Language Programming
5313 @geindex Mixed Language Programming
5315 This section describes how to develop a mixed-language program,
5316 with a focus on combining Ada with C or C++.
5318 @menu
5319 * Interfacing to C:: 
5320 * Calling Conventions:: 
5321 * Building Mixed Ada and C++ Programs:: 
5322 * Generating Ada Bindings for C and C++ headers:: 
5323 * Generating C Headers for Ada Specifications:: 
5325 @end menu
5327 @node Interfacing to C,Calling Conventions,,Mixed Language Programming
5328 @anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{b2}@anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{b3}
5329 @subsection Interfacing to C
5332 Interfacing Ada with a foreign language such as C involves using
5333 compiler directives to import and/or export entity definitions in each
5334 language -- using @code{extern} statements in C, for instance, and the
5335 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
5336 A full treatment of these topics is provided in Appendix B, section 1
5337 of the Ada Reference Manual.
5339 There are two ways to build a program using GNAT that contains some Ada
5340 sources and some foreign language sources, depending on whether or not
5341 the main subprogram is written in Ada.  Here is a source example with
5342 the main subprogram in Ada:
5344 @example
5345 /* file1.c */
5346 #include <stdio.h>
5348 void print_num (int num)
5350   printf ("num is %d.\\n", num);
5351   return;
5353 @end example
5355 @example
5356 /* file2.c */
5358 /* num_from_Ada is declared in my_main.adb */
5359 extern int num_from_Ada;
5361 int get_num (void)
5363   return num_from_Ada;
5365 @end example
5367 @example
5368 --  my_main.adb
5369 procedure My_Main is
5371    --  Declare then export an Integer entity called num_from_Ada
5372    My_Num : Integer := 10;
5373    pragma Export (C, My_Num, "num_from_Ada");
5375    --  Declare an Ada function spec for Get_Num, then use
5376    --  C function get_num for the implementation.
5377    function Get_Num return Integer;
5378    pragma Import (C, Get_Num, "get_num");
5380    --  Declare an Ada procedure spec for Print_Num, then use
5381    --  C function print_num for the implementation.
5382    procedure Print_Num (Num : Integer);
5383    pragma Import (C, Print_Num, "print_num");
5385 begin
5386    Print_Num (Get_Num);
5387 end My_Main;
5388 @end example
5390 To build this example:
5393 @itemize *
5395 @item 
5396 First compile the foreign language files to
5397 generate object files:
5399 @example
5400 $ gcc -c file1.c
5401 $ gcc -c file2.c
5402 @end example
5404 @item 
5405 Then, compile the Ada units to produce a set of object files and ALI
5406 files:
5408 @example
5409 $ gnatmake -c my_main.adb
5410 @end example
5412 @item 
5413 Run the Ada binder on the Ada main program:
5415 @example
5416 $ gnatbind my_main.ali
5417 @end example
5419 @item 
5420 Link the Ada main program, the Ada objects and the other language
5421 objects:
5423 @example
5424 $ gnatlink my_main.ali file1.o file2.o
5425 @end example
5426 @end itemize
5428 The last three steps can be grouped in a single command:
5430 @example
5431 $ gnatmake my_main.adb -largs file1.o file2.o
5432 @end example
5434 @geindex Binder output file
5436 If the main program is in a language other than Ada, then you may have
5437 more than one entry point into the Ada subsystem. You must use a special
5438 binder option to generate callable routines that initialize and
5439 finalize the Ada units (@ref{b4,,Binding with Non-Ada Main Programs}).
5440 Calls to the initialization and finalization routines must be inserted
5441 in the main program, or some other appropriate point in the code. The
5442 call to initialize the Ada units must occur before the first Ada
5443 subprogram is called, and the call to finalize the Ada units must occur
5444 after the last Ada subprogram returns. The binder will place the
5445 initialization and finalization subprograms into the
5446 @code{b~xxx.adb} file where they can be accessed by your C
5447 sources.  To illustrate, we have the following example:
5449 @example
5450 /* main.c */
5451 extern void adainit (void);
5452 extern void adafinal (void);
5453 extern int add (int, int);
5454 extern int sub (int, int);
5456 int main (int argc, char *argv[])
5458    int a = 21, b = 7;
5460    adainit();
5462    /* Should print "21 + 7 = 28" */
5463    printf ("%d + %d = %d\\n", a, b, add (a, b));
5465    /* Should print "21 - 7 = 14" */
5466    printf ("%d - %d = %d\\n", a, b, sub (a, b));
5468    adafinal();
5470 @end example
5472 @example
5473 --  unit1.ads
5474 package Unit1 is
5475    function Add (A, B : Integer) return Integer;
5476    pragma Export (C, Add, "add");
5477 end Unit1;
5478 @end example
5480 @example
5481 --  unit1.adb
5482 package body Unit1 is
5483    function Add (A, B : Integer) return Integer is
5484    begin
5485       return A + B;
5486    end Add;
5487 end Unit1;
5488 @end example
5490 @example
5491 --  unit2.ads
5492 package Unit2 is
5493    function Sub (A, B : Integer) return Integer;
5494    pragma Export (C, Sub, "sub");
5495 end Unit2;
5496 @end example
5498 @example
5499 --  unit2.adb
5500 package body Unit2 is
5501    function Sub (A, B : Integer) return Integer is
5502    begin
5503       return A - B;
5504    end Sub;
5505 end Unit2;
5506 @end example
5508 The build procedure for this application is similar to the last
5509 example's:
5512 @itemize *
5514 @item 
5515 First, compile the foreign language files to generate object files:
5517 @example
5518 $ gcc -c main.c
5519 @end example
5521 @item 
5522 Next, compile the Ada units to produce a set of object files and ALI
5523 files:
5525 @example
5526 $ gnatmake -c unit1.adb
5527 $ gnatmake -c unit2.adb
5528 @end example
5530 @item 
5531 Run the Ada binder on every generated ALI file.  Make sure to use the
5532 @code{-n} option to specify a foreign main program:
5534 @example
5535 $ gnatbind -n unit1.ali unit2.ali
5536 @end example
5538 @item 
5539 Link the Ada main program, the Ada objects and the foreign language
5540 objects. You need only list the last ALI file here:
5542 @example
5543 $ gnatlink unit2.ali main.o -o exec_file
5544 @end example
5546 This procedure yields a binary executable called @code{exec_file}.
5547 @end itemize
5549 Depending on the circumstances (for example when your non-Ada main object
5550 does not provide symbol @code{main}), you may also need to instruct the
5551 GNAT linker not to include the standard startup objects by passing the
5552 @code{-nostartfiles} switch to @code{gnatlink}.
5554 @node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5555 @anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{b5}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{b6}
5556 @subsection Calling Conventions
5559 @geindex Foreign Languages
5561 @geindex Calling Conventions
5563 GNAT follows standard calling sequence conventions and will thus interface
5564 to any other language that also follows these conventions. The following
5565 Convention identifiers are recognized by GNAT:
5567 @geindex Interfacing to Ada
5569 @geindex Other Ada compilers
5571 @geindex Convention Ada
5574 @table @asis
5576 @item @code{Ada}
5578 This indicates that the standard Ada calling sequence will be
5579 used and all Ada data items may be passed without any limitations in the
5580 case where GNAT is used to generate both the caller and callee. It is also
5581 possible to mix GNAT generated code and code generated by another Ada
5582 compiler. In this case, the data types should be restricted to simple
5583 cases, including primitive types. Whether complex data types can be passed
5584 depends on the situation. Probably it is safe to pass simple arrays, such
5585 as arrays of integers or floats. Records may or may not work, depending
5586 on whether both compilers lay them out identically. Complex structures
5587 involving variant records, access parameters, tasks, or protected types,
5588 are unlikely to be able to be passed.
5590 Note that in the case of GNAT running
5591 on a platform that supports HP Ada 83, a higher degree of compatibility
5592 can be guaranteed, and in particular records are laid out in an identical
5593 manner in the two compilers. Note also that if output from two different
5594 compilers is mixed, the program is responsible for dealing with elaboration
5595 issues. Probably the safest approach is to write the main program in the
5596 version of Ada other than GNAT, so that it takes care of its own elaboration
5597 requirements, and then call the GNAT-generated adainit procedure to ensure
5598 elaboration of the GNAT components. Consult the documentation of the other
5599 Ada compiler for further details on elaboration.
5601 However, it is not possible to mix the tasking run time of GNAT and
5602 HP Ada 83, All the tasking operations must either be entirely within
5603 GNAT compiled sections of the program, or entirely within HP Ada 83
5604 compiled sections of the program.
5605 @end table
5607 @geindex Interfacing to Assembly
5609 @geindex Convention Assembler
5612 @table @asis
5614 @item @code{Assembler}
5616 Specifies assembler as the convention. In practice this has the
5617 same effect as convention Ada (but is not equivalent in the sense of being
5618 considered the same convention).
5619 @end table
5621 @geindex Convention Asm
5623 @geindex Asm
5626 @table @asis
5628 @item @code{Asm}
5630 Equivalent to Assembler.
5632 @geindex Interfacing to COBOL
5634 @geindex Convention COBOL
5635 @end table
5637 @geindex COBOL
5640 @table @asis
5642 @item @code{COBOL}
5644 Data will be passed according to the conventions described
5645 in section B.4 of the Ada Reference Manual.
5646 @end table
5648 @geindex C
5650 @geindex Interfacing to C
5652 @geindex Convention C
5655 @table @asis
5657 @item @code{C}
5659 Data will be passed according to the conventions described
5660 in section B.3 of the Ada Reference Manual.
5662 A note on interfacing to a C 'varargs' function:
5664 @quotation
5666 @geindex C varargs function
5668 @geindex Interfacing to C varargs function
5670 @geindex varargs function interfaces
5672 In C, @code{varargs} allows a function to take a variable number of
5673 arguments. There is no direct equivalent in this to Ada. One
5674 approach that can be used is to create a C wrapper for each
5675 different profile and then interface to this C wrapper. For
5676 example, to print an @code{int} value using @code{printf},
5677 create a C function @code{printfi} that takes two arguments, a
5678 pointer to a string and an int, and calls @code{printf}.
5679 Then in the Ada program, use pragma @code{Import} to
5680 interface to @code{printfi}.
5682 It may work on some platforms to directly interface to
5683 a @code{varargs} function by providing a specific Ada profile
5684 for a particular call. However, this does not work on
5685 all platforms, since there is no guarantee that the
5686 calling sequence for a two argument normal C function
5687 is the same as for calling a @code{varargs} C function with
5688 the same two arguments.
5689 @end quotation
5690 @end table
5692 @geindex Convention Default
5694 @geindex Default
5697 @table @asis
5699 @item @code{Default}
5701 Equivalent to C.
5702 @end table
5704 @geindex Convention External
5706 @geindex External
5709 @table @asis
5711 @item @code{External}
5713 Equivalent to C.
5714 @end table
5716 @geindex C++
5718 @geindex Interfacing to C++
5720 @geindex Convention C++
5723 @table @asis
5725 @item @code{C_Plus_Plus} (or @code{CPP})
5727 This stands for C++. For most purposes this is identical to C.
5728 See the separate description of the specialized GNAT pragmas relating to
5729 C++ interfacing for further details.
5730 @end table
5732 @geindex Fortran
5734 @geindex Interfacing to Fortran
5736 @geindex Convention Fortran
5739 @table @asis
5741 @item @code{Fortran}
5743 Data will be passed according to the conventions described
5744 in section B.5 of the Ada Reference Manual.
5746 @item @code{Intrinsic}
5748 This applies to an intrinsic operation, as defined in the Ada
5749 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5750 this means that the body of the subprogram is provided by the compiler itself,
5751 usually by means of an efficient code sequence, and that the user does not
5752 supply an explicit body for it. In an application program, the pragma may
5753 be applied to the following sets of names:
5756 @itemize *
5758 @item 
5759 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5760 The corresponding subprogram declaration must have
5761 two formal parameters. The
5762 first one must be a signed integer type or a modular type with a binary
5763 modulus, and the second parameter must be of type Natural.
5764 The return type must be the same as the type of the first argument. The size
5765 of this type can only be 8, 16, 32, or 64.
5767 @item 
5768 Binary arithmetic operators: '+', '-', '*', '/'.
5769 The corresponding operator declaration must have parameters and result type
5770 that have the same root numeric type (for example, all three are long_float
5771 types). This simplifies the definition of operations that use type checking
5772 to perform dimensional checks:
5773 @end itemize
5775 @example
5776   type Distance is new Long_Float;
5777   type Time     is new Long_Float;
5778   type Velocity is new Long_Float;
5779   function "/" (D : Distance; T : Time)
5780     return Velocity;
5781   pragma Import (Intrinsic, "/");
5783 This common idiom is often programmed with a generic definition and an
5784 explicit body. The pragma makes it simpler to introduce such declarations.
5785 It incurs no overhead in compilation time or code size, because it is
5786 implemented as a single machine instruction.
5787 @end example
5790 @itemize *
5792 @item 
5793 General subprogram entities. This is used  to bind an Ada subprogram
5794 declaration to
5795 a compiler builtin by name with back-ends where such interfaces are
5796 available. A typical example is the set of @code{__builtin} functions
5797 exposed by the GCC back-end, as in the following example:
5799 @example
5800 function builtin_sqrt (F : Float) return Float;
5801 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5802 @end example
5804 Most of the GCC builtins are accessible this way, and as for other
5805 import conventions (e.g. C), it is the user's responsibility to ensure
5806 that the Ada subprogram profile matches the underlying builtin
5807 expectations.
5808 @end itemize
5809 @end table
5811 @geindex Stdcall
5813 @geindex Convention Stdcall
5816 @table @asis
5818 @item @code{Stdcall}
5820 This is relevant only to Windows implementations of GNAT,
5821 and specifies that the @code{Stdcall} calling sequence will be used,
5822 as defined by the NT API. Nevertheless, to ease building
5823 cross-platform bindings this convention will be handled as a @code{C} calling
5824 convention on non-Windows platforms.
5825 @end table
5827 @geindex DLL
5829 @geindex Convention DLL
5832 @table @asis
5834 @item @code{DLL}
5836 This is equivalent to @code{Stdcall}.
5837 @end table
5839 @geindex Win32
5841 @geindex Convention Win32
5844 @table @asis
5846 @item @code{Win32}
5848 This is equivalent to @code{Stdcall}.
5849 @end table
5851 @geindex Stubbed
5853 @geindex Convention Stubbed
5856 @table @asis
5858 @item @code{Stubbed}
5860 This is a special convention that indicates that the compiler
5861 should provide a stub body that raises @code{Program_Error}.
5862 @end table
5864 GNAT additionally provides a useful pragma @code{Convention_Identifier}
5865 that can be used to parameterize conventions and allow additional synonyms
5866 to be specified. For example if you have legacy code in which the convention
5867 identifier Fortran77 was used for Fortran, you can use the configuration
5868 pragma:
5870 @example
5871 pragma Convention_Identifier (Fortran77, Fortran);
5872 @end example
5874 And from now on the identifier Fortran77 may be used as a convention
5875 identifier (for example in an @code{Import} pragma) with the same
5876 meaning as Fortran.
5878 @node Building Mixed Ada and C++ Programs,Generating Ada Bindings for C and C++ headers,Calling Conventions,Mixed Language Programming
5879 @anchor{gnat_ugn/the_gnat_compilation_model id64}@anchor{b7}@anchor{gnat_ugn/the_gnat_compilation_model building-mixed-ada-and-c-programs}@anchor{b8}
5880 @subsection Building Mixed Ada and C++ Programs
5883 A programmer inexperienced with mixed-language development may find that
5884 building an application containing both Ada and C++ code can be a
5885 challenge.  This section gives a few hints that should make this task easier.
5887 @menu
5888 * Interfacing to C++:: 
5889 * Linking a Mixed C++ & Ada Program:: 
5890 * A Simple Example:: 
5891 * Interfacing with C++ constructors:: 
5892 * Interfacing with C++ at the Class Level:: 
5894 @end menu
5896 @node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5897 @anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{b9}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{ba}
5898 @subsubsection Interfacing to C++
5901 GNAT supports interfacing with the G++ compiler (or any C++ compiler
5902 generating code that is compatible with the G++ Application Binary
5903 Interface ---see @indicateurl{http://www.codesourcery.com/archives/cxx-abi}).
5905 Interfacing can be done at 3 levels: simple data, subprograms, and
5906 classes. In the first two cases, GNAT offers a specific @code{Convention C_Plus_Plus}
5907 (or @code{CPP}) that behaves exactly like @code{Convention C}.
5908 Usually, C++ mangles the names of subprograms. To generate proper mangled
5909 names automatically, see @ref{19,,Generating Ada Bindings for C and C++ headers}).
5910 This problem can also be addressed manually in two ways:
5913 @itemize *
5915 @item 
5916 by modifying the C++ code in order to force a C convention using
5917 the @code{extern "C"} syntax.
5919 @item 
5920 by figuring out the mangled name (using e.g. @code{nm}) and using it as the
5921 Link_Name argument of the pragma import.
5922 @end itemize
5924 Interfacing at the class level can be achieved by using the GNAT specific
5925 pragmas such as @code{CPP_Constructor}.  See the @cite{GNAT_Reference_Manual} for additional information.
5927 @node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5928 @anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-ada-program}@anchor{bb}@anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-and-ada-program}@anchor{bc}
5929 @subsubsection Linking a Mixed C++ & Ada Program
5932 Usually the linker of the C++ development system must be used to link
5933 mixed applications because most C++ systems will resolve elaboration
5934 issues (such as calling constructors on global class instances)
5935 transparently during the link phase. GNAT has been adapted to ease the
5936 use of a foreign linker for the last phase. Three cases can be
5937 considered:
5940 @itemize *
5942 @item 
5943 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5944 The C++ linker can simply be called by using the C++ specific driver
5945 called @code{g++}.
5947 Note that if the C++ code uses inline functions, you will need to
5948 compile your C++ code with the @code{-fkeep-inline-functions} switch in
5949 order to provide an existing function implementation that the Ada code can
5950 link with.
5952 @example
5953 $ g++ -c -fkeep-inline-functions file1.C
5954 $ g++ -c -fkeep-inline-functions file2.C
5955 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5956 @end example
5958 @item 
5959 Using GNAT and G++ from two different GCC installations: If both
5960 compilers are on the :envvar`PATH`, the previous method may be used. It is
5961 important to note that environment variables such as
5962 @geindex C_INCLUDE_PATH
5963 @geindex environment variable; C_INCLUDE_PATH
5964 @code{C_INCLUDE_PATH}, 
5965 @geindex GCC_EXEC_PREFIX
5966 @geindex environment variable; GCC_EXEC_PREFIX
5967 @code{GCC_EXEC_PREFIX},
5968 @geindex BINUTILS_ROOT
5969 @geindex environment variable; BINUTILS_ROOT
5970 @code{BINUTILS_ROOT}, and
5971 @geindex GCC_ROOT
5972 @geindex environment variable; GCC_ROOT
5973 @code{GCC_ROOT} will affect both compilers
5974 at the same time and may make one of the two compilers operate
5975 improperly if set during invocation of the wrong compiler.  It is also
5976 very important that the linker uses the proper @code{libgcc.a} GCC
5977 library -- that is, the one from the C++ compiler installation. The
5978 implicit link command as suggested in the @code{gnatmake} command
5979 from the former example can be replaced by an explicit link command with
5980 the full-verbosity option in order to verify which library is used:
5982 @example
5983 $ gnatbind ada_unit
5984 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5985 @end example
5987 If there is a problem due to interfering environment variables, it can
5988 be worked around by using an intermediate script. The following example
5989 shows the proper script to use when GNAT has not been installed at its
5990 default location and g++ has been installed at its default location:
5992 @example
5993 $ cat ./my_script
5994 #!/bin/sh
5995 unset BINUTILS_ROOT
5996 unset GCC_ROOT
5997 c++ $*
5998 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5999 @end example
6001 @item 
6002 Using a non-GNU C++ compiler: The commands previously described can be
6003 used to insure that the C++ linker is used. Nonetheless, you need to add
6004 a few more parameters to the link command line, depending on the exception
6005 mechanism used.
6007 If the @code{setjmp} / @code{longjmp} exception mechanism is used, only the paths
6008 to the @code{libgcc} libraries are required:
6010 @example
6011 $ cat ./my_script
6012 #!/bin/sh
6013 CC $* gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a
6014 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
6015 @end example
6017 where CC is the name of the non-GNU C++ compiler.
6019 If the "zero cost" exception mechanism is used, and the platform
6020 supports automatic registration of exception tables (e.g., Solaris),
6021 paths to more objects are required:
6023 @example
6024 $ cat ./my_script
6025 #!/bin/sh
6026 CC gcc -print-file-name=crtbegin.o $* \\
6027 gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a \\
6028 gcc -print-file-name=crtend.o
6029 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
6030 @end example
6032 If the "zero cost exception" mechanism is used, and the platform
6033 doesn't support automatic registration of exception tables (e.g., HP-UX
6034 or AIX), the simple approach described above will not work and
6035 a pre-linking phase using GNAT will be necessary.
6036 @end itemize
6038 Another alternative is to use the @code{gprbuild} multi-language builder
6039 which has a large knowledge base and knows how to link Ada and C++ code
6040 together automatically in most cases.
6042 @node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
6043 @anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{bd}@anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{be}
6044 @subsubsection A Simple Example
6047 The following example, provided as part of the GNAT examples, shows how
6048 to achieve procedural interfacing between Ada and C++ in both
6049 directions. The C++ class A has two methods. The first method is exported
6050 to Ada by the means of an extern C wrapper function. The second method
6051 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
6052 a limited record with a layout comparable to the C++ class. The Ada
6053 subprogram, in turn, calls the C++ method. So, starting from the C++
6054 main program, the process passes back and forth between the two
6055 languages.
6057 Here are the compilation commands:
6059 @example
6060 $ gnatmake -c simple_cpp_interface
6061 $ g++ -c cpp_main.C
6062 $ g++ -c ex7.C
6063 $ gnatbind -n simple_cpp_interface
6064 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
6065 @end example
6067 Here are the corresponding sources:
6069 @example
6070 //cpp_main.C
6072 #include "ex7.h"
6074 extern "C" @{
6075   void adainit (void);
6076   void adafinal (void);
6077   void method1 (A *t);
6080 void method1 (A *t)
6082   t->method1 ();
6085 int main ()
6087   A obj;
6088   adainit ();
6089   obj.method2 (3030);
6090   adafinal ();
6092 @end example
6094 @example
6095 //ex7.h
6097 class Origin @{
6098  public:
6099   int o_value;
6101 class A : public Origin @{
6102  public:
6103   void method1 (void);
6104   void method2 (int v);
6105   A();
6106   int   a_value;
6108 @end example
6110 @example
6111 //ex7.C
6113 #include "ex7.h"
6114 #include <stdio.h>
6116 extern "C" @{ void ada_method2 (A *t, int v);@}
6118 void A::method1 (void)
6120   a_value = 2020;
6121   printf ("in A::method1, a_value = %d \\n",a_value);
6124 void A::method2 (int v)
6126    ada_method2 (this, v);
6127    printf ("in A::method2, a_value = %d \\n",a_value);
6130 A::A(void)
6132    a_value = 1010;
6133   printf ("in A::A, a_value = %d \\n",a_value);
6135 @end example
6137 @example
6138 -- simple_cpp_interface.ads
6139 with System;
6140 package Simple_Cpp_Interface is
6141    type A is limited
6142       record
6143          Vptr    : System.Address;
6144          O_Value : Integer;
6145          A_Value : Integer;
6146       end record;
6147    pragma Convention (C, A);
6149    procedure Method1 (This : in out A);
6150    pragma Import (C, Method1);
6152    procedure Ada_Method2 (This : in out A; V : Integer);
6153    pragma Export (C, Ada_Method2);
6155 end Simple_Cpp_Interface;
6156 @end example
6158 @example
6159 -- simple_cpp_interface.adb
6160 package body Simple_Cpp_Interface is
6162    procedure Ada_Method2 (This : in out A; V : Integer) is
6163    begin
6164       Method1 (This);
6165       This.A_Value := V;
6166    end Ada_Method2;
6168 end Simple_Cpp_Interface;
6169 @end example
6171 @node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
6172 @anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{bf}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{c0}
6173 @subsubsection Interfacing with C++ constructors
6176 In order to interface with C++ constructors GNAT provides the
6177 @code{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
6178 for additional information).
6179 In this section we present some common uses of C++ constructors
6180 in mixed-languages programs in GNAT.
6182 Let us assume that we need to interface with the following
6183 C++ class:
6185 @example
6186 class Root @{
6187 public:
6188   int  a_value;
6189   int  b_value;
6190   virtual int Get_Value ();
6191   Root();              // Default constructor
6192   Root(int v);         // 1st non-default constructor
6193   Root(int v, int w);  // 2nd non-default constructor
6195 @end example
6197 For this purpose we can write the following package spec (further
6198 information on how to build this spec is available in
6199 @ref{c1,,Interfacing with C++ at the Class Level} and
6200 @ref{19,,Generating Ada Bindings for C and C++ headers}).
6202 @example
6203 with Interfaces.C; use Interfaces.C;
6204 package Pkg_Root is
6205   type Root is tagged limited record
6206      A_Value : int;
6207      B_Value : int;
6208   end record;
6209   pragma Import (CPP, Root);
6211   function Get_Value (Obj : Root) return int;
6212   pragma Import (CPP, Get_Value);
6214   function Constructor return Root;
6215   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
6217   function Constructor (v : Integer) return Root;
6218   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
6220   function Constructor (v, w : Integer) return Root;
6221   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
6222 end Pkg_Root;
6223 @end example
6225 On the Ada side the constructor is represented by a function (whose
6226 name is arbitrary) that returns the classwide type corresponding to
6227 the imported C++ class. Although the constructor is described as a
6228 function, it is typically a procedure with an extra implicit argument
6229 (the object being initialized) at the implementation level. GNAT
6230 issues the appropriate call, whatever it is, to get the object
6231 properly initialized.
6233 Constructors can only appear in the following contexts:
6236 @itemize *
6238 @item 
6239 On the right side of an initialization of an object of type @code{T}.
6241 @item 
6242 On the right side of an initialization of a record component of type @code{T}.
6244 @item 
6245 In an Ada 2005 limited aggregate.
6247 @item 
6248 In an Ada 2005 nested limited aggregate.
6250 @item 
6251 In an Ada 2005 limited aggregate that initializes an object built in
6252 place by an extended return statement.
6253 @end itemize
6255 In a declaration of an object whose type is a class imported from C++,
6256 either the default C++ constructor is implicitly called by GNAT, or
6257 else the required C++ constructor must be explicitly called in the
6258 expression that initializes the object. For example:
6260 @example
6261 Obj1 : Root;
6262 Obj2 : Root := Constructor;
6263 Obj3 : Root := Constructor (v => 10);
6264 Obj4 : Root := Constructor (30, 40);
6265 @end example
6267 The first two declarations are equivalent: in both cases the default C++
6268 constructor is invoked (in the former case the call to the constructor is
6269 implicit, and in the latter case the call is explicit in the object
6270 declaration). @code{Obj3} is initialized by the C++ non-default constructor
6271 that takes an integer argument, and @code{Obj4} is initialized by the
6272 non-default C++ constructor that takes two integers.
6274 Let us derive the imported C++ class in the Ada side. For example:
6276 @example
6277 type DT is new Root with record
6278    C_Value : Natural := 2009;
6279 end record;
6280 @end example
6282 In this case the components DT inherited from the C++ side must be
6283 initialized by a C++ constructor, and the additional Ada components
6284 of type DT are initialized by GNAT. The initialization of such an
6285 object is done either by default, or by means of a function returning
6286 an aggregate of type DT, or by means of an extension aggregate.
6288 @example
6289 Obj5 : DT;
6290 Obj6 : DT := Function_Returning_DT (50);
6291 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6292 @end example
6294 The declaration of @code{Obj5} invokes the default constructors: the
6295 C++ default constructor of the parent type takes care of the initialization
6296 of the components inherited from Root, and GNAT takes care of the default
6297 initialization of the additional Ada components of type DT (that is,
6298 @code{C_Value} is initialized to value 2009). The order of invocation of
6299 the constructors is consistent with the order of elaboration required by
6300 Ada and C++. That is, the constructor of the parent type is always called
6301 before the constructor of the derived type.
6303 Let us now consider a record that has components whose type is imported
6304 from C++. For example:
6306 @example
6307 type Rec1 is limited record
6308    Data1 : Root := Constructor (10);
6309    Value : Natural := 1000;
6310 end record;
6312 type Rec2 (D : Integer := 20) is limited record
6313    Rec   : Rec1;
6314    Data2 : Root := Constructor (D, 30);
6315 end record;
6316 @end example
6318 The initialization of an object of type @code{Rec2} will call the
6319 non-default C++ constructors specified for the imported components.
6320 For example:
6322 @example
6323 Obj8 : Rec2 (40);
6324 @end example
6326 Using Ada 2005 we can use limited aggregates to initialize an object
6327 invoking C++ constructors that differ from those specified in the type
6328 declarations. For example:
6330 @example
6331 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6332                         others => <>),
6333                 others => <>);
6334 @end example
6336 The above declaration uses an Ada 2005 limited aggregate to
6337 initialize @code{Obj9}, and the C++ constructor that has two integer
6338 arguments is invoked to initialize the @code{Data1} component instead
6339 of the constructor specified in the declaration of type @code{Rec1}. In
6340 Ada 2005 the box in the aggregate indicates that unspecified components
6341 are initialized using the expression (if any) available in the component
6342 declaration. That is, in this case discriminant @code{D} is initialized
6343 to value @code{20}, @code{Value} is initialized to value 1000, and the
6344 non-default C++ constructor that handles two integers takes care of
6345 initializing component @code{Data2} with values @code{20,30}.
6347 In Ada 2005 we can use the extended return statement to build the Ada
6348 equivalent to C++ non-default constructors. For example:
6350 @example
6351 function Constructor (V : Integer) return Rec2 is
6352 begin
6353    return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
6354                                  others => <>),
6355                          others => <>) do
6356       --  Further actions required for construction of
6357       --  objects of type Rec2
6358       ...
6359    end record;
6360 end Constructor;
6361 @end example
6363 In this example the extended return statement construct is used to
6364 build in place the returned object whose components are initialized
6365 by means of a limited aggregate. Any further action associated with
6366 the constructor can be placed inside the construct.
6368 @node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6369 @anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-at-the-class-level}@anchor{c1}@anchor{gnat_ugn/the_gnat_compilation_model id69}@anchor{c2}
6370 @subsubsection Interfacing with C++ at the Class Level
6373 In this section we demonstrate the GNAT features for interfacing with
6374 C++ by means of an example making use of Ada 2005 abstract interface
6375 types. This example consists of a classification of animals; classes
6376 have been used to model our main classification of animals, and
6377 interfaces provide support for the management of secondary
6378 classifications. We first demonstrate a case in which the types and
6379 constructors are defined on the C++ side and imported from the Ada
6380 side, and latter the reverse case.
6382 The root of our derivation will be the @code{Animal} class, with a
6383 single private attribute (the @code{Age} of the animal), a constructor,
6384 and two public primitives to set and get the value of this attribute.
6386 @example
6387 class Animal @{
6388  public:
6389    virtual void Set_Age (int New_Age);
6390    virtual int Age ();
6391    Animal() @{Age_Count = 0;@};
6392  private:
6393    int Age_Count;
6395 @end example
6397 Abstract interface types are defined in C++ by means of classes with pure
6398 virtual functions and no data members. In our example we will use two
6399 interfaces that provide support for the common management of @code{Carnivore}
6400 and @code{Domestic} animals:
6402 @example
6403 class Carnivore @{
6404 public:
6405    virtual int Number_Of_Teeth () = 0;
6408 class Domestic @{
6409 public:
6410    virtual void Set_Owner (char* Name) = 0;
6412 @end example
6414 Using these declarations, we can now say that a @code{Dog} is an animal that is
6415 both Carnivore and Domestic, that is:
6417 @example
6418 class Dog : Animal, Carnivore, Domestic @{
6419  public:
6420    virtual int  Number_Of_Teeth ();
6421    virtual void Set_Owner (char* Name);
6423    Dog(); // Constructor
6424  private:
6425    int  Tooth_Count;
6426    char *Owner;
6428 @end example
6430 In the following examples we will assume that the previous declarations are
6431 located in a file named @code{animals.h}. The following package demonstrates
6432 how to import these C++ declarations from the Ada side:
6434 @example
6435 with Interfaces.C.Strings; use Interfaces.C.Strings;
6436 package Animals is
6437   type Carnivore is limited interface;
6438   pragma Convention (C_Plus_Plus, Carnivore);
6439   function Number_Of_Teeth (X : Carnivore)
6440      return Natural is abstract;
6442   type Domestic is limited interface;
6443   pragma Convention (C_Plus_Plus, Domestic);
6444   procedure Set_Owner
6445     (X    : in out Domestic;
6446      Name : Chars_Ptr) is abstract;
6448   type Animal is tagged limited record
6449     Age : Natural;
6450   end record;
6451   pragma Import (C_Plus_Plus, Animal);
6453   procedure Set_Age (X : in out Animal; Age : Integer);
6454   pragma Import (C_Plus_Plus, Set_Age);
6456   function Age (X : Animal) return Integer;
6457   pragma Import (C_Plus_Plus, Age);
6459   function New_Animal return Animal;
6460   pragma CPP_Constructor (New_Animal);
6461   pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6463   type Dog is new Animal and Carnivore and Domestic with record
6464     Tooth_Count : Natural;
6465     Owner       : Chars_Ptr;
6466   end record;
6467   pragma Import (C_Plus_Plus, Dog);
6469   function Number_Of_Teeth (A : Dog) return Natural;
6470   pragma Import (C_Plus_Plus, Number_Of_Teeth);
6472   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6473   pragma Import (C_Plus_Plus, Set_Owner);
6475   function New_Dog return Dog;
6476   pragma CPP_Constructor (New_Dog);
6477   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6478 end Animals;
6479 @end example
6481 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6482 interfacing with these C++ classes is easy. The only requirement is that all
6483 the primitives and components must be declared exactly in the same order in
6484 the two languages.
6486 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6487 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
6488 the arguments to the called primitives will be the same as for C++. For the
6489 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
6490 to indicate that they have been defined on the C++ side; this is required
6491 because the dispatch table associated with these tagged types will be built
6492 in the C++ side and therefore will not contain the predefined Ada primitives
6493 which Ada would otherwise expect.
6495 As the reader can see there is no need to indicate the C++ mangled names
6496 associated with each subprogram because it is assumed that all the calls to
6497 these primitives will be dispatching calls. The only exception is the
6498 constructor, which must be registered with the compiler by means of
6499 @code{pragma CPP_Constructor} and needs to provide its associated C++
6500 mangled name because the Ada compiler generates direct calls to it.
6502 With the above packages we can now declare objects of type Dog on the Ada side
6503 and dispatch calls to the corresponding subprograms on the C++ side. We can
6504 also extend the tagged type Dog with further fields and primitives, and
6505 override some of its C++ primitives on the Ada side. For example, here we have
6506 a type derivation defined on the Ada side that inherits all the dispatching
6507 primitives of the ancestor from the C++ side.
6509 @example
6510 with Animals; use Animals;
6511 package Vaccinated_Animals is
6512   type Vaccinated_Dog is new Dog with null record;
6513   function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6514 end Vaccinated_Animals;
6515 @end example
6517 It is important to note that, because of the ABI compatibility, the programmer
6518 does not need to add any further information to indicate either the object
6519 layout or the dispatch table entry associated with each dispatching operation.
6521 Now let us define all the types and constructors on the Ada side and export
6522 them to C++, using the same hierarchy of our previous example:
6524 @example
6525 with Interfaces.C.Strings;
6526 use Interfaces.C.Strings;
6527 package Animals is
6528   type Carnivore is limited interface;
6529   pragma Convention (C_Plus_Plus, Carnivore);
6530   function Number_Of_Teeth (X : Carnivore)
6531      return Natural is abstract;
6533   type Domestic is limited interface;
6534   pragma Convention (C_Plus_Plus, Domestic);
6535   procedure Set_Owner
6536     (X    : in out Domestic;
6537      Name : Chars_Ptr) is abstract;
6539   type Animal is tagged record
6540     Age : Natural;
6541   end record;
6542   pragma Convention (C_Plus_Plus, Animal);
6544   procedure Set_Age (X : in out Animal; Age : Integer);
6545   pragma Export (C_Plus_Plus, Set_Age);
6547   function Age (X : Animal) return Integer;
6548   pragma Export (C_Plus_Plus, Age);
6550   function New_Animal return Animal'Class;
6551   pragma Export (C_Plus_Plus, New_Animal);
6553   type Dog is new Animal and Carnivore and Domestic with record
6554     Tooth_Count : Natural;
6555     Owner       : String (1 .. 30);
6556   end record;
6557   pragma Convention (C_Plus_Plus, Dog);
6559   function Number_Of_Teeth (A : Dog) return Natural;
6560   pragma Export (C_Plus_Plus, Number_Of_Teeth);
6562   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6563   pragma Export (C_Plus_Plus, Set_Owner);
6565   function New_Dog return Dog'Class;
6566   pragma Export (C_Plus_Plus, New_Dog);
6567 end Animals;
6568 @end example
6570 Compared with our previous example the only differences are the use of
6571 @code{pragma Convention} (instead of @code{pragma Import}), and the use of
6572 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
6573 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6574 nothing else to be done; as explained above, the only requirement is that all
6575 the primitives and components are declared in exactly the same order.
6577 For completeness, let us see a brief C++ main program that uses the
6578 declarations available in @code{animals.h} (presented in our first example) to
6579 import and use the declarations from the Ada side, properly initializing and
6580 finalizing the Ada run-time system along the way:
6582 @example
6583 #include "animals.h"
6584 #include <iostream>
6585 using namespace std;
6587 void Check_Carnivore (Carnivore *obj) @{...@}
6588 void Check_Domestic (Domestic *obj)   @{...@}
6589 void Check_Animal (Animal *obj)       @{...@}
6590 void Check_Dog (Dog *obj)             @{...@}
6592 extern "C" @{
6593   void adainit (void);
6594   void adafinal (void);
6595   Dog* new_dog ();
6598 void test ()
6600   Dog *obj = new_dog();  // Ada constructor
6601   Check_Carnivore (obj); // Check secondary DT
6602   Check_Domestic (obj);  // Check secondary DT
6603   Check_Animal (obj);    // Check primary DT
6604   Check_Dog (obj);       // Check primary DT
6607 int main ()
6609   adainit ();  test();  adafinal ();
6610   return 0;
6612 @end example
6614 @node Generating Ada Bindings for C and C++ headers,Generating C Headers for Ada Specifications,Building Mixed Ada and C++ Programs,Mixed Language Programming
6615 @anchor{gnat_ugn/the_gnat_compilation_model id70}@anchor{c3}@anchor{gnat_ugn/the_gnat_compilation_model generating-ada-bindings-for-c-and-c-headers}@anchor{19}
6616 @subsection Generating Ada Bindings for C and C++ headers
6619 @geindex Binding generation (for C and C++ headers)
6621 @geindex C headers (binding generation)
6623 @geindex C++ headers (binding generation)
6625 GNAT includes a binding generator for C and C++ headers which is
6626 intended to do 95% of the tedious work of generating Ada specs from C
6627 or C++ header files.
6629 Note that this capability is not intended to generate 100% correct Ada specs,
6630 and will is some cases require manual adjustments, although it can often
6631 be used out of the box in practice.
6633 Some of the known limitations include:
6636 @itemize *
6638 @item 
6639 only very simple character constant macros are translated into Ada
6640 constants. Function macros (macros with arguments) are partially translated
6641 as comments, to be completed manually if needed.
6643 @item 
6644 some extensions (e.g. vector types) are not supported
6646 @item 
6647 pointers to pointers or complex structures are mapped to System.Address
6649 @item 
6650 identifiers with identical name (except casing) will generate compilation
6651 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
6652 @end itemize
6654 The code generated is using the Ada 2005 syntax, which makes it
6655 easier to interface with other languages than previous versions of Ada.
6657 @menu
6658 * Running the Binding Generator:: 
6659 * Generating Bindings for C++ Headers:: 
6660 * Switches:: 
6662 @end menu
6664 @node Running the Binding Generator,Generating Bindings for C++ Headers,,Generating Ada Bindings for C and C++ headers
6665 @anchor{gnat_ugn/the_gnat_compilation_model id71}@anchor{c4}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{c5}
6666 @subsubsection Running the Binding Generator
6669 The binding generator is part of the @code{gcc} compiler and can be
6670 invoked via the @code{-fdump-ada-spec} switch, which will generate Ada
6671 spec files for the header files specified on the command line, and all
6672 header files needed by these files transitively. For example:
6674 @example
6675 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
6676 $ gcc -c -gnat05 *.ads
6677 @end example
6679 will generate, under GNU/Linux, the following files: @code{time_h.ads},
6680 @code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6681 correspond to the files @code{/usr/include/time.h},
6682 @code{/usr/include/bits/time.h}, etc..., and will then compile these Ada specs
6683 in Ada 2005 mode.
6685 The @code{-C} switch tells @code{gcc} to extract comments from headers,
6686 and will attempt to generate corresponding Ada comments.
6688 If you want to generate a single Ada file and not the transitive closure, you
6689 can use instead the @code{-fdump-ada-spec-slim} switch.
6691 You can optionally specify a parent unit, of which all generated units will
6692 be children, using @code{-fada-spec-parent=@emph{unit}}.
6694 Note that we recommend when possible to use the @emph{g++} driver to
6695 generate bindings, even for most C headers, since this will in general
6696 generate better Ada specs. For generating bindings for C++ headers, it is
6697 mandatory to use the @emph{g++} command, or @emph{gcc -x c++} which
6698 is equivalent in this case. If @emph{g++} cannot work on your C headers
6699 because of incompatibilities between C and C++, then you can fallback to
6700 @code{gcc} instead.
6702 For an example of better bindings generated from the C++ front-end,
6703 the name of the parameters (when available) are actually ignored by the C
6704 front-end. Consider the following C header:
6706 @example
6707 extern void foo (int variable);
6708 @end example
6710 with the C front-end, @code{variable} is ignored, and the above is handled as:
6712 @example
6713 extern void foo (int);
6714 @end example
6716 generating a generic:
6718 @example
6719 procedure foo (param1 : int);
6720 @end example
6722 with the C++ front-end, the name is available, and we generate:
6724 @example
6725 procedure foo (variable : int);
6726 @end example
6728 In some cases, the generated bindings will be more complete or more meaningful
6729 when defining some macros, which you can do via the @code{-D} switch. This
6730 is for example the case with @code{Xlib.h} under GNU/Linux:
6732 @example
6733 $ g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6734 @end example
6736 The above will generate more complete bindings than a straight call without
6737 the @code{-DXLIB_ILLEGAL_ACCESS} switch.
6739 In other cases, it is not possible to parse a header file in a stand-alone
6740 manner, because other include files need to be included first. In this
6741 case, the solution is to create a small header file including the needed
6742 @code{#include} and possible @code{#define} directives. For example, to
6743 generate Ada bindings for @code{readline/readline.h}, you need to first
6744 include @code{stdio.h}, so you can create a file with the following two
6745 lines in e.g. @code{readline1.h}:
6747 @example
6748 #include <stdio.h>
6749 #include <readline/readline.h>
6750 @end example
6752 and then generate Ada bindings from this file:
6754 @example
6755 $ g++ -c -fdump-ada-spec readline1.h
6756 @end example
6758 @node Generating Bindings for C++ Headers,Switches,Running the Binding Generator,Generating Ada Bindings for C and C++ headers
6759 @anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{c6}@anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{c7}
6760 @subsubsection Generating Bindings for C++ Headers
6763 Generating bindings for C++ headers is done using the same options, always
6764 with the @emph{g++} compiler. Note that generating Ada spec from C++ headers is a
6765 much more complex job and support for C++ headers is much more limited that
6766 support for C headers. As a result, you will need to modify the resulting
6767 bindings by hand more extensively when using C++ headers.
6769 In this mode, C++ classes will be mapped to Ada tagged types, constructors
6770 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
6771 multiple inheritance of abstract classes will be mapped to Ada interfaces
6772 (see the @emph{Interfacing to C++} section in the @cite{GNAT Reference Manual}
6773 for additional information on interfacing to C++).
6775 For example, given the following C++ header file:
6777 @example
6778 class Carnivore @{
6779 public:
6780    virtual int Number_Of_Teeth () = 0;
6783 class Domestic @{
6784 public:
6785    virtual void Set_Owner (char* Name) = 0;
6788 class Animal @{
6789 public:
6790   int Age_Count;
6791   virtual void Set_Age (int New_Age);
6794 class Dog : Animal, Carnivore, Domestic @{
6795  public:
6796   int  Tooth_Count;
6797   char *Owner;
6799   virtual int  Number_Of_Teeth ();
6800   virtual void Set_Owner (char* Name);
6802   Dog();
6804 @end example
6806 The corresponding Ada code is generated:
6808 @example
6809 package Class_Carnivore is
6810   type Carnivore is limited interface;
6811   pragma Import (CPP, Carnivore);
6813   function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6814 end;
6815 use Class_Carnivore;
6817 package Class_Domestic is
6818   type Domestic is limited interface;
6819   pragma Import (CPP, Domestic);
6821   procedure Set_Owner
6822     (this : access Domestic;
6823      Name : Interfaces.C.Strings.chars_ptr) is abstract;
6824 end;
6825 use Class_Domestic;
6827 package Class_Animal is
6828   type Animal is tagged limited record
6829     Age_Count : aliased int;
6830   end record;
6831   pragma Import (CPP, Animal);
6833   procedure Set_Age (this : access Animal; New_Age : int);
6834   pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6835 end;
6836 use Class_Animal;
6838 package Class_Dog is
6839   type Dog is new Animal and Carnivore and Domestic with record
6840     Tooth_Count : aliased int;
6841     Owner : Interfaces.C.Strings.chars_ptr;
6842   end record;
6843   pragma Import (CPP, Dog);
6845   function Number_Of_Teeth (this : access Dog) return int;
6846   pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6848   procedure Set_Owner
6849     (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6850   pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6852   function New_Dog return Dog;
6853   pragma CPP_Constructor (New_Dog);
6854   pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6855 end;
6856 use Class_Dog;
6857 @end example
6859 @node Switches,,Generating Bindings for C++ Headers,Generating Ada Bindings for C and C++ headers
6860 @anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{c8}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{c9}
6861 @subsubsection Switches
6864 @geindex -fdump-ada-spec (gcc)
6867 @table @asis
6869 @item @code{-fdump-ada-spec}
6871 Generate Ada spec files for the given header files transitively (including
6872 all header files that these headers depend upon).
6873 @end table
6875 @geindex -fdump-ada-spec-slim (gcc)
6878 @table @asis
6880 @item @code{-fdump-ada-spec-slim}
6882 Generate Ada spec files for the header files specified on the command line
6883 only.
6884 @end table
6886 @geindex -fada-spec-parent (gcc)
6889 @table @asis
6891 @item @code{-fada-spec-parent=@emph{unit}}
6893 Specifies that all files generated by @code{-fdump-ada-spec} are
6894 to be child units of the specified parent unit.
6895 @end table
6897 @geindex -C (gcc)
6900 @table @asis
6902 @item @code{-C}
6904 Extract comments from headers and generate Ada comments in the Ada spec files.
6905 @end table
6907 @node Generating C Headers for Ada Specifications,,Generating Ada Bindings for C and C++ headers,Mixed Language Programming
6908 @anchor{gnat_ugn/the_gnat_compilation_model generating-c-headers-for-ada-specifications}@anchor{ca}@anchor{gnat_ugn/the_gnat_compilation_model id73}@anchor{cb}
6909 @subsection Generating C Headers for Ada Specifications
6912 @geindex Binding generation (for Ada specs)
6914 @geindex C headers (binding generation)
6916 GNAT includes a C header generator for Ada specifications which supports
6917 Ada types that have a direct mapping to C types. This includes in particular
6918 support for:
6921 @itemize *
6923 @item 
6924 Scalar types
6926 @item 
6927 Constrained arrays
6929 @item 
6930 Records (untagged)
6932 @item 
6933 Composition of the above types
6935 @item 
6936 Constant declarations
6938 @item 
6939 Object declarations
6941 @item 
6942 Subprogram declarations
6943 @end itemize
6945 @menu
6946 * Running the C Header Generator:: 
6948 @end menu
6950 @node Running the C Header Generator,,,Generating C Headers for Ada Specifications
6951 @anchor{gnat_ugn/the_gnat_compilation_model running-the-c-header-generator}@anchor{cc}
6952 @subsubsection Running the C Header Generator
6955 The C header generator is part of the GNAT compiler and can be invoked via
6956 the @code{-gnatceg} combination of switches, which will generate a @code{.h}
6957 file corresponding to the given input file (Ada spec or body). Note that
6958 only spec files are processed in any case, so giving a spec or a body file
6959 as input is equivalent. For example:
6961 @example
6962 $ gcc -c -gnatceg pack1.ads
6963 @end example
6965 will generate a self-contained file called @code{pack1.h} including
6966 common definitions from the Ada Standard package, followed by the
6967 definitions included in @code{pack1.ads}, as well as all the other units
6968 withed by this file.
6970 For instance, given the following Ada files:
6972 @example
6973 package Pack2 is
6974    type Int is range 1 .. 10;
6975 end Pack2;
6976 @end example
6978 @example
6979 with Pack2;
6981 package Pack1 is
6982    type Rec is record
6983       Field1, Field2 : Pack2.Int;
6984    end record;
6986    Global : Rec := (1, 2);
6988    procedure Proc1 (R : Rec);
6989    procedure Proc2 (R : in out Rec);
6990 end Pack1;
6991 @end example
6993 The above @code{gcc} command will generate the following @code{pack1.h} file:
6995 @example
6996 /* Standard definitions skipped */
6997 #ifndef PACK2_ADS
6998 #define PACK2_ADS
6999 typedef short_short_integer pack2__TintB;
7000 typedef pack2__TintB pack2__int;
7001 #endif /* PACK2_ADS */
7003 #ifndef PACK1_ADS
7004 #define PACK1_ADS
7005 typedef struct _pack1__rec @{
7006   pack2__int field1;
7007   pack2__int field2;
7008 @} pack1__rec;
7009 extern pack1__rec pack1__global;
7010 extern void pack1__proc1(const pack1__rec r);
7011 extern void pack1__proc2(pack1__rec *r);
7012 #endif /* PACK1_ADS */
7013 @end example
7015 You can then @code{include} @code{pack1.h} from a C source file and use the types,
7016 call subprograms, reference objects, and constants.
7018 @node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
7019 @anchor{gnat_ugn/the_gnat_compilation_model id74}@anchor{cd}@anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{45}
7020 @section GNAT and Other Compilation Models
7023 This section compares the GNAT model with the approaches taken in
7024 other environents, first the C/C++ model and then the mechanism that
7025 has been used in other Ada systems, in particular those traditionally
7026 used for Ada 83.
7028 @menu
7029 * Comparison between GNAT and C/C++ Compilation Models:: 
7030 * Comparison between GNAT and Conventional Ada Library Models:: 
7032 @end menu
7034 @node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
7035 @anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-c-c-compilation-models}@anchor{ce}@anchor{gnat_ugn/the_gnat_compilation_model id75}@anchor{cf}
7036 @subsection Comparison between GNAT and C/C++ Compilation Models
7039 The GNAT model of compilation is close to the C and C++ models. You can
7040 think of Ada specs as corresponding to header files in C. As in C, you
7041 don't need to compile specs; they are compiled when they are used. The
7042 Ada @emph{with} is similar in effect to the @code{#include} of a C
7043 header.
7045 One notable difference is that, in Ada, you may compile specs separately
7046 to check them for semantic and syntactic accuracy. This is not always
7047 possible with C headers because they are fragments of programs that have
7048 less specific syntactic or semantic rules.
7050 The other major difference is the requirement for running the binder,
7051 which performs two important functions. First, it checks for
7052 consistency. In C or C++, the only defense against assembling
7053 inconsistent programs lies outside the compiler, in a makefile, for
7054 example. The binder satisfies the Ada requirement that it be impossible
7055 to construct an inconsistent program when the compiler is used in normal
7056 mode.
7058 @geindex Elaboration order control
7060 The other important function of the binder is to deal with elaboration
7061 issues. There are also elaboration issues in C++ that are handled
7062 automatically. This automatic handling has the advantage of being
7063 simpler to use, but the C++ programmer has no control over elaboration.
7064 Where @code{gnatbind} might complain there was no valid order of
7065 elaboration, a C++ compiler would simply construct a program that
7066 malfunctioned at run time.
7068 @node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
7069 @anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-conventional-ada-library-models}@anchor{d0}@anchor{gnat_ugn/the_gnat_compilation_model id76}@anchor{d1}
7070 @subsection Comparison between GNAT and Conventional Ada Library Models
7073 This section is intended for Ada programmers who have
7074 used an Ada compiler implementing the traditional Ada library
7075 model, as described in the Ada Reference Manual.
7077 @geindex GNAT library
7079 In GNAT, there is no 'library' in the normal sense. Instead, the set of
7080 source files themselves acts as the library. Compiling Ada programs does
7081 not generate any centralized information, but rather an object file and
7082 a ALI file, which are of interest only to the binder and linker.
7083 In a traditional system, the compiler reads information not only from
7084 the source file being compiled, but also from the centralized library.
7085 This means that the effect of a compilation depends on what has been
7086 previously compiled. In particular:
7089 @itemize *
7091 @item 
7092 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7093 to the version of the unit most recently compiled into the library.
7095 @item 
7096 Inlining is effective only if the necessary body has already been
7097 compiled into the library.
7099 @item 
7100 Compiling a unit may obsolete other units in the library.
7101 @end itemize
7103 In GNAT, compiling one unit never affects the compilation of any other
7104 units because the compiler reads only source files. Only changes to source
7105 files can affect the results of a compilation. In particular:
7108 @itemize *
7110 @item 
7111 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7112 to the source version of the unit that is currently accessible to the
7113 compiler.
7115 @geindex Inlining
7117 @item 
7118 Inlining requires the appropriate source files for the package or
7119 subprogram bodies to be available to the compiler. Inlining is always
7120 effective, independent of the order in which units are compiled.
7122 @item 
7123 Compiling a unit never affects any other compilations. The editing of
7124 sources may cause previous compilations to be out of date if they
7125 depended on the source file being modified.
7126 @end itemize
7128 The most important result of these differences is that order of compilation
7129 is never significant in GNAT. There is no situation in which one is
7130 required to do one compilation before another. What shows up as order of
7131 compilation requirements in the traditional Ada library becomes, in
7132 GNAT, simple source dependencies; in other words, there is only a set
7133 of rules saying what source files must be present when a file is
7134 compiled.
7136 @node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
7137 @anchor{gnat_ugn/the_gnat_compilation_model using-gnat-files-with-external-tools}@anchor{1a}@anchor{gnat_ugn/the_gnat_compilation_model id77}@anchor{d2}
7138 @section Using GNAT Files with External Tools
7141 This section explains how files that are produced by GNAT may be
7142 used with tools designed for other languages.
7144 @menu
7145 * Using Other Utility Programs with GNAT:: 
7146 * The External Symbol Naming Scheme of GNAT:: 
7148 @end menu
7150 @node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
7151 @anchor{gnat_ugn/the_gnat_compilation_model using-other-utility-programs-with-gnat}@anchor{d3}@anchor{gnat_ugn/the_gnat_compilation_model id78}@anchor{d4}
7152 @subsection Using Other Utility Programs with GNAT
7155 The object files generated by GNAT are in standard system format and in
7156 particular the debugging information uses this format. This means
7157 programs generated by GNAT can be used with existing utilities that
7158 depend on these formats.
7160 In general, any utility program that works with C will also often work with
7161 Ada programs generated by GNAT. This includes software utilities such as
7162 gprof (a profiling program), gdb (the FSF debugger), and utilities such
7163 as Purify.
7165 @node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
7166 @anchor{gnat_ugn/the_gnat_compilation_model the-external-symbol-naming-scheme-of-gnat}@anchor{d5}@anchor{gnat_ugn/the_gnat_compilation_model id79}@anchor{d6}
7167 @subsection The External Symbol Naming Scheme of GNAT
7170 In order to interpret the output from GNAT, when using tools that are
7171 originally intended for use with other languages, it is useful to
7172 understand the conventions used to generate link names from the Ada
7173 entity names.
7175 All link names are in all lowercase letters. With the exception of library
7176 procedure names, the mechanism used is simply to use the full expanded
7177 Ada name with dots replaced by double underscores. For example, suppose
7178 we have the following package spec:
7180 @example
7181 package QRS is
7182    MN : Integer;
7183 end QRS;
7184 @end example
7186 @geindex pragma Export
7188 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
7189 the corresponding link name is @code{qrs__mn}.
7190 Of course if a @code{pragma Export} is used this may be overridden:
7192 @example
7193 package Exports is
7194    Var1 : Integer;
7195    pragma Export (Var1, C, External_Name => "var1_name");
7196    Var2 : Integer;
7197    pragma Export (Var2, C, Link_Name => "var2_link_name");
7198 end Exports;
7199 @end example
7201 In this case, the link name for @code{Var1} is whatever link name the
7202 C compiler would assign for the C function @code{var1_name}. This typically
7203 would be either @code{var1_name} or @code{_var1_name}, depending on operating
7204 system conventions, but other possibilities exist. The link name for
7205 @code{Var2} is @code{var2_link_name}, and this is not operating system
7206 dependent.
7208 One exception occurs for library level procedures. A potential ambiguity
7209 arises between the required name @code{_main} for the C main program,
7210 and the name we would otherwise assign to an Ada library level procedure
7211 called @code{Main} (which might well not be the main program).
7213 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
7214 names. So if we have a library level procedure such as:
7216 @example
7217 procedure Hello (S : String);
7218 @end example
7220 the external name of this procedure will be @code{_ada_hello}.
7222 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7224 @node Building Executable Programs with GNAT,GNAT Utility Programs,The GNAT Compilation Model,Top
7225 @anchor{gnat_ugn/building_executable_programs_with_gnat building-executable-programs-with-gnat}@anchor{a}@anchor{gnat_ugn/building_executable_programs_with_gnat doc}@anchor{d7}@anchor{gnat_ugn/building_executable_programs_with_gnat id1}@anchor{d8}
7226 @chapter Building Executable Programs with GNAT
7229 This chapter describes first the gnatmake tool
7230 (@ref{1b,,Building with gnatmake}),
7231 which automatically determines the set of sources
7232 needed by an Ada compilation unit and executes the necessary
7233 (re)compilations, binding and linking.
7234 It also explains how to use each tool individually: the
7235 compiler (gcc, see @ref{1c,,Compiling with gcc}),
7236 binder (gnatbind, see @ref{1d,,Binding with gnatbind}),
7237 and linker (gnatlink, see @ref{1e,,Linking with gnatlink})
7238 to build executable programs.
7239 Finally, this chapter provides examples of
7240 how to make use of the general GNU make mechanism
7241 in a GNAT context (see @ref{1f,,Using the GNU make Utility}).
7244 @menu
7245 * Building with gnatmake:: 
7246 * Compiling with gcc:: 
7247 * Compiler Switches:: 
7248 * Linker Switches:: 
7249 * Binding with gnatbind:: 
7250 * Linking with gnatlink:: 
7251 * Using the GNU make Utility:: 
7253 @end menu
7255 @node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
7256 @anchor{gnat_ugn/building_executable_programs_with_gnat the-gnat-make-program-gnatmake}@anchor{1b}@anchor{gnat_ugn/building_executable_programs_with_gnat building-with-gnatmake}@anchor{d9}
7257 @section Building with @code{gnatmake}
7260 @geindex gnatmake
7262 A typical development cycle when working on an Ada program consists of
7263 the following steps:
7266 @enumerate 
7268 @item 
7269 Edit some sources to fix bugs;
7271 @item 
7272 Add enhancements;
7274 @item 
7275 Compile all sources affected;
7277 @item 
7278 Rebind and relink; and
7280 @item 
7281 Test.
7282 @end enumerate
7284 @geindex Dependency rules (compilation)
7286 The third step in particular can be tricky, because not only do the modified
7287 files have to be compiled, but any files depending on these files must also be
7288 recompiled. The dependency rules in Ada can be quite complex, especially
7289 in the presence of overloading, @code{use} clauses, generics and inlined
7290 subprograms.
7292 @code{gnatmake} automatically takes care of the third and fourth steps
7293 of this process. It determines which sources need to be compiled,
7294 compiles them, and binds and links the resulting object files.
7296 Unlike some other Ada make programs, the dependencies are always
7297 accurately recomputed from the new sources. The source based approach of
7298 the GNAT compilation model makes this possible. This means that if
7299 changes to the source program cause corresponding changes in
7300 dependencies, they will always be tracked exactly correctly by
7301 @code{gnatmake}.
7303 Note that for advanced forms of project structure, we recommend creating
7304 a project file as explained in the @emph{GNAT_Project_Manager} chapter in the
7305 @emph{GPRbuild User's Guide}, and using the
7306 @code{gprbuild} tool which supports building with project files and works similarly
7307 to @code{gnatmake}.
7309 @menu
7310 * Running gnatmake:: 
7311 * Switches for gnatmake:: 
7312 * Mode Switches for gnatmake:: 
7313 * Notes on the Command Line:: 
7314 * How gnatmake Works:: 
7315 * Examples of gnatmake Usage:: 
7317 @end menu
7319 @node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7320 @anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{da}@anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{db}
7321 @subsection Running @code{gnatmake}
7324 The usual form of the @code{gnatmake} command is
7326 @example
7327 $ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7328 @end example
7330 The only required argument is one @code{file_name}, which specifies
7331 a compilation unit that is a main program. Several @code{file_names} can be
7332 specified: this will result in several executables being built.
7333 If @code{switches} are present, they can be placed before the first
7334 @code{file_name}, between @code{file_names} or after the last @code{file_name}.
7335 If @code{mode_switches} are present, they must always be placed after
7336 the last @code{file_name} and all @code{switches}.
7338 If you are using standard file extensions (@code{.adb} and
7339 @code{.ads}), then the
7340 extension may be omitted from the @code{file_name} arguments. However, if
7341 you are using non-standard extensions, then it is required that the
7342 extension be given. A relative or absolute directory path can be
7343 specified in a @code{file_name}, in which case, the input source file will
7344 be searched for in the specified directory only. Otherwise, the input
7345 source file will first be searched in the directory where
7346 @code{gnatmake} was invoked and if it is not found, it will be search on
7347 the source path of the compiler as described in
7348 @ref{89,,Search Paths and the Run-Time Library (RTL)}.
7350 All @code{gnatmake} output (except when you specify @code{-M}) is sent to
7351 @code{stderr}. The output produced by the
7352 @code{-M} switch is sent to @code{stdout}.
7354 @node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7355 @anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{dc}@anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{dd}
7356 @subsection Switches for @code{gnatmake}
7359 You may specify any of the following switches to @code{gnatmake}:
7361 @geindex --version (gnatmake)
7364 @table @asis
7366 @item @code{--version}
7368 Display Copyright and version, then exit disregarding all other options.
7369 @end table
7371 @geindex --help (gnatmake)
7374 @table @asis
7376 @item @code{--help}
7378 If @code{--version} was not used, display usage, then exit disregarding
7379 all other options.
7380 @end table
7382 @geindex --GCC=compiler_name (gnatmake)
7385 @table @asis
7387 @item @code{--GCC=@emph{compiler_name}}
7389 Program used for compiling. The default is @code{gcc}. You need to use
7390 quotes around @code{compiler_name} if @code{compiler_name} contains
7391 spaces or other separator characters.
7392 As an example @code{--GCC="foo -x  -y"}
7393 will instruct @code{gnatmake} to use @code{foo -x -y} as your
7394 compiler. A limitation of this syntax is that the name and path name of
7395 the executable itself must not include any embedded spaces. Note that
7396 switch @code{-c} is always inserted after your command name. Thus in the
7397 above example the compiler command that will be used by @code{gnatmake}
7398 will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7399 used, only the last @code{compiler_name} is taken into account. However,
7400 all the additional switches are also taken into account. Thus,
7401 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7402 @code{--GCC="bar -x -y -z -t"}.
7403 @end table
7405 @geindex --GNATBIND=binder_name (gnatmake)
7408 @table @asis
7410 @item @code{--GNATBIND=@emph{binder_name}}
7412 Program used for binding. The default is @code{gnatbind}. You need to
7413 use quotes around @code{binder_name} if @code{binder_name} contains spaces
7414 or other separator characters.
7415 As an example @code{--GNATBIND="bar -x  -y"}
7416 will instruct @code{gnatmake} to use @code{bar -x -y} as your
7417 binder. Binder switches that are normally appended by @code{gnatmake}
7418 to @code{gnatbind} are now appended to the end of @code{bar -x -y}.
7419 A limitation of this syntax is that the name and path name of the executable
7420 itself must not include any embedded spaces.
7421 @end table
7423 @geindex --GNATLINK=linker_name (gnatmake)
7426 @table @asis
7428 @item @code{--GNATLINK=@emph{linker_name}}
7430 Program used for linking. The default is @code{gnatlink}. You need to
7431 use quotes around @code{linker_name} if @code{linker_name} contains spaces
7432 or other separator characters.
7433 As an example @code{--GNATLINK="lan -x  -y"}
7434 will instruct @code{gnatmake} to use @code{lan -x -y} as your
7435 linker. Linker switches that are normally appended by @code{gnatmake} to
7436 @code{gnatlink} are now appended to the end of @code{lan -x -y}.
7437 A limitation of this syntax is that the name and path name of the executable
7438 itself must not include any embedded spaces.
7440 @item @code{--create-map-file}
7442 When linking an executable, create a map file. The name of the map file
7443 has the same name as the executable with extension ".map".
7445 @item @code{--create-map-file=@emph{mapfile}}
7447 When linking an executable, create a map file with the specified name.
7448 @end table
7450 @geindex --create-missing-dirs (gnatmake)
7453 @table @asis
7455 @item @code{--create-missing-dirs}
7457 When using project files (@code{-P@emph{project}}), automatically create
7458 missing object directories, library directories and exec
7459 directories.
7461 @item @code{--single-compile-per-obj-dir}
7463 Disallow simultaneous compilations in the same object directory when
7464 project files are used.
7466 @item @code{--subdirs=@emph{subdir}}
7468 Actual object directory of each project file is the subdirectory subdir of the
7469 object directory specified or defaulted in the project file.
7471 @item @code{--unchecked-shared-lib-imports}
7473 By default, shared library projects are not allowed to import static library
7474 projects. When this switch is used on the command line, this restriction is
7475 relaxed.
7477 @item @code{--source-info=@emph{source info file}}
7479 Specify a source info file. This switch is active only when project files
7480 are used. If the source info file is specified as a relative path, then it is
7481 relative to the object directory of the main project. If the source info file
7482 does not exist, then after the Project Manager has successfully parsed and
7483 processed the project files and found the sources, it creates the source info
7484 file. If the source info file already exists and can be read successfully,
7485 then the Project Manager will get all the needed information about the sources
7486 from the source info file and will not look for them. This reduces the time
7487 to process the project files, especially when looking for sources that take a
7488 long time. If the source info file exists but cannot be parsed successfully,
7489 the Project Manager will attempt to recreate it. If the Project Manager fails
7490 to create the source info file, a message is issued, but gnatmake does not
7491 fail. @code{gnatmake} "trusts" the source info file. This means that
7492 if the source files have changed (addition, deletion, moving to a different
7493 source directory), then the source info file need to be deleted and recreated.
7494 @end table
7496 @geindex -a (gnatmake)
7499 @table @asis
7501 @item @code{-a}
7503 Consider all files in the make process, even the GNAT internal system
7504 files (for example, the predefined Ada library files), as well as any
7505 locked files. Locked files are files whose ALI file is write-protected.
7506 By default,
7507 @code{gnatmake} does not check these files,
7508 because the assumption is that the GNAT internal files are properly up
7509 to date, and also that any write protected ALI files have been properly
7510 installed. Note that if there is an installation problem, such that one
7511 of these files is not up to date, it will be properly caught by the
7512 binder.
7513 You may have to specify this switch if you are working on GNAT
7514 itself. The switch @code{-a} is also useful
7515 in conjunction with @code{-f}
7516 if you need to recompile an entire application,
7517 including run-time files, using special configuration pragmas,
7518 such as a @code{Normalize_Scalars} pragma.
7520 By default
7521 @code{gnatmake -a} compiles all GNAT
7522 internal files with
7523 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7524 @end table
7526 @geindex -b (gnatmake)
7529 @table @asis
7531 @item @code{-b}
7533 Bind only. Can be combined with @code{-c} to do
7534 compilation and binding, but no link.
7535 Can be combined with @code{-l}
7536 to do binding and linking. When not combined with
7537 @code{-c}
7538 all the units in the closure of the main program must have been previously
7539 compiled and must be up to date. The root unit specified by @code{file_name}
7540 may be given without extension, with the source extension or, if no GNAT
7541 Project File is specified, with the ALI file extension.
7542 @end table
7544 @geindex -c (gnatmake)
7547 @table @asis
7549 @item @code{-c}
7551 Compile only. Do not perform binding, except when @code{-b}
7552 is also specified. Do not perform linking, except if both
7553 @code{-b} and
7554 @code{-l} are also specified.
7555 If the root unit specified by @code{file_name} is not a main unit, this is the
7556 default. Otherwise @code{gnatmake} will attempt binding and linking
7557 unless all objects are up to date and the executable is more recent than
7558 the objects.
7559 @end table
7561 @geindex -C (gnatmake)
7564 @table @asis
7566 @item @code{-C}
7568 Use a temporary mapping file. A mapping file is a way to communicate
7569 to the compiler two mappings: from unit names to file names (without
7570 any directory information) and from file names to path names (with
7571 full directory information). A mapping file can make the compiler's
7572 file searches faster, especially if there are many source directories,
7573 or the sources are read over a slow network connection. If
7574 @code{-P} is used, a mapping file is always used, so
7575 @code{-C} is unnecessary; in this case the mapping file
7576 is initially populated based on the project file. If
7577 @code{-C} is used without
7578 @code{-P},
7579 the mapping file is initially empty. Each invocation of the compiler
7580 will add any newly accessed sources to the mapping file.
7581 @end table
7583 @geindex -C= (gnatmake)
7586 @table @asis
7588 @item @code{-C=@emph{file}}
7590 Use a specific mapping file. The file, specified as a path name (absolute or
7591 relative) by this switch, should already exist, otherwise the switch is
7592 ineffective. The specified mapping file will be communicated to the compiler.
7593 This switch is not compatible with a project file
7594 (-P`file`) or with multiple compiling processes
7595 (-jnnn, when nnn is greater than 1).
7596 @end table
7598 @geindex -d (gnatmake)
7601 @table @asis
7603 @item @code{-d}
7605 Display progress for each source, up to date or not, as a single line:
7607 @example
7608 completed x out of y (zz%)
7609 @end example
7611 If the file needs to be compiled this is displayed after the invocation of
7612 the compiler. These lines are displayed even in quiet output mode.
7613 @end table
7615 @geindex -D (gnatmake)
7618 @table @asis
7620 @item @code{-D @emph{dir}}
7622 Put all object files and ALI file in directory @code{dir}.
7623 If the @code{-D} switch is not used, all object files
7624 and ALI files go in the current working directory.
7626 This switch cannot be used when using a project file.
7627 @end table
7629 @geindex -eI (gnatmake)
7632 @table @asis
7634 @item @code{-eI@emph{nnn}}
7636 Indicates that the main source is a multi-unit source and the rank of the unit
7637 in the source file is nnn. nnn needs to be a positive number and a valid
7638 index in the source. This switch cannot be used when @code{gnatmake} is
7639 invoked for several mains.
7640 @end table
7642 @geindex -eL (gnatmake)
7644 @geindex symbolic links
7647 @table @asis
7649 @item @code{-eL}
7651 Follow all symbolic links when processing project files.
7652 This should be used if your project uses symbolic links for files or
7653 directories, but is not needed in other cases.
7655 @geindex naming scheme
7657 This also assumes that no directory matches the naming scheme for files (for
7658 instance that you do not have a directory called "sources.ads" when using the
7659 default GNAT naming scheme).
7661 When you do not have to use this switch (i.e., by default), gnatmake is able to
7662 save a lot of system calls (several per source file and object file), which
7663 can result in a significant speed up to load and manipulate a project file,
7664 especially when using source files from a remote system.
7665 @end table
7667 @geindex -eS (gnatmake)
7670 @table @asis
7672 @item @code{-eS}
7674 Output the commands for the compiler, the binder and the linker
7675 on standard output,
7676 instead of standard error.
7677 @end table
7679 @geindex -f (gnatmake)
7682 @table @asis
7684 @item @code{-f}
7686 Force recompilations. Recompile all sources, even though some object
7687 files may be up to date, but don't recompile predefined or GNAT internal
7688 files or locked files (files with a write-protected ALI file),
7689 unless the @code{-a} switch is also specified.
7690 @end table
7692 @geindex -F (gnatmake)
7695 @table @asis
7697 @item @code{-F}
7699 When using project files, if some errors or warnings are detected during
7700 parsing and verbose mode is not in effect (no use of switch
7701 -v), then error lines start with the full path name of the project
7702 file, rather than its simple file name.
7703 @end table
7705 @geindex -g (gnatmake)
7708 @table @asis
7710 @item @code{-g}
7712 Enable debugging. This switch is simply passed to the compiler and to the
7713 linker.
7714 @end table
7716 @geindex -i (gnatmake)
7719 @table @asis
7721 @item @code{-i}
7723 In normal mode, @code{gnatmake} compiles all object files and ALI files
7724 into the current directory. If the @code{-i} switch is used,
7725 then instead object files and ALI files that already exist are overwritten
7726 in place. This means that once a large project is organized into separate
7727 directories in the desired manner, then @code{gnatmake} will automatically
7728 maintain and update this organization. If no ALI files are found on the
7729 Ada object path (see @ref{89,,Search Paths and the Run-Time Library (RTL)}),
7730 the new object and ALI files are created in the
7731 directory containing the source being compiled. If another organization
7732 is desired, where objects and sources are kept in different directories,
7733 a useful technique is to create dummy ALI files in the desired directories.
7734 When detecting such a dummy file, @code{gnatmake} will be forced to
7735 recompile the corresponding source file, and it will be put the resulting
7736 object and ALI files in the directory where it found the dummy file.
7737 @end table
7739 @geindex -j (gnatmake)
7741 @geindex Parallel make
7744 @table @asis
7746 @item @code{-j@emph{n}}
7748 Use @code{n} processes to carry out the (re)compilations. On a multiprocessor
7749 machine compilations will occur in parallel. If @code{n} is 0, then the
7750 maximum number of parallel compilations is the number of core processors
7751 on the platform. In the event of compilation errors, messages from various
7752 compilations might get interspersed (but @code{gnatmake} will give you the
7753 full ordered list of failing compiles at the end). If this is problematic,
7754 rerun the make process with n set to 1 to get a clean list of messages.
7755 @end table
7757 @geindex -k (gnatmake)
7760 @table @asis
7762 @item @code{-k}
7764 Keep going. Continue as much as possible after a compilation error. To
7765 ease the programmer's task in case of compilation errors, the list of
7766 sources for which the compile fails is given when @code{gnatmake}
7767 terminates.
7769 If @code{gnatmake} is invoked with several @code{file_names} and with this
7770 switch, if there are compilation errors when building an executable,
7771 @code{gnatmake} will not attempt to build the following executables.
7772 @end table
7774 @geindex -l (gnatmake)
7777 @table @asis
7779 @item @code{-l}
7781 Link only. Can be combined with @code{-b} to binding
7782 and linking. Linking will not be performed if combined with
7783 @code{-c}
7784 but not with @code{-b}.
7785 When not combined with @code{-b}
7786 all the units in the closure of the main program must have been previously
7787 compiled and must be up to date, and the main program needs to have been bound.
7788 The root unit specified by @code{file_name}
7789 may be given without extension, with the source extension or, if no GNAT
7790 Project File is specified, with the ALI file extension.
7791 @end table
7793 @geindex -m (gnatmake)
7796 @table @asis
7798 @item @code{-m}
7800 Specify that the minimum necessary amount of recompilations
7801 be performed. In this mode @code{gnatmake} ignores time
7802 stamp differences when the only
7803 modifications to a source file consist in adding/removing comments,
7804 empty lines, spaces or tabs. This means that if you have changed the
7805 comments in a source file or have simply reformatted it, using this
7806 switch will tell @code{gnatmake} not to recompile files that depend on it
7807 (provided other sources on which these files depend have undergone no
7808 semantic modifications). Note that the debugging information may be
7809 out of date with respect to the sources if the @code{-m} switch causes
7810 a compilation to be switched, so the use of this switch represents a
7811 trade-off between compilation time and accurate debugging information.
7812 @end table
7814 @geindex Dependencies
7815 @geindex producing list
7817 @geindex -M (gnatmake)
7820 @table @asis
7822 @item @code{-M}
7824 Check if all objects are up to date. If they are, output the object
7825 dependences to @code{stdout} in a form that can be directly exploited in
7826 a @code{Makefile}. By default, each source file is prefixed with its
7827 (relative or absolute) directory name. This name is whatever you
7828 specified in the various @code{-aI}
7829 and @code{-I} switches. If you use
7830 @code{gnatmake -M}  @code{-q}
7831 (see below), only the source file names,
7832 without relative paths, are output. If you just specify the  @code{-M}
7833 switch, dependencies of the GNAT internal system files are omitted. This
7834 is typically what you want. If you also specify
7835 the @code{-a} switch,
7836 dependencies of the GNAT internal files are also listed. Note that
7837 dependencies of the objects in external Ada libraries (see
7838 switch  @code{-aL@emph{dir}} in the following list)
7839 are never reported.
7840 @end table
7842 @geindex -n (gnatmake)
7845 @table @asis
7847 @item @code{-n}
7849 Don't compile, bind, or link. Checks if all objects are up to date.
7850 If they are not, the full name of the first file that needs to be
7851 recompiled is printed.
7852 Repeated use of this option, followed by compiling the indicated source
7853 file, will eventually result in recompiling all required units.
7854 @end table
7856 @geindex -o (gnatmake)
7859 @table @asis
7861 @item @code{-o @emph{exec_name}}
7863 Output executable name. The name of the final executable program will be
7864 @code{exec_name}. If the @code{-o} switch is omitted the default
7865 name for the executable will be the name of the input file in appropriate form
7866 for an executable file on the host system.
7868 This switch cannot be used when invoking @code{gnatmake} with several
7869 @code{file_names}.
7870 @end table
7872 @geindex -p (gnatmake)
7875 @table @asis
7877 @item @code{-p}
7879 Same as @code{--create-missing-dirs}
7880 @end table
7882 @geindex -P (gnatmake)
7885 @table @asis
7887 @item @code{-P@emph{project}}
7889 Use project file @code{project}. Only one such switch can be used.
7890 @end table
7892 @c -- Comment:
7893 @c :ref:`gnatmake_and_Project_Files`.
7895 @geindex -q (gnatmake)
7898 @table @asis
7900 @item @code{-q}
7902 Quiet. When this flag is not set, the commands carried out by
7903 @code{gnatmake} are displayed.
7904 @end table
7906 @geindex -s (gnatmake)
7909 @table @asis
7911 @item @code{-s}
7913 Recompile if compiler switches have changed since last compilation.
7914 All compiler switches but -I and -o are taken into account in the
7915 following way:
7916 orders between different 'first letter' switches are ignored, but
7917 orders between same switches are taken into account. For example,
7918 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O}
7919 is equivalent to @code{-O -g}.
7921 This switch is recommended when Integrated Preprocessing is used.
7922 @end table
7924 @geindex -u (gnatmake)
7927 @table @asis
7929 @item @code{-u}
7931 Unique. Recompile at most the main files. It implies -c. Combined with
7932 -f, it is equivalent to calling the compiler directly. Note that using
7933 -u with a project file and no main has a special meaning.
7934 @end table
7936 @c --Comment
7937 @c (See :ref:`Project_Files_and_Main_Subprograms`.)
7939 @geindex -U (gnatmake)
7942 @table @asis
7944 @item @code{-U}
7946 When used without a project file or with one or several mains on the command
7947 line, is equivalent to -u. When used with a project file and no main
7948 on the command line, all sources of all project files are checked and compiled
7949 if not up to date, and libraries are rebuilt, if necessary.
7950 @end table
7952 @geindex -v (gnatmake)
7955 @table @asis
7957 @item @code{-v}
7959 Verbose. Display the reason for all recompilations @code{gnatmake}
7960 decides are necessary, with the highest verbosity level.
7961 @end table
7963 @geindex -vl (gnatmake)
7966 @table @asis
7968 @item @code{-vl}
7970 Verbosity level Low. Display fewer lines than in verbosity Medium.
7971 @end table
7973 @geindex -vm (gnatmake)
7976 @table @asis
7978 @item @code{-vm}
7980 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7981 @end table
7983 @geindex -vm (gnatmake)
7986 @table @asis
7988 @item @code{-vh}
7990 Verbosity level High. Equivalent to -v.
7992 @item @code{-vP@emph{x}}
7994 Indicate the verbosity of the parsing of GNAT project files.
7995 See @ref{de,,Switches Related to Project Files}.
7996 @end table
7998 @geindex -x (gnatmake)
8001 @table @asis
8003 @item @code{-x}
8005 Indicate that sources that are not part of any Project File may be compiled.
8006 Normally, when using Project Files, only sources that are part of a Project
8007 File may be compile. When this switch is used, a source outside of all Project
8008 Files may be compiled. The ALI file and the object file will be put in the
8009 object directory of the main Project. The compilation switches used will only
8010 be those specified on the command line. Even when
8011 @code{-x} is used, mains specified on the
8012 command line need to be sources of a project file.
8014 @item @code{-X@emph{name}=@emph{value}}
8016 Indicate that external variable @code{name} has the value @code{value}.
8017 The Project Manager will use this value for occurrences of
8018 @code{external(name)} when parsing the project file.
8019 @ref{de,,Switches Related to Project Files}.
8020 @end table
8022 @geindex -z (gnatmake)
8025 @table @asis
8027 @item @code{-z}
8029 No main subprogram. Bind and link the program even if the unit name
8030 given on the command line is a package name. The resulting executable
8031 will execute the elaboration routines of the package and its closure,
8032 then the finalization routines.
8033 @end table
8035 @subsubheading GCC switches
8038 Any uppercase or multi-character switch that is not a @code{gnatmake} switch
8039 is passed to @code{gcc} (e.g., @code{-O}, @code{-gnato,} etc.)
8041 @subsubheading Source and library search path switches
8044 @geindex -aI (gnatmake)
8047 @table @asis
8049 @item @code{-aI@emph{dir}}
8051 When looking for source files also look in directory @code{dir}.
8052 The order in which source files search is undertaken is
8053 described in @ref{89,,Search Paths and the Run-Time Library (RTL)}.
8054 @end table
8056 @geindex -aL (gnatmake)
8059 @table @asis
8061 @item @code{-aL@emph{dir}}
8063 Consider @code{dir} as being an externally provided Ada library.
8064 Instructs @code{gnatmake} to skip compilation units whose @code{.ALI}
8065 files have been located in directory @code{dir}. This allows you to have
8066 missing bodies for the units in @code{dir} and to ignore out of date bodies
8067 for the same units. You still need to specify
8068 the location of the specs for these units by using the switches
8069 @code{-aI@emph{dir}}  or @code{-I@emph{dir}}.
8070 Note: this switch is provided for compatibility with previous versions
8071 of @code{gnatmake}. The easier method of causing standard libraries
8072 to be excluded from consideration is to write-protect the corresponding
8073 ALI files.
8074 @end table
8076 @geindex -aO (gnatmake)
8079 @table @asis
8081 @item @code{-aO@emph{dir}}
8083 When searching for library and object files, look in directory
8084 @code{dir}. The order in which library files are searched is described in
8085 @ref{8c,,Search Paths for gnatbind}.
8086 @end table
8088 @geindex Search paths
8089 @geindex for gnatmake
8091 @geindex -A (gnatmake)
8094 @table @asis
8096 @item @code{-A@emph{dir}}
8098 Equivalent to @code{-aL@emph{dir}} @code{-aI@emph{dir}}.
8100 @geindex -I (gnatmake)
8102 @item @code{-I@emph{dir}}
8104 Equivalent to @code{-aO@emph{dir} -aI@emph{dir}}.
8105 @end table
8107 @geindex -I- (gnatmake)
8109 @geindex Source files
8110 @geindex suppressing search
8113 @table @asis
8115 @item @code{-I-}
8117 Do not look for source files in the directory containing the source
8118 file named in the command line.
8119 Do not look for ALI or object files in the directory
8120 where @code{gnatmake} was invoked.
8121 @end table
8123 @geindex -L (gnatmake)
8125 @geindex Linker libraries
8128 @table @asis
8130 @item @code{-L@emph{dir}}
8132 Add directory @code{dir} to the list of directories in which the linker
8133 will search for libraries. This is equivalent to
8134 @code{-largs} @code{-L@emph{dir}}.
8135 Furthermore, under Windows, the sources pointed to by the libraries path
8136 set in the registry are not searched for.
8137 @end table
8139 @geindex -nostdinc (gnatmake)
8142 @table @asis
8144 @item @code{-nostdinc}
8146 Do not look for source files in the system default directory.
8147 @end table
8149 @geindex -nostdlib (gnatmake)
8152 @table @asis
8154 @item @code{-nostdlib}
8156 Do not look for library files in the system default directory.
8157 @end table
8159 @geindex --RTS (gnatmake)
8162 @table @asis
8164 @item @code{--RTS=@emph{rts-path}}
8166 Specifies the default location of the runtime library. GNAT looks for the
8167 runtime
8168 in the following directories, and stops as soon as a valid runtime is found
8169 (@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
8170 @code{ada_object_path} present):
8173 @itemize *
8175 @item 
8176 @emph{<current directory>/$rts_path}
8178 @item 
8179 @emph{<default-search-dir>/$rts_path}
8181 @item 
8182 @emph{<default-search-dir>/rts-$rts_path}
8184 @item 
8185 The selected path is handled like a normal RTS path.
8186 @end itemize
8187 @end table
8189 @node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
8190 @anchor{gnat_ugn/building_executable_programs_with_gnat id4}@anchor{df}@anchor{gnat_ugn/building_executable_programs_with_gnat mode-switches-for-gnatmake}@anchor{e0}
8191 @subsection Mode Switches for @code{gnatmake}
8194 The mode switches (referred to as @code{mode_switches}) allow the
8195 inclusion of switches that are to be passed to the compiler itself, the
8196 binder or the linker. The effect of a mode switch is to cause all
8197 subsequent switches up to the end of the switch list, or up to the next
8198 mode switch, to be interpreted as switches to be passed on to the
8199 designated component of GNAT.
8201 @geindex -cargs (gnatmake)
8204 @table @asis
8206 @item @code{-cargs @emph{switches}}
8208 Compiler switches. Here @code{switches} is a list of switches
8209 that are valid switches for @code{gcc}. They will be passed on to
8210 all compile steps performed by @code{gnatmake}.
8211 @end table
8213 @geindex -bargs (gnatmake)
8216 @table @asis
8218 @item @code{-bargs @emph{switches}}
8220 Binder switches. Here @code{switches} is a list of switches
8221 that are valid switches for @code{gnatbind}. They will be passed on to
8222 all bind steps performed by @code{gnatmake}.
8223 @end table
8225 @geindex -largs (gnatmake)
8228 @table @asis
8230 @item @code{-largs @emph{switches}}
8232 Linker switches. Here @code{switches} is a list of switches
8233 that are valid switches for @code{gnatlink}. They will be passed on to
8234 all link steps performed by @code{gnatmake}.
8235 @end table
8237 @geindex -margs (gnatmake)
8240 @table @asis
8242 @item @code{-margs @emph{switches}}
8244 Make switches. The switches are directly interpreted by @code{gnatmake},
8245 regardless of any previous occurrence of @code{-cargs}, @code{-bargs}
8246 or @code{-largs}.
8247 @end table
8249 @node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
8250 @anchor{gnat_ugn/building_executable_programs_with_gnat id5}@anchor{e1}@anchor{gnat_ugn/building_executable_programs_with_gnat notes-on-the-command-line}@anchor{e2}
8251 @subsection Notes on the Command Line
8254 This section contains some additional useful notes on the operation
8255 of the @code{gnatmake} command.
8257 @geindex Recompilation (by gnatmake)
8260 @itemize *
8262 @item 
8263 If @code{gnatmake} finds no ALI files, it recompiles the main program
8264 and all other units required by the main program.
8265 This means that @code{gnatmake}
8266 can be used for the initial compile, as well as during subsequent steps of
8267 the development cycle.
8269 @item 
8270 If you enter @code{gnatmake foo.adb}, where @code{foo}
8271 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8272 @code{foo.adb} (because it finds no ALI) and stops, issuing a
8273 warning.
8275 @item 
8276 In @code{gnatmake} the switch @code{-I}
8277 is used to specify both source and
8278 library file paths. Use @code{-aI}
8279 instead if you just want to specify
8280 source paths only and @code{-aO}
8281 if you want to specify library paths
8282 only.
8284 @item 
8285 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8286 This may conveniently be used to exclude standard libraries from
8287 consideration and in particular it means that the use of the
8288 @code{-f} switch will not recompile these files
8289 unless @code{-a} is also specified.
8291 @item 
8292 @code{gnatmake} has been designed to make the use of Ada libraries
8293 particularly convenient. Assume you have an Ada library organized
8294 as follows: @emph{obj-dir} contains the objects and ALI files for
8295 of your Ada compilation units,
8296 whereas @emph{include-dir} contains the
8297 specs of these units, but no bodies. Then to compile a unit
8298 stored in @code{main.adb}, which uses this Ada library you would just type:
8300 @example
8301 $ gnatmake -aI`include-dir`  -aL`obj-dir`  main
8302 @end example
8304 @item 
8305 Using @code{gnatmake} along with the @code{-m (minimal recompilation)}
8306 switch provides a mechanism for avoiding unnecessary recompilations. Using
8307 this switch,
8308 you can update the comments/format of your
8309 source files without having to recompile everything. Note, however, that
8310 adding or deleting lines in a source files may render its debugging
8311 info obsolete. If the file in question is a spec, the impact is rather
8312 limited, as that debugging info will only be useful during the
8313 elaboration phase of your program. For bodies the impact can be more
8314 significant. In all events, your debugger will warn you if a source file
8315 is more recent than the corresponding object, and alert you to the fact
8316 that the debugging information may be out of date.
8317 @end itemize
8319 @node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8320 @anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{e3}@anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{e4}
8321 @subsection How @code{gnatmake} Works
8324 Generally @code{gnatmake} automatically performs all necessary
8325 recompilations and you don't need to worry about how it works. However,
8326 it may be useful to have some basic understanding of the @code{gnatmake}
8327 approach and in particular to understand how it uses the results of
8328 previous compilations without incorrectly depending on them.
8330 First a definition: an object file is considered @emph{up to date} if the
8331 corresponding ALI file exists and if all the source files listed in the
8332 dependency section of this ALI file have time stamps matching those in
8333 the ALI file. This means that neither the source file itself nor any
8334 files that it depends on have been modified, and hence there is no need
8335 to recompile this file.
8337 @code{gnatmake} works by first checking if the specified main unit is up
8338 to date. If so, no compilations are required for the main unit. If not,
8339 @code{gnatmake} compiles the main program to build a new ALI file that
8340 reflects the latest sources. Then the ALI file of the main unit is
8341 examined to find all the source files on which the main program depends,
8342 and @code{gnatmake} recursively applies the above procedure on all these
8343 files.
8345 This process ensures that @code{gnatmake} only trusts the dependencies
8346 in an existing ALI file if they are known to be correct. Otherwise it
8347 always recompiles to determine a new, guaranteed accurate set of
8348 dependencies. As a result the program is compiled 'upside down' from what may
8349 be more familiar as the required order of compilation in some other Ada
8350 systems. In particular, clients are compiled before the units on which
8351 they depend. The ability of GNAT to compile in any order is critical in
8352 allowing an order of compilation to be chosen that guarantees that
8353 @code{gnatmake} will recompute a correct set of new dependencies if
8354 necessary.
8356 When invoking @code{gnatmake} with several @code{file_names}, if a unit is
8357 imported by several of the executables, it will be recompiled at most once.
8359 Note: when using non-standard naming conventions
8360 (@ref{35,,Using Other File Names}), changing through a configuration pragmas
8361 file the version of a source and invoking @code{gnatmake} to recompile may
8362 have no effect, if the previous version of the source is still accessible
8363 by @code{gnatmake}. It may be necessary to use the switch
8366 @node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8367 @anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatmake-usage}@anchor{e5}@anchor{gnat_ugn/building_executable_programs_with_gnat id7}@anchor{e6}
8368 @subsection Examples of @code{gnatmake} Usage
8372 @table @asis
8374 @item @emph{gnatmake hello.adb}
8376 Compile all files necessary to bind and link the main program
8377 @code{hello.adb} (containing unit @code{Hello}) and bind and link the
8378 resulting object files to generate an executable file @code{hello}.
8380 @item @emph{gnatmake main1 main2 main3}
8382 Compile all files necessary to bind and link the main programs
8383 @code{main1.adb} (containing unit @code{Main1}), @code{main2.adb}
8384 (containing unit @code{Main2}) and @code{main3.adb}
8385 (containing unit @code{Main3}) and bind and link the resulting object files
8386 to generate three executable files @code{main1},
8387 @code{main2}  and @code{main3}.
8389 @item @emph{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8391 Compile all files necessary to bind and link the main program unit
8392 @code{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8393 be done with optimization level 2 and the order of elaboration will be
8394 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8395 displaying commands it is executing.
8396 @end table
8398 @node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8399 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{1c}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{e7}
8400 @section Compiling with @code{gcc}
8403 This section discusses how to compile Ada programs using the @code{gcc}
8404 command. It also describes the set of switches
8405 that can be used to control the behavior of the compiler.
8407 @menu
8408 * Compiling Programs:: 
8409 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
8410 * Order of Compilation Issues:: 
8411 * Examples:: 
8413 @end menu
8415 @node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8416 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{e8}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{e9}
8417 @subsection Compiling Programs
8420 The first step in creating an executable program is to compile the units
8421 of the program using the @code{gcc} command. You must compile the
8422 following files:
8425 @itemize *
8427 @item 
8428 the body file (@code{.adb}) for a library level subprogram or generic
8429 subprogram
8431 @item 
8432 the spec file (@code{.ads}) for a library level package or generic
8433 package that has no body
8435 @item 
8436 the body file (@code{.adb}) for a library level package
8437 or generic package that has a body
8438 @end itemize
8440 You need @emph{not} compile the following files
8443 @itemize *
8445 @item 
8446 the spec of a library unit which has a body
8448 @item 
8449 subunits
8450 @end itemize
8452 because they are compiled as part of compiling related units. GNAT
8453 package specs
8454 when the corresponding body is compiled, and subunits when the parent is
8455 compiled.
8457 @geindex cannot generate code
8459 If you attempt to compile any of these files, you will get one of the
8460 following error messages (where @code{fff} is the name of the file you
8461 compiled):
8463 @quotation
8465 @example
8466 cannot generate code for file `@w{`}fff`@w{`} (package spec)
8467 to check package spec, use -gnatc
8469 cannot generate code for file `@w{`}fff`@w{`} (missing subunits)
8470 to check parent unit, use -gnatc
8472 cannot generate code for file `@w{`}fff`@w{`} (subprogram spec)
8473 to check subprogram spec, use -gnatc
8475 cannot generate code for file `@w{`}fff`@w{`} (subunit)
8476 to check subunit, use -gnatc
8477 @end example
8478 @end quotation
8480 As indicated by the above error messages, if you want to submit
8481 one of these files to the compiler to check for correct semantics
8482 without generating code, then use the @code{-gnatc} switch.
8484 The basic command for compiling a file containing an Ada unit is:
8486 @example
8487 $ gcc -c [switches] <file name>
8488 @end example
8490 where @code{file name} is the name of the Ada file (usually
8491 having an extension @code{.ads} for a spec or @code{.adb} for a body).
8492 You specify the
8493 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
8494 The result of a successful compilation is an object file, which has the
8495 same name as the source file but an extension of @code{.o} and an Ada
8496 Library Information (ALI) file, which also has the same name as the
8497 source file, but with @code{.ali} as the extension. GNAT creates these
8498 two output files in the current directory, but you may specify a source
8499 file in any directory using an absolute or relative path specification
8500 containing the directory information.
8502 TESTING: the @code{--foobar@emph{NN}} switch
8504 @geindex gnat1
8506 @code{gcc} is actually a driver program that looks at the extensions of
8507 the file arguments and loads the appropriate compiler. For example, the
8508 GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8509 These programs are in directories known to the driver program (in some
8510 configurations via environment variables you set), but need not be in
8511 your path. The @code{gcc} driver also calls the assembler and any other
8512 utilities needed to complete the generation of the required object
8513 files.
8515 It is possible to supply several file names on the same @code{gcc}
8516 command. This causes @code{gcc} to call the appropriate compiler for
8517 each file. For example, the following command lists two separate
8518 files to be compiled:
8520 @example
8521 $ gcc -c x.adb y.adb
8522 @end example
8524 calls @code{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8525 @code{y.adb}.
8526 The compiler generates two object files @code{x.o} and @code{y.o}
8527 and the two ALI files @code{x.ali} and @code{y.ali}.
8529 Any switches apply to all the files listed, see @ref{ea,,Compiler Switches} for a
8530 list of available @code{gcc} switches.
8532 @node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8533 @anchor{gnat_ugn/building_executable_programs_with_gnat id10}@anchor{eb}@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-and-the-run-time-library-rtl}@anchor{89}
8534 @subsection Search Paths and the Run-Time Library (RTL)
8537 With the GNAT source-based library system, the compiler must be able to
8538 find source files for units that are needed by the unit being compiled.
8539 Search paths are used to guide this process.
8541 The compiler compiles one source file whose name must be given
8542 explicitly on the command line. In other words, no searching is done
8543 for this file. To find all other source files that are needed (the most
8544 common being the specs of units), the compiler examines the following
8545 directories, in the following order:
8548 @itemize *
8550 @item 
8551 The directory containing the source file of the main unit being compiled
8552 (the file name on the command line).
8554 @item 
8555 Each directory named by an @code{-I} switch given on the @code{gcc}
8556 command line, in the order given.
8558 @geindex ADA_PRJ_INCLUDE_FILE
8560 @item 
8561 Each of the directories listed in the text file whose name is given
8562 by the 
8563 @geindex ADA_PRJ_INCLUDE_FILE
8564 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8565 @code{ADA_PRJ_INCLUDE_FILE} environment variable.
8566 @geindex ADA_PRJ_INCLUDE_FILE
8567 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8568 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8569 driver when project files are used. It should not normally be set
8570 by other means.
8572 @geindex ADA_INCLUDE_PATH
8574 @item 
8575 Each of the directories listed in the value of the
8576 @geindex ADA_INCLUDE_PATH
8577 @geindex environment variable; ADA_INCLUDE_PATH
8578 @code{ADA_INCLUDE_PATH} environment variable.
8579 Construct this value
8580 exactly as the 
8581 @geindex PATH
8582 @geindex environment variable; PATH
8583 @code{PATH} environment variable: a list of directory
8584 names separated by colons (semicolons when working with the NT version).
8586 @item 
8587 The content of the @code{ada_source_path} file which is part of the GNAT
8588 installation tree and is used to store standard libraries such as the
8589 GNAT Run Time Library (RTL) source files.
8590 @ref{87,,Installing a library}
8591 @end itemize
8593 Specifying the switch @code{-I-}
8594 inhibits the use of the directory
8595 containing the source file named in the command line. You can still
8596 have this directory on your search path, but in this case it must be
8597 explicitly requested with a @code{-I} switch.
8599 Specifying the switch @code{-nostdinc}
8600 inhibits the search of the default location for the GNAT Run Time
8601 Library (RTL) source files.
8603 The compiler outputs its object files and ALI files in the current
8604 working directory.
8605 Caution: The object file can be redirected with the @code{-o} switch;
8606 however, @code{gcc} and @code{gnat1} have not been coordinated on this
8607 so the @code{ALI} file will not go to the right place. Therefore, you should
8608 avoid using the @code{-o} switch.
8610 @geindex System.IO
8612 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8613 children make up the GNAT RTL, together with the simple @code{System.IO}
8614 package used in the @code{"Hello World"} example. The sources for these units
8615 are needed by the compiler and are kept together in one directory. Not
8616 all of the bodies are needed, but all of the sources are kept together
8617 anyway. In a normal installation, you need not specify these directory
8618 names when compiling or binding. Either the environment variables or
8619 the built-in defaults cause these files to be found.
8621 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8622 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8623 consisting of child units of @code{GNAT}. This is a collection of generally
8624 useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8625 for further details.
8627 Besides simplifying access to the RTL, a major use of search paths is
8628 in compiling sources from multiple directories. This can make
8629 development environments much more flexible.
8631 @node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8632 @anchor{gnat_ugn/building_executable_programs_with_gnat id11}@anchor{ec}@anchor{gnat_ugn/building_executable_programs_with_gnat order-of-compilation-issues}@anchor{ed}
8633 @subsection Order of Compilation Issues
8636 If, in our earlier example, there was a spec for the @code{hello}
8637 procedure, it would be contained in the file @code{hello.ads}; yet this
8638 file would not have to be explicitly compiled. This is the result of the
8639 model we chose to implement library management. Some of the consequences
8640 of this model are as follows:
8643 @itemize *
8645 @item 
8646 There is no point in compiling specs (except for package
8647 specs with no bodies) because these are compiled as needed by clients. If
8648 you attempt a useless compilation, you will receive an error message.
8649 It is also useless to compile subunits because they are compiled as needed
8650 by the parent.
8652 @item 
8653 There are no order of compilation requirements: performing a
8654 compilation never obsoletes anything. The only way you can obsolete
8655 something and require recompilations is to modify one of the
8656 source files on which it depends.
8658 @item 
8659 There is no library as such, apart from the ALI files
8660 (@ref{42,,The Ada Library Information Files}, for information on the format
8661 of these files). For now we find it convenient to create separate ALI files,
8662 but eventually the information therein may be incorporated into the object
8663 file directly.
8665 @item 
8666 When you compile a unit, the source files for the specs of all units
8667 that it @emph{with}s, all its subunits, and the bodies of any generics it
8668 instantiates must be available (reachable by the search-paths mechanism
8669 described above), or you will receive a fatal error message.
8670 @end itemize
8672 @node Examples,,Order of Compilation Issues,Compiling with gcc
8673 @anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{ee}@anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{ef}
8674 @subsection Examples
8677 The following are some typical Ada compilation command line examples:
8679 @example
8680 $ gcc -c xyz.adb
8681 @end example
8683 Compile body in file @code{xyz.adb} with all default options.
8685 @example
8686 $ gcc -c -O2 -gnata xyz-def.adb
8687 @end example
8689 Compile the child unit package in file @code{xyz-def.adb} with extensive
8690 optimizations, and pragma @code{Assert}/@cite{Debug} statements
8691 enabled.
8693 @example
8694 $ gcc -c -gnatc abc-def.adb
8695 @end example
8697 Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8698 mode.
8700 @node Compiler Switches,Linker Switches,Compiling with gcc,Building Executable Programs with GNAT
8701 @anchor{gnat_ugn/building_executable_programs_with_gnat compiler-switches}@anchor{f0}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gcc}@anchor{ea}
8702 @section Compiler Switches
8705 The @code{gcc} command accepts switches that control the
8706 compilation process. These switches are fully described in this section:
8707 first an alphabetical listing of all switches with a brief description,
8708 and then functionally grouped sets of switches with more detailed
8709 information.
8711 More switches exist for GCC than those documented here, especially
8712 for specific targets. However, their use is not recommended as
8713 they may change code generation in ways that are incompatible with
8714 the Ada run-time library, or can cause inconsistencies between
8715 compilation units.
8717 @menu
8718 * Alphabetical List of All Switches:: 
8719 * Output and Error Message Control:: 
8720 * Warning Message Control:: 
8721 * Debugging and Assertion Control:: 
8722 * Validity Checking:: 
8723 * Style Checking:: 
8724 * Run-Time Checks:: 
8725 * Using gcc for Syntax Checking:: 
8726 * Using gcc for Semantic Checking:: 
8727 * Compiling Different Versions of Ada:: 
8728 * Character Set Control:: 
8729 * File Naming Control:: 
8730 * Subprogram Inlining Control:: 
8731 * Auxiliary Output Control:: 
8732 * Debugging Control:: 
8733 * Exception Handling Control:: 
8734 * Units to Sources Mapping Files:: 
8735 * Code Generation Control:: 
8737 @end menu
8739 @node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8740 @anchor{gnat_ugn/building_executable_programs_with_gnat id13}@anchor{f1}@anchor{gnat_ugn/building_executable_programs_with_gnat alphabetical-list-of-all-switches}@anchor{f2}
8741 @subsection Alphabetical List of All Switches
8744 @geindex -b (gcc)
8747 @table @asis
8749 @item @code{-b @emph{target}}
8751 Compile your program to run on @code{target}, which is the name of a
8752 system configuration. You must have a GNAT cross-compiler built if
8753 @code{target} is not the same as your host system.
8754 @end table
8756 @geindex -B (gcc)
8759 @table @asis
8761 @item @code{-B@emph{dir}}
8763 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8764 from @code{dir} instead of the default location. Only use this switch
8765 when multiple versions of the GNAT compiler are available.
8766 See the "Options for Directory Search" section in the
8767 @cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8768 You would normally use the @code{-b} or @code{-V} switch instead.
8769 @end table
8771 @geindex -c (gcc)
8774 @table @asis
8776 @item @code{-c}
8778 Compile. Always use this switch when compiling Ada programs.
8780 Note: for some other languages when using @code{gcc}, notably in
8781 the case of C and C++, it is possible to use
8782 use @code{gcc} without a @code{-c} switch to
8783 compile and link in one step. In the case of GNAT, you
8784 cannot use this approach, because the binder must be run
8785 and @code{gcc} cannot be used to run the GNAT binder.
8786 @end table
8788 @geindex -fcallgraph-info (gcc)
8791 @table @asis
8793 @item @code{-fcallgraph-info[=su,da]}
8795 Makes the compiler output callgraph information for the program, on a
8796 per-file basis. The information is generated in the VCG format.  It can
8797 be decorated with additional, per-node and/or per-edge information, if a
8798 list of comma-separated markers is additionally specified. When the
8799 @code{su} marker is specified, the callgraph is decorated with stack usage
8800 information; it is equivalent to @code{-fstack-usage}. When the @code{da}
8801 marker is specified, the callgraph is decorated with information about
8802 dynamically allocated objects.
8803 @end table
8805 @geindex -fdump-scos (gcc)
8808 @table @asis
8810 @item @code{-fdump-scos}
8812 Generates SCO (Source Coverage Obligation) information in the ALI file.
8813 This information is used by advanced coverage tools. See unit @code{SCOs}
8814 in the compiler sources for details in files @code{scos.ads} and
8815 @code{scos.adb}.
8816 @end table
8818 @geindex -flto (gcc)
8821 @table @asis
8823 @item @code{-flto[=@emph{n}]}
8825 Enables Link Time Optimization. This switch must be used in conjunction
8826 with the @code{-Ox} switches (but not with the @code{-gnatn} switch
8827 since it is a full replacement for the latter) and instructs the compiler
8828 to defer most optimizations until the link stage. The advantage of this
8829 approach is that the compiler can do a whole-program analysis and choose
8830 the best interprocedural optimization strategy based on a complete view
8831 of the program, instead of a fragmentary view with the usual approach.
8832 This can also speed up the compilation of big programs and reduce the
8833 size of the executable, compared with a traditional per-unit compilation
8834 with inlining across modules enabled by the @code{-gnatn} switch.
8835 The drawback of this approach is that it may require more memory and that
8836 the debugging information generated by -g with it might be hardly usable.
8837 The switch, as well as the accompanying @code{-Ox} switches, must be
8838 specified both for the compilation and the link phases.
8839 If the @code{n} parameter is specified, the optimization and final code
8840 generation at link time are executed using @code{n} parallel jobs by
8841 means of an installed @code{make} program.
8842 @end table
8844 @geindex -fno-inline (gcc)
8847 @table @asis
8849 @item @code{-fno-inline}
8851 Suppresses all inlining, unless requested with pragma @code{Inline_Always}. The
8852 effect is enforced regardless of other optimization or inlining switches.
8853 Note that inlining can also be suppressed on a finer-grained basis with
8854 pragma @code{No_Inline}.
8855 @end table
8857 @geindex -fno-inline-functions (gcc)
8860 @table @asis
8862 @item @code{-fno-inline-functions}
8864 Suppresses automatic inlining of subprograms, which is enabled
8865 if @code{-O3} is used.
8866 @end table
8868 @geindex -fno-inline-small-functions (gcc)
8871 @table @asis
8873 @item @code{-fno-inline-small-functions}
8875 Suppresses automatic inlining of small subprograms, which is enabled
8876 if @code{-O2} is used.
8877 @end table
8879 @geindex -fno-inline-functions-called-once (gcc)
8882 @table @asis
8884 @item @code{-fno-inline-functions-called-once}
8886 Suppresses inlining of subprograms local to the unit and called once
8887 from within it, which is enabled if @code{-O1} is used.
8888 @end table
8890 @geindex -fno-ivopts (gcc)
8893 @table @asis
8895 @item @code{-fno-ivopts}
8897 Suppresses high-level loop induction variable optimizations, which are
8898 enabled if @code{-O1} is used. These optimizations are generally
8899 profitable but, for some specific cases of loops with numerous uses
8900 of the iteration variable that follow a common pattern, they may end
8901 up destroying the regularity that could be exploited at a lower level
8902 and thus producing inferior code.
8903 @end table
8905 @geindex -fno-strict-aliasing (gcc)
8908 @table @asis
8910 @item @code{-fno-strict-aliasing}
8912 Causes the compiler to avoid assumptions regarding non-aliasing
8913 of objects of different types. See
8914 @ref{f3,,Optimization and Strict Aliasing} for details.
8915 @end table
8917 @geindex -fno-strict-overflow (gcc)
8920 @table @asis
8922 @item @code{-fno-strict-overflow}
8924 Causes the compiler to avoid assumptions regarding the rules of signed
8925 integer overflow. These rules specify that signed integer overflow will
8926 result in a Constraint_Error exception at run time and are enforced in
8927 default mode by the compiler, so this switch should not be necessary in
8928 normal operating mode. It might be useful in conjunction with @code{-gnato0}
8929 for very peculiar cases of low-level programming.
8930 @end table
8932 @geindex -fstack-check (gcc)
8935 @table @asis
8937 @item @code{-fstack-check}
8939 Activates stack checking.
8940 See @ref{f4,,Stack Overflow Checking} for details.
8941 @end table
8943 @geindex -fstack-usage (gcc)
8946 @table @asis
8948 @item @code{-fstack-usage}
8950 Makes the compiler output stack usage information for the program, on a
8951 per-subprogram basis. See @ref{f5,,Static Stack Usage Analysis} for details.
8952 @end table
8954 @geindex -g (gcc)
8957 @table @asis
8959 @item @code{-g}
8961 Generate debugging information. This information is stored in the object
8962 file and copied from there to the final executable file by the linker,
8963 where it can be read by the debugger. You must use the
8964 @code{-g} switch if you plan on using the debugger.
8965 @end table
8967 @geindex -gnat05 (gcc)
8970 @table @asis
8972 @item @code{-gnat05}
8974 Allow full Ada 2005 features.
8975 @end table
8977 @geindex -gnat12 (gcc)
8980 @table @asis
8982 @item @code{-gnat12}
8984 Allow full Ada 2012 features.
8985 @end table
8987 @geindex -gnat83 (gcc)
8989 @geindex -gnat2005 (gcc)
8992 @table @asis
8994 @item @code{-gnat2005}
8996 Allow full Ada 2005 features (same as @code{-gnat05})
8997 @end table
8999 @geindex -gnat2012 (gcc)
9002 @table @asis
9004 @item @code{-gnat2012}
9006 Allow full Ada 2012 features (same as @code{-gnat12})
9008 @item @code{-gnat83}
9010 Enforce Ada 83 restrictions.
9011 @end table
9013 @geindex -gnat95 (gcc)
9016 @table @asis
9018 @item @code{-gnat95}
9020 Enforce Ada 95 restrictions.
9022 Note: for compatibility with some Ada 95 compilers which support only
9023 the @code{overriding} keyword of Ada 2005, the @code{-gnatd.D} switch can
9024 be used along with @code{-gnat95} to achieve a similar effect with GNAT.
9026 @code{-gnatd.D} instructs GNAT to consider @code{overriding} as a keyword
9027 and handle its associated semantic checks, even in Ada 95 mode.
9028 @end table
9030 @geindex -gnata (gcc)
9033 @table @asis
9035 @item @code{-gnata}
9037 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
9038 activated. Note that these pragmas can also be controlled using the
9039 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
9040 It also activates pragmas @code{Check}, @code{Precondition}, and
9041 @code{Postcondition}. Note that these pragmas can also be controlled
9042 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
9043 also activates all assertions defined in the RM as aspects: preconditions,
9044 postconditions, type invariants and (sub)type predicates. In all Ada modes,
9045 corresponding pragmas for type invariants and (sub)type predicates are
9046 also activated. The default is that all these assertions are disabled,
9047 and have no effect, other than being checked for syntactic validity, and
9048 in the case of subtype predicates, constructions such as membership tests
9049 still test predicates even if assertions are turned off.
9050 @end table
9052 @geindex -gnatA (gcc)
9055 @table @asis
9057 @item @code{-gnatA}
9059 Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
9060 it will be ignored.
9061 @end table
9063 @geindex -gnatb (gcc)
9066 @table @asis
9068 @item @code{-gnatb}
9070 Generate brief messages to @code{stderr} even if verbose mode set.
9071 @end table
9073 @geindex -gnatB (gcc)
9076 @table @asis
9078 @item @code{-gnatB}
9080 Assume no invalid (bad) values except for 'Valid attribute use
9081 (@ref{f6,,Validity Checking}).
9082 @end table
9084 @geindex -gnatc (gcc)
9087 @table @asis
9089 @item @code{-gnatc}
9091 Check syntax and semantics only (no code generation attempted). When the
9092 compiler is invoked by @code{gnatmake}, if the switch @code{-gnatc} is
9093 only given to the compiler (after @code{-cargs} or in package Compiler of
9094 the project file, @code{gnatmake} will fail because it will not find the
9095 object file after compilation. If @code{gnatmake} is called with
9096 @code{-gnatc} as a builder switch (before @code{-cargs} or in package
9097 Builder of the project file) then @code{gnatmake} will not fail because
9098 it will not look for the object files after compilation, and it will not try
9099 to build and link.
9100 @end table
9102 @geindex -gnatC (gcc)
9105 @table @asis
9107 @item @code{-gnatC}
9109 Generate CodePeer intermediate format (no code generation attempted).
9110 This switch will generate an intermediate representation suitable for
9111 use by CodePeer (@code{.scil} files). This switch is not compatible with
9112 code generation (it will, among other things, disable some switches such
9113 as -gnatn, and enable others such as -gnata).
9114 @end table
9116 @geindex -gnatd (gcc)
9119 @table @asis
9121 @item @code{-gnatd}
9123 Specify debug options for the compiler. The string of characters after
9124 the @code{-gnatd} specify the specific debug options. The possible
9125 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
9126 compiler source file @code{debug.adb} for details of the implemented
9127 debug options. Certain debug options are relevant to applications
9128 programmers, and these are documented at appropriate points in this
9129 users guide.
9130 @end table
9132 @geindex -gnatD[nn] (gcc)
9135 @table @asis
9137 @item @code{-gnatD}
9139 Create expanded source files for source level debugging. This switch
9140 also suppresses generation of cross-reference information
9141 (see @code{-gnatx}). Note that this switch is not allowed if a previous
9142 -gnatR switch has been given, since these two switches are not compatible.
9143 @end table
9145 @geindex -gnateA (gcc)
9148 @table @asis
9150 @item @code{-gnateA}
9152 Check that the actual parameters of a subprogram call are not aliases of one
9153 another. To qualify as aliasing, the actuals must denote objects of a composite
9154 type, their memory locations must be identical or overlapping, and at least one
9155 of the corresponding formal parameters must be of mode OUT or IN OUT.
9157 @example
9158 type Rec_Typ is record
9159    Data : Integer := 0;
9160 end record;
9162 function Self (Val : Rec_Typ) return Rec_Typ is
9163 begin
9164    return Val;
9165 end Self;
9167 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
9168 begin
9169    null;
9170 end Detect_Aliasing;
9172 Obj : Rec_Typ;
9174 Detect_Aliasing (Obj, Obj);
9175 Detect_Aliasing (Obj, Self (Obj));
9176 @end example
9178 In the example above, the first call to @code{Detect_Aliasing} fails with a
9179 @code{Program_Error} at runtime because the actuals for @code{Val_1} and
9180 @code{Val_2} denote the same object. The second call executes without raising
9181 an exception because @code{Self(Obj)} produces an anonymous object which does
9182 not share the memory location of @code{Obj}.
9183 @end table
9185 @geindex -gnatec (gcc)
9188 @table @asis
9190 @item @code{-gnatec=@emph{path}}
9192 Specify a configuration pragma file
9193 (the equal sign is optional)
9194 (@ref{79,,The Configuration Pragmas Files}).
9195 @end table
9197 @geindex -gnateC (gcc)
9200 @table @asis
9202 @item @code{-gnateC}
9204 Generate CodePeer messages in a compiler-like format. This switch is only
9205 effective if @code{-gnatcC} is also specified and requires an installation
9206 of CodePeer.
9207 @end table
9209 @geindex -gnated (gcc)
9212 @table @asis
9214 @item @code{-gnated}
9216 Disable atomic synchronization
9217 @end table
9219 @geindex -gnateD (gcc)
9222 @table @asis
9224 @item @code{-gnateDsymbol[=@emph{value}]}
9226 Defines a symbol, associated with @code{value}, for preprocessing.
9227 (@ref{18,,Integrated Preprocessing}).
9228 @end table
9230 @geindex -gnateE (gcc)
9233 @table @asis
9235 @item @code{-gnateE}
9237 Generate extra information in exception messages. In particular, display
9238 extra column information and the value and range associated with index and
9239 range check failures, and extra column information for access checks.
9240 In cases where the compiler is able to determine at compile time that
9241 a check will fail, it gives a warning, and the extra information is not
9242 produced at run time.
9243 @end table
9245 @geindex -gnatef (gcc)
9248 @table @asis
9250 @item @code{-gnatef}
9252 Display full source path name in brief error messages.
9253 @end table
9255 @geindex -gnateF (gcc)
9258 @table @asis
9260 @item @code{-gnateF}
9262 Check for overflow on all floating-point operations, including those
9263 for unconstrained predefined types. See description of pragma
9264 @code{Check_Float_Overflow} in GNAT RM.
9265 @end table
9267 @geindex -gnateg (gcc)
9269 @code{-gnateg}
9270 @code{-gnatceg}
9272 @quotation
9274 The @code{-gnatc} switch must always be specified before this switch, e.g.
9275 @code{-gnatceg}. Generate a C header from the Ada input file. See
9276 @ref{ca,,Generating C Headers for Ada Specifications} for more
9277 information.
9278 @end quotation
9280 @geindex -gnateG (gcc)
9283 @table @asis
9285 @item @code{-gnateG}
9287 Save result of preprocessing in a text file.
9288 @end table
9290 @geindex -gnatei (gcc)
9293 @table @asis
9295 @item @code{-gnatei@emph{nnn}}
9297 Set maximum number of instantiations during compilation of a single unit to
9298 @code{nnn}. This may be useful in increasing the default maximum of 8000 for
9299 the rare case when a single unit legitimately exceeds this limit.
9300 @end table
9302 @geindex -gnateI (gcc)
9305 @table @asis
9307 @item @code{-gnateI@emph{nnn}}
9309 Indicates that the source is a multi-unit source and that the index of the
9310 unit to compile is @code{nnn}. @code{nnn} needs to be a positive number and need
9311 to be a valid index in the multi-unit source.
9312 @end table
9314 @geindex -gnatel (gcc)
9317 @table @asis
9319 @item @code{-gnatel}
9321 This switch can be used with the static elaboration model to issue info
9322 messages showing
9323 where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
9324 are generated. This is useful in diagnosing elaboration circularities
9325 caused by these implicit pragmas when using the static elaboration
9326 model. See See the section in this guide on elaboration checking for
9327 further details. These messages are not generated by default, and are
9328 intended only for temporary use when debugging circularity problems.
9329 @end table
9331 @geindex -gnatel (gcc)
9334 @table @asis
9336 @item @code{-gnateL}
9338 This switch turns off the info messages about implicit elaboration pragmas.
9339 @end table
9341 @geindex -gnatem (gcc)
9344 @table @asis
9346 @item @code{-gnatem=@emph{path}}
9348 Specify a mapping file
9349 (the equal sign is optional)
9350 (@ref{f7,,Units to Sources Mapping Files}).
9351 @end table
9353 @geindex -gnatep (gcc)
9356 @table @asis
9358 @item @code{-gnatep=@emph{file}}
9360 Specify a preprocessing data file
9361 (the equal sign is optional)
9362 (@ref{18,,Integrated Preprocessing}).
9363 @end table
9365 @geindex -gnateP (gcc)
9368 @table @asis
9370 @item @code{-gnateP}
9372 Turn categorization dependency errors into warnings.
9373 Ada requires that units that WITH one another have compatible categories, for
9374 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9375 these errors become warnings (which can be ignored, or suppressed in the usual
9376 manner). This can be useful in some specialized circumstances such as the
9377 temporary use of special test software.
9378 @end table
9380 @geindex -gnateS (gcc)
9383 @table @asis
9385 @item @code{-gnateS}
9387 Synonym of @code{-fdump-scos}, kept for backwards compatibility.
9388 @end table
9390 @geindex -gnatet=file (gcc)
9393 @table @asis
9395 @item @code{-gnatet=@emph{path}}
9397 Generate target dependent information. The format of the output file is
9398 described in the section about switch @code{-gnateT}.
9399 @end table
9401 @geindex -gnateT (gcc)
9404 @table @asis
9406 @item @code{-gnateT=@emph{path}}
9408 Read target dependent information, such as endianness or sizes and alignments
9409 of base type. If this switch is passed, the default target dependent
9410 information of the compiler is replaced by the one read from the input file.
9411 This is used by tools other than the compiler, e.g. to do
9412 semantic analysis of programs that will run on some other target than
9413 the machine on which the tool is run.
9415 The following target dependent values should be defined,
9416 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
9417 positive integer value, and fields marked with a question mark are
9418 boolean fields, where a value of 0 is False, and a value of 1 is True:
9420 @example
9421 Bits_BE                    : Nat; -- Bits stored big-endian?
9422 Bits_Per_Unit              : Pos; -- Bits in a storage unit
9423 Bits_Per_Word              : Pos; -- Bits in a word
9424 Bytes_BE                   : Nat; -- Bytes stored big-endian?
9425 Char_Size                  : Pos; -- Standard.Character'Size
9426 Double_Float_Alignment     : Nat; -- Alignment of double float
9427 Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
9428 Double_Size                : Pos; -- Standard.Long_Float'Size
9429 Float_Size                 : Pos; -- Standard.Float'Size
9430 Float_Words_BE             : Nat; -- Float words stored big-endian?
9431 Int_Size                   : Pos; -- Standard.Integer'Size
9432 Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
9433 Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
9434 Long_Size                  : Pos; -- Standard.Long_Integer'Size
9435 Maximum_Alignment          : Pos; -- Maximum permitted alignment
9436 Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
9437 Pointer_Size               : Pos; -- System.Address'Size
9438 Short_Enums                : Nat; -- Short foreign convention enums?
9439 Short_Size                 : Pos; -- Standard.Short_Integer'Size
9440 Strict_Alignment           : Nat; -- Strict alignment?
9441 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9442 Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
9443 Words_BE                   : Nat; -- Words stored big-endian?
9444 @end example
9446 The format of the input file is as follows. First come the values of
9447 the variables defined above, with one line per value:
9449 @example
9450 name  value
9451 @end example
9453 where @code{name} is the name of the parameter, spelled out in full,
9454 and cased as in the above list, and @code{value} is an unsigned decimal
9455 integer. Two or more blanks separates the name from the value.
9457 All the variables must be present, in alphabetical order (i.e. the
9458 same order as the list above).
9460 Then there is a blank line to separate the two parts of the file. Then
9461 come the lines showing the floating-point types to be registered, with
9462 one line per registered mode:
9464 @example
9465 name  digs float_rep size alignment
9466 @end example
9468 where @code{name} is the string name of the type (which can have
9469 single spaces embedded in the name (e.g. long double), @code{digs} is
9470 the number of digits for the floating-point type, @code{float_rep} is
9471 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
9472 AAMP), @code{size} is the size in bits, @code{alignment} is the
9473 alignment in bits. The name is followed by at least two blanks, fields
9474 are separated by at least one blank, and a LF character immediately
9475 follows the alignment field.
9477 Here is an example of a target parameterization file:
9479 @example
9480 Bits_BE                       0
9481 Bits_Per_Unit                 8
9482 Bits_Per_Word                64
9483 Bytes_BE                      0
9484 Char_Size                     8
9485 Double_Float_Alignment        0
9486 Double_Scalar_Alignment       0
9487 Double_Size                  64
9488 Float_Size                   32
9489 Float_Words_BE                0
9490 Int_Size                     64
9491 Long_Double_Size            128
9492 Long_Long_Size               64
9493 Long_Size                    64
9494 Maximum_Alignment            16
9495 Max_Unaligned_Field          64
9496 Pointer_Size                 64
9497 Short_Size                   16
9498 Strict_Alignment              0
9499 System_Allocator_Alignment   16
9500 Wchar_T_Size                 32
9501 Words_BE                      0
9503 float         15  I  64  64
9504 double        15  I  64  64
9505 long double   18  I  80 128
9506 TF            33  I 128 128
9507 @end example
9508 @end table
9510 @geindex -gnateu (gcc)
9513 @table @asis
9515 @item @code{-gnateu}
9517 Ignore unrecognized validity, warning, and style switches that
9518 appear after this switch is given. This may be useful when
9519 compiling sources developed on a later version of the compiler
9520 with an earlier version. Of course the earlier version must
9521 support this switch.
9522 @end table
9524 @geindex -gnateV (gcc)
9527 @table @asis
9529 @item @code{-gnateV}
9531 Check that all actual parameters of a subprogram call are valid according to
9532 the rules of validity checking (@ref{f6,,Validity Checking}).
9533 @end table
9535 @geindex -gnateY (gcc)
9538 @table @asis
9540 @item @code{-gnateY}
9542 Ignore all STYLE_CHECKS pragmas. Full legality checks
9543 are still carried out, but the pragmas have no effect
9544 on what style checks are active. This allows all style
9545 checking options to be controlled from the command line.
9546 @end table
9548 @geindex -gnatE (gcc)
9551 @table @asis
9553 @item @code{-gnatE}
9555 Full dynamic elaboration checks.
9556 @end table
9558 @geindex -gnatf (gcc)
9561 @table @asis
9563 @item @code{-gnatf}
9565 Full errors. Multiple errors per line, all undefined references, do not
9566 attempt to suppress cascaded errors.
9567 @end table
9569 @geindex -gnatF (gcc)
9572 @table @asis
9574 @item @code{-gnatF}
9576 Externals names are folded to all uppercase.
9577 @end table
9579 @geindex -gnatg (gcc)
9582 @table @asis
9584 @item @code{-gnatg}
9586 Internal GNAT implementation mode. This should not be used for
9587 applications programs, it is intended only for use by the compiler
9588 and its run-time library. For documentation, see the GNAT sources.
9589 Note that @code{-gnatg} implies
9590 @code{-gnatw.ge} and
9591 @code{-gnatyg}
9592 so that all standard warnings and all standard style options are turned on.
9593 All warnings and style messages are treated as errors.
9594 @end table
9596 @geindex -gnatG[nn] (gcc)
9599 @table @asis
9601 @item @code{-gnatG=nn}
9603 List generated expanded code in source form.
9604 @end table
9606 @geindex -gnath (gcc)
9609 @table @asis
9611 @item @code{-gnath}
9613 Output usage information. The output is written to @code{stdout}.
9614 @end table
9616 @geindex -gnati (gcc)
9619 @table @asis
9621 @item @code{-gnati@emph{c}}
9623 Identifier character set (@code{c} = 1/2/3/4/8/9/p/f/n/w).
9624 For details of the possible selections for @code{c},
9625 see @ref{48,,Character Set Control}.
9626 @end table
9628 @geindex -gnatI (gcc)
9631 @table @asis
9633 @item @code{-gnatI}
9635 Ignore representation clauses. When this switch is used,
9636 representation clauses are treated as comments. This is useful
9637 when initially porting code where you want to ignore rep clause
9638 problems, and also for compiling foreign code (particularly
9639 for use with ASIS). The representation clauses that are ignored
9640 are: enumeration_representation_clause, record_representation_clause,
9641 and attribute_definition_clause for the following attributes:
9642 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9643 Object_Size, Scalar_Storage_Order, Size, Small, Stream_Size,
9644 and Value_Size. Pragma Default_Scalar_Storage_Order is also ignored.
9645 Note that this option should be used only for compiling -- the
9646 code is likely to malfunction at run time.
9648 Note that when @code{-gnatct} is used to generate trees for input
9649 into ASIS tools, these representation clauses are removed
9650 from the tree and ignored. This means that the tool will not see them.
9651 @end table
9653 @geindex -gnatjnn (gcc)
9656 @table @asis
9658 @item @code{-gnatj@emph{nn}}
9660 Reformat error messages to fit on @code{nn} character lines
9661 @end table
9663 @geindex -gnatk (gcc)
9666 @table @asis
9668 @item @code{-gnatk=@emph{n}}
9670 Limit file names to @code{n} (1-999) characters (@code{k} = krunch).
9671 @end table
9673 @geindex -gnatl (gcc)
9676 @table @asis
9678 @item @code{-gnatl}
9680 Output full source listing with embedded error messages.
9681 @end table
9683 @geindex -gnatL (gcc)
9686 @table @asis
9688 @item @code{-gnatL}
9690 Used in conjunction with -gnatG or -gnatD to intersperse original
9691 source lines (as comment lines with line numbers) in the expanded
9692 source output.
9693 @end table
9695 @geindex -gnatm (gcc)
9698 @table @asis
9700 @item @code{-gnatm=@emph{n}}
9702 Limit number of detected error or warning messages to @code{n}
9703 where @code{n} is in the range 1..999999. The default setting if
9704 no switch is given is 9999. If the number of warnings reaches this
9705 limit, then a message is output and further warnings are suppressed,
9706 but the compilation is continued. If the number of error messages
9707 reaches this limit, then a message is output and the compilation
9708 is abandoned. The equal sign here is optional. A value of zero
9709 means that no limit applies.
9710 @end table
9712 @geindex -gnatn (gcc)
9715 @table @asis
9717 @item @code{-gnatn[12]}
9719 Activate inlining across modules for subprograms for which pragma @code{Inline}
9720 is specified. This inlining is performed by the GCC back-end. An optional
9721 digit sets the inlining level: 1 for moderate inlining across modules
9722 or 2 for full inlining across modules. If no inlining level is specified,
9723 the compiler will pick it based on the optimization level.
9724 @end table
9726 @geindex -gnatN (gcc)
9729 @table @asis
9731 @item @code{-gnatN}
9733 Activate front end inlining for subprograms for which
9734 pragma @code{Inline} is specified. This inlining is performed
9735 by the front end and will be visible in the
9736 @code{-gnatG} output.
9738 When using a gcc-based back end (in practice this means using any version
9739 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
9740 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
9741 Historically front end inlining was more extensive than the gcc back end
9742 inlining, but that is no longer the case.
9743 @end table
9745 @geindex -gnato0 (gcc)
9748 @table @asis
9750 @item @code{-gnato0}
9752 Suppresses overflow checking. This causes the behavior of the compiler to
9753 match the default for older versions where overflow checking was suppressed
9754 by default. This is equivalent to having
9755 @code{pragma Suppress (Overflow_Check)} in a configuration pragma file.
9756 @end table
9758 @geindex -gnato?? (gcc)
9761 @table @asis
9763 @item @code{-gnato??}
9765 Set default mode for handling generation of code to avoid intermediate
9766 arithmetic overflow. Here @code{??} is two digits, a
9767 single digit, or nothing. Each digit is one of the digits @code{1}
9768 through @code{3}:
9771 @multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
9772 @item
9774 Digit
9776 @tab
9778 Interpretation
9780 @item
9782 @emph{1}
9784 @tab
9786 All intermediate overflows checked against base type (@code{STRICT})
9788 @item
9790 @emph{2}
9792 @tab
9794 Minimize intermediate overflows (@code{MINIMIZED})
9796 @item
9798 @emph{3}
9800 @tab
9802 Eliminate intermediate overflows (@code{ELIMINATED})
9804 @end multitable
9807 If only one digit appears, then it applies to all
9808 cases; if two digits are given, then the first applies outside
9809 assertions, pre/postconditions, and type invariants, and the second
9810 applies within assertions, pre/postconditions, and type invariants.
9812 If no digits follow the @code{-gnato}, then it is equivalent to
9813 @code{-gnato11},
9814 causing all intermediate overflows to be handled in strict
9815 mode.
9817 This switch also causes arithmetic overflow checking to be performed
9818 (as though @code{pragma Unsuppress (Overflow_Check)} had been specified).
9820 The default if no option @code{-gnato} is given is that overflow handling
9821 is in @code{STRICT} mode (computations done using the base type), and that
9822 overflow checking is enabled.
9824 Note that division by zero is a separate check that is not
9825 controlled by this switch (divide-by-zero checking is on by default).
9827 See also @ref{f8,,Specifying the Desired Mode}.
9828 @end table
9830 @geindex -gnatp (gcc)
9833 @table @asis
9835 @item @code{-gnatp}
9837 Suppress all checks. See @ref{f9,,Run-Time Checks} for details. This switch
9838 has no effect if cancelled by a subsequent @code{-gnat-p} switch.
9839 @end table
9841 @geindex -gnat-p (gcc)
9844 @table @asis
9846 @item @code{-gnat-p}
9848 Cancel effect of previous @code{-gnatp} switch.
9849 @end table
9851 @geindex -gnatP (gcc)
9854 @table @asis
9856 @item @code{-gnatP}
9858 Enable polling. This is required on some systems (notably Windows NT) to
9859 obtain asynchronous abort and asynchronous transfer of control capability.
9860 See @code{Pragma_Polling} in the @cite{GNAT_Reference_Manual} for full
9861 details.
9862 @end table
9864 @geindex -gnatq (gcc)
9867 @table @asis
9869 @item @code{-gnatq}
9871 Don't quit. Try semantics, even if parse errors.
9872 @end table
9874 @geindex -gnatQ (gcc)
9877 @table @asis
9879 @item @code{-gnatQ}
9881 Don't quit. Generate @code{ALI} and tree files even if illegalities.
9882 Note that code generation is still suppressed in the presence of any
9883 errors, so even with @code{-gnatQ} no object file is generated.
9884 @end table
9886 @geindex -gnatr (gcc)
9889 @table @asis
9891 @item @code{-gnatr}
9893 Treat pragma Restrictions as Restriction_Warnings.
9894 @end table
9896 @geindex -gnatR (gcc)
9899 @table @asis
9901 @item @code{-gnatR[0/1/2/3][e][m][s]}
9903 Output representation information for declared types, objects and
9904 subprograms. Note that this switch is not allowed if a previous
9905 @code{-gnatD} switch has been given, since these two switches
9906 are not compatible.
9907 @end table
9909 @geindex -gnats (gcc)
9912 @table @asis
9914 @item @code{-gnats}
9916 Syntax check only.
9917 @end table
9919 @geindex -gnatS (gcc)
9922 @table @asis
9924 @item @code{-gnatS}
9926 Print package Standard.
9927 @end table
9929 @geindex -gnatt (gcc)
9932 @table @asis
9934 @item @code{-gnatt}
9936 Generate tree output file.
9937 @end table
9939 @geindex -gnatT (gcc)
9942 @table @asis
9944 @item @code{-gnatT@emph{nnn}}
9946 All compiler tables start at @code{nnn} times usual starting size.
9947 @end table
9949 @geindex -gnatu (gcc)
9952 @table @asis
9954 @item @code{-gnatu}
9956 List units for this compilation.
9957 @end table
9959 @geindex -gnatU (gcc)
9962 @table @asis
9964 @item @code{-gnatU}
9966 Tag all error messages with the unique string 'error:'
9967 @end table
9969 @geindex -gnatv (gcc)
9972 @table @asis
9974 @item @code{-gnatv}
9976 Verbose mode. Full error output with source lines to @code{stdout}.
9977 @end table
9979 @geindex -gnatV (gcc)
9982 @table @asis
9984 @item @code{-gnatV}
9986 Control level of validity checking (@ref{f6,,Validity Checking}).
9987 @end table
9989 @geindex -gnatw (gcc)
9992 @table @asis
9994 @item @code{-gnatw@emph{xxx}}
9996 Warning mode where
9997 @code{xxx} is a string of option letters that denotes
9998 the exact warnings that
9999 are enabled or disabled (@ref{fa,,Warning Message Control}).
10000 @end table
10002 @geindex -gnatW (gcc)
10005 @table @asis
10007 @item @code{-gnatW@emph{e}}
10009 Wide character encoding method
10010 (@code{e}=n/h/u/s/e/8).
10011 @end table
10013 @geindex -gnatx (gcc)
10016 @table @asis
10018 @item @code{-gnatx}
10020 Suppress generation of cross-reference information.
10021 @end table
10023 @geindex -gnatX (gcc)
10026 @table @asis
10028 @item @code{-gnatX}
10030 Enable GNAT implementation extensions and latest Ada version.
10031 @end table
10033 @geindex -gnaty (gcc)
10036 @table @asis
10038 @item @code{-gnaty}
10040 Enable built-in style checks (@ref{fb,,Style Checking}).
10041 @end table
10043 @geindex -gnatz (gcc)
10046 @table @asis
10048 @item @code{-gnatz@emph{m}}
10050 Distribution stub generation and compilation
10051 (@code{m}=r/c for receiver/caller stubs).
10052 @end table
10054 @geindex -I (gcc)
10057 @table @asis
10059 @item @code{-I@emph{dir}}
10061 @geindex RTL
10063 Direct GNAT to search the @code{dir} directory for source files needed by
10064 the current compilation
10065 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
10066 @end table
10068 @geindex -I- (gcc)
10071 @table @asis
10073 @item @code{-I-}
10075 @geindex RTL
10077 Except for the source file named in the command line, do not look for source
10078 files in the directory containing the source file named in the command line
10079 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
10080 @end table
10082 @geindex -o (gcc)
10085 @table @asis
10087 @item @code{-o @emph{file}}
10089 This switch is used in @code{gcc} to redirect the generated object file
10090 and its associated ALI file. Beware of this switch with GNAT, because it may
10091 cause the object file and ALI file to have different names which in turn
10092 may confuse the binder and the linker.
10093 @end table
10095 @geindex -nostdinc (gcc)
10098 @table @asis
10100 @item @code{-nostdinc}
10102 Inhibit the search of the default location for the GNAT Run Time
10103 Library (RTL) source files.
10104 @end table
10106 @geindex -nostdlib (gcc)
10109 @table @asis
10111 @item @code{-nostdlib}
10113 Inhibit the search of the default location for the GNAT Run Time
10114 Library (RTL) ALI files.
10115 @end table
10117 @geindex -O (gcc)
10120 @table @asis
10122 @item @code{-O[@emph{n}]}
10124 @code{n} controls the optimization level:
10127 @multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
10128 @item
10130 @emph{n}
10132 @tab
10134 Effect
10136 @item
10138 @emph{0}
10140 @tab
10142 No optimization, the default setting if no @code{-O} appears
10144 @item
10146 @emph{1}
10148 @tab
10150 Normal optimization, the default if you specify @code{-O} without an
10151 operand. A good compromise between code quality and compilation
10152 time.
10154 @item
10156 @emph{2}
10158 @tab
10160 Extensive optimization, may improve execution time, possibly at
10161 the cost of substantially increased compilation time.
10163 @item
10165 @emph{3}
10167 @tab
10169 Same as @code{-O2}, and also includes inline expansion for small
10170 subprograms in the same unit.
10172 @item
10174 @emph{s}
10176 @tab
10178 Optimize space usage
10180 @end multitable
10183 See also @ref{fc,,Optimization Levels}.
10184 @end table
10186 @geindex -pass-exit-codes (gcc)
10189 @table @asis
10191 @item @code{-pass-exit-codes}
10193 Catch exit codes from the compiler and use the most meaningful as
10194 exit status.
10195 @end table
10197 @geindex --RTS (gcc)
10200 @table @asis
10202 @item @code{--RTS=@emph{rts-path}}
10204 Specifies the default location of the runtime library. Same meaning as the
10205 equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
10206 @end table
10208 @geindex -S (gcc)
10211 @table @asis
10213 @item @code{-S}
10215 Used in place of @code{-c} to
10216 cause the assembler source file to be
10217 generated, using @code{.s} as the extension,
10218 instead of the object file.
10219 This may be useful if you need to examine the generated assembly code.
10220 @end table
10222 @geindex -fverbose-asm (gcc)
10225 @table @asis
10227 @item @code{-fverbose-asm}
10229 Used in conjunction with @code{-S}
10230 to cause the generated assembly code file to be annotated with variable
10231 names, making it significantly easier to follow.
10232 @end table
10234 @geindex -v (gcc)
10237 @table @asis
10239 @item @code{-v}
10241 Show commands generated by the @code{gcc} driver. Normally used only for
10242 debugging purposes or if you need to be sure what version of the
10243 compiler you are executing.
10244 @end table
10246 @geindex -V (gcc)
10249 @table @asis
10251 @item @code{-V @emph{ver}}
10253 Execute @code{ver} version of the compiler. This is the @code{gcc}
10254 version, not the GNAT version.
10255 @end table
10257 @geindex -w (gcc)
10260 @table @asis
10262 @item @code{-w}
10264 Turn off warnings generated by the back end of the compiler. Use of
10265 this switch also causes the default for front end warnings to be set
10266 to suppress (as though @code{-gnatws} had appeared at the start of
10267 the options).
10268 @end table
10270 @geindex Combining GNAT switches
10272 You may combine a sequence of GNAT switches into a single switch. For
10273 example, the combined switch
10275 @quotation
10277 @example
10278 -gnatofi3
10279 @end example
10280 @end quotation
10282 is equivalent to specifying the following sequence of switches:
10284 @quotation
10286 @example
10287 -gnato -gnatf -gnati3
10288 @end example
10289 @end quotation
10291 The following restrictions apply to the combination of switches
10292 in this manner:
10295 @itemize *
10297 @item 
10298 The switch @code{-gnatc} if combined with other switches must come
10299 first in the string.
10301 @item 
10302 The switch @code{-gnats} if combined with other switches must come
10303 first in the string.
10305 @item 
10306 The switches
10307 @code{-gnatzc} and @code{-gnatzr} may not be combined with any other
10308 switches, and only one of them may appear in the command line.
10310 @item 
10311 The switch @code{-gnat-p} may not be combined with any other switch.
10313 @item 
10314 Once a 'y' appears in the string (that is a use of the @code{-gnaty}
10315 switch), then all further characters in the switch are interpreted
10316 as style modifiers (see description of @code{-gnaty}).
10318 @item 
10319 Once a 'd' appears in the string (that is a use of the @code{-gnatd}
10320 switch), then all further characters in the switch are interpreted
10321 as debug flags (see description of @code{-gnatd}).
10323 @item 
10324 Once a 'w' appears in the string (that is a use of the @code{-gnatw}
10325 switch), then all further characters in the switch are interpreted
10326 as warning mode modifiers (see description of @code{-gnatw}).
10328 @item 
10329 Once a 'V' appears in the string (that is a use of the @code{-gnatV}
10330 switch), then all further characters in the switch are interpreted
10331 as validity checking options (@ref{f6,,Validity Checking}).
10333 @item 
10334 Option 'em', 'ec', 'ep', 'l=' and 'R' must be the last options in
10335 a combined list of options.
10336 @end itemize
10338 @node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10339 @anchor{gnat_ugn/building_executable_programs_with_gnat id14}@anchor{fd}@anchor{gnat_ugn/building_executable_programs_with_gnat output-and-error-message-control}@anchor{fe}
10340 @subsection Output and Error Message Control
10343 @geindex stderr
10345 The standard default format for error messages is called 'brief format'.
10346 Brief format messages are written to @code{stderr} (the standard error
10347 file) and have the following form:
10349 @example
10350 e.adb:3:04: Incorrect spelling of keyword "function"
10351 e.adb:4:20: ";" should be "is"
10352 @end example
10354 The first integer after the file name is the line number in the file,
10355 and the second integer is the column number within the line.
10356 @code{GPS} can parse the error messages
10357 and point to the referenced character.
10358 The following switches provide control over the error message
10359 format:
10361 @geindex -gnatv (gcc)
10364 @table @asis
10366 @item @code{-gnatv}
10368 The @code{v} stands for verbose.
10369 The effect of this setting is to write long-format error
10370 messages to @code{stdout} (the standard output file.
10371 The same program compiled with the
10372 @code{-gnatv} switch would generate:
10374 @example
10375 3. funcion X (Q : Integer)
10376    |
10377 >>> Incorrect spelling of keyword "function"
10378 4. return Integer;
10379                  |
10380 >>> ";" should be "is"
10381 @end example
10383 The vertical bar indicates the location of the error, and the @code{>>>}
10384 prefix can be used to search for error messages. When this switch is
10385 used the only source lines output are those with errors.
10386 @end table
10388 @geindex -gnatl (gcc)
10391 @table @asis
10393 @item @code{-gnatl}
10395 The @code{l} stands for list.
10396 This switch causes a full listing of
10397 the file to be generated. In the case where a body is
10398 compiled, the corresponding spec is also listed, along
10399 with any subunits. Typical output from compiling a package
10400 body @code{p.adb} might look like:
10402 @example
10403 Compiling: p.adb
10405      1. package body p is
10406      2.    procedure a;
10407      3.    procedure a is separate;
10408      4. begin
10409      5.    null
10410                |
10411         >>> missing ";"
10413      6. end;
10415 Compiling: p.ads
10417      1. package p is
10418      2.    pragma Elaborate_Body
10419                                 |
10420         >>> missing ";"
10422      3. end p;
10424 Compiling: p-a.adb
10426      1. separate p
10427                 |
10428         >>> missing "("
10430      2. procedure a is
10431      3. begin
10432      4.    null
10433                |
10434         >>> missing ";"
10436      5. end;
10437 @end example
10439 When you specify the @code{-gnatv} or @code{-gnatl} switches and
10440 standard output is redirected, a brief summary is written to
10441 @code{stderr} (standard error) giving the number of error messages and
10442 warning messages generated.
10443 @end table
10445 @geindex -gnatl=fname (gcc)
10448 @table @asis
10450 @item @code{-gnatl=@emph{fname}}
10452 This has the same effect as @code{-gnatl} except that the output is
10453 written to a file instead of to standard output. If the given name
10454 @code{fname} does not start with a period, then it is the full name
10455 of the file to be written. If @code{fname} is an extension, it is
10456 appended to the name of the file being compiled. For example, if
10457 file @code{xyz.adb} is compiled with @code{-gnatl=.lst},
10458 then the output is written to file xyz.adb.lst.
10459 @end table
10461 @geindex -gnatU (gcc)
10464 @table @asis
10466 @item @code{-gnatU}
10468 This switch forces all error messages to be preceded by the unique
10469 string 'error:'. This means that error messages take a few more
10470 characters in space, but allows easy searching for and identification
10471 of error messages.
10472 @end table
10474 @geindex -gnatb (gcc)
10477 @table @asis
10479 @item @code{-gnatb}
10481 The @code{b} stands for brief.
10482 This switch causes GNAT to generate the
10483 brief format error messages to @code{stderr} (the standard error
10484 file) as well as the verbose
10485 format message or full listing (which as usual is written to
10486 @code{stdout} (the standard output file).
10487 @end table
10489 @geindex -gnatm (gcc)
10492 @table @asis
10494 @item @code{-gnatm=@emph{n}}
10496 The @code{m} stands for maximum.
10497 @code{n} is a decimal integer in the
10498 range of 1 to 999999 and limits the number of error or warning
10499 messages to be generated. For example, using
10500 @code{-gnatm2} might yield
10502 @example
10503 e.adb:3:04: Incorrect spelling of keyword "function"
10504 e.adb:5:35: missing ".."
10505 fatal error: maximum number of errors detected
10506 compilation abandoned
10507 @end example
10509 The default setting if
10510 no switch is given is 9999. If the number of warnings reaches this
10511 limit, then a message is output and further warnings are suppressed,
10512 but the compilation is continued. If the number of error messages
10513 reaches this limit, then a message is output and the compilation
10514 is abandoned. A value of zero means that no limit applies.
10516 Note that the equal sign is optional, so the switches
10517 @code{-gnatm2} and @code{-gnatm=2} are equivalent.
10518 @end table
10520 @geindex -gnatf (gcc)
10523 @table @asis
10525 @item @code{-gnatf}
10527 @geindex Error messages
10528 @geindex suppressing
10530 The @code{f} stands for full.
10531 Normally, the compiler suppresses error messages that are likely to be
10532 redundant. This switch causes all error
10533 messages to be generated. In particular, in the case of
10534 references to undefined variables. If a given variable is referenced
10535 several times, the normal format of messages is
10537 @example
10538 e.adb:7:07: "V" is undefined (more references follow)
10539 @end example
10541 where the parenthetical comment warns that there are additional
10542 references to the variable @code{V}. Compiling the same program with the
10543 @code{-gnatf} switch yields
10545 @example
10546 e.adb:7:07: "V" is undefined
10547 e.adb:8:07: "V" is undefined
10548 e.adb:8:12: "V" is undefined
10549 e.adb:8:16: "V" is undefined
10550 e.adb:9:07: "V" is undefined
10551 e.adb:9:12: "V" is undefined
10552 @end example
10554 The @code{-gnatf} switch also generates additional information for
10555 some error messages.  Some examples are:
10558 @itemize *
10560 @item 
10561 Details on possibly non-portable unchecked conversion
10563 @item 
10564 List possible interpretations for ambiguous calls
10566 @item 
10567 Additional details on incorrect parameters
10568 @end itemize
10569 @end table
10571 @geindex -gnatjnn (gcc)
10574 @table @asis
10576 @item @code{-gnatjnn}
10578 In normal operation mode (or if @code{-gnatj0} is used), then error messages
10579 with continuation lines are treated as though the continuation lines were
10580 separate messages (and so a warning with two continuation lines counts as
10581 three warnings, and is listed as three separate messages).
10583 If the @code{-gnatjnn} switch is used with a positive value for nn, then
10584 messages are output in a different manner. A message and all its continuation
10585 lines are treated as a unit, and count as only one warning or message in the
10586 statistics totals. Furthermore, the message is reformatted so that no line
10587 is longer than nn characters.
10588 @end table
10590 @geindex -gnatq (gcc)
10593 @table @asis
10595 @item @code{-gnatq}
10597 The @code{q} stands for quit (really 'don't quit').
10598 In normal operation mode, the compiler first parses the program and
10599 determines if there are any syntax errors. If there are, appropriate
10600 error messages are generated and compilation is immediately terminated.
10601 This switch tells
10602 GNAT to continue with semantic analysis even if syntax errors have been
10603 found. This may enable the detection of more errors in a single run. On
10604 the other hand, the semantic analyzer is more likely to encounter some
10605 internal fatal error when given a syntactically invalid tree.
10606 @end table
10608 @geindex -gnatQ (gcc)
10611 @table @asis
10613 @item @code{-gnatQ}
10615 In normal operation mode, the @code{ALI} file is not generated if any
10616 illegalities are detected in the program. The use of @code{-gnatQ} forces
10617 generation of the @code{ALI} file. This file is marked as being in
10618 error, so it cannot be used for binding purposes, but it does contain
10619 reasonably complete cross-reference information, and thus may be useful
10620 for use by tools (e.g., semantic browsing tools or integrated development
10621 environments) that are driven from the @code{ALI} file. This switch
10622 implies @code{-gnatq}, since the semantic phase must be run to get a
10623 meaningful ALI file.
10625 In addition, if @code{-gnatt} is also specified, then the tree file is
10626 generated even if there are illegalities. It may be useful in this case
10627 to also specify @code{-gnatq} to ensure that full semantic processing
10628 occurs. The resulting tree file can be processed by ASIS, for the purpose
10629 of providing partial information about illegal units, but if the error
10630 causes the tree to be badly malformed, then ASIS may crash during the
10631 analysis.
10633 When @code{-gnatQ} is used and the generated @code{ALI} file is marked as
10634 being in error, @code{gnatmake} will attempt to recompile the source when it
10635 finds such an @code{ALI} file, including with switch @code{-gnatc}.
10637 Note that @code{-gnatQ} has no effect if @code{-gnats} is specified,
10638 since ALI files are never generated if @code{-gnats} is set.
10639 @end table
10641 @node Warning Message Control,Debugging and Assertion Control,Output and Error Message Control,Compiler Switches
10642 @anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{fa}@anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{ff}
10643 @subsection Warning Message Control
10646 @geindex Warning messages
10648 In addition to error messages, which correspond to illegalities as defined
10649 in the Ada Reference Manual, the compiler detects two kinds of warning
10650 situations.
10652 First, the compiler considers some constructs suspicious and generates a
10653 warning message to alert you to a possible error. Second, if the
10654 compiler detects a situation that is sure to raise an exception at
10655 run time, it generates a warning message. The following shows an example
10656 of warning messages:
10658 @example
10659 e.adb:4:24: warning: creation of object may raise Storage_Error
10660 e.adb:10:17: warning: static value out of range
10661 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10662 @end example
10664 GNAT considers a large number of situations as appropriate
10665 for the generation of warning messages. As always, warnings are not
10666 definite indications of errors. For example, if you do an out-of-range
10667 assignment with the deliberate intention of raising a
10668 @code{Constraint_Error} exception, then the warning that may be
10669 issued does not indicate an error. Some of the situations for which GNAT
10670 issues warnings (at least some of the time) are given in the following
10671 list. This list is not complete, and new warnings are often added to
10672 subsequent versions of GNAT. The list is intended to give a general idea
10673 of the kinds of warnings that are generated.
10676 @itemize *
10678 @item 
10679 Possible infinitely recursive calls
10681 @item 
10682 Out-of-range values being assigned
10684 @item 
10685 Possible order of elaboration problems
10687 @item 
10688 Size not a multiple of alignment for a record type
10690 @item 
10691 Assertions (pragma Assert) that are sure to fail
10693 @item 
10694 Unreachable code
10696 @item 
10697 Address clauses with possibly unaligned values, or where an attempt is
10698 made to overlay a smaller variable with a larger one.
10700 @item 
10701 Fixed-point type declarations with a null range
10703 @item 
10704 Direct_IO or Sequential_IO instantiated with a type that has access values
10706 @item 
10707 Variables that are never assigned a value
10709 @item 
10710 Variables that are referenced before being initialized
10712 @item 
10713 Task entries with no corresponding @code{accept} statement
10715 @item 
10716 Duplicate accepts for the same task entry in a @code{select}
10718 @item 
10719 Objects that take too much storage
10721 @item 
10722 Unchecked conversion between types of differing sizes
10724 @item 
10725 Missing @code{return} statement along some execution path in a function
10727 @item 
10728 Incorrect (unrecognized) pragmas
10730 @item 
10731 Incorrect external names
10733 @item 
10734 Allocation from empty storage pool
10736 @item 
10737 Potentially blocking operation in protected type
10739 @item 
10740 Suspicious parenthesization of expressions
10742 @item 
10743 Mismatching bounds in an aggregate
10745 @item 
10746 Attempt to return local value by reference
10748 @item 
10749 Premature instantiation of a generic body
10751 @item 
10752 Attempt to pack aliased components
10754 @item 
10755 Out of bounds array subscripts
10757 @item 
10758 Wrong length on string assignment
10760 @item 
10761 Violations of style rules if style checking is enabled
10763 @item 
10764 Unused @emph{with} clauses
10766 @item 
10767 @code{Bit_Order} usage that does not have any effect
10769 @item 
10770 @code{Standard.Duration} used to resolve universal fixed expression
10772 @item 
10773 Dereference of possibly null value
10775 @item 
10776 Declaration that is likely to cause storage error
10778 @item 
10779 Internal GNAT unit @emph{with}ed by application unit
10781 @item 
10782 Values known to be out of range at compile time
10784 @item 
10785 Unreferenced or unmodified variables. Note that a special
10786 exemption applies to variables which contain any of the substrings
10787 @code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
10788 are considered likely to be intentionally used in a situation where
10789 otherwise a warning would be given, so warnings of this kind are
10790 always suppressed for such variables.
10792 @item 
10793 Address overlays that could clobber memory
10795 @item 
10796 Unexpected initialization when address clause present
10798 @item 
10799 Bad alignment for address clause
10801 @item 
10802 Useless type conversions
10804 @item 
10805 Redundant assignment statements and other redundant constructs
10807 @item 
10808 Useless exception handlers
10810 @item 
10811 Accidental hiding of name by child unit
10813 @item 
10814 Access before elaboration detected at compile time
10816 @item 
10817 A range in a @code{for} loop that is known to be null or might be null
10818 @end itemize
10820 The following section lists compiler switches that are available
10821 to control the handling of warning messages. It is also possible
10822 to exercise much finer control over what warnings are issued and
10823 suppressed using the GNAT pragma Warnings (see the description
10824 of the pragma in the @cite{GNAT_Reference_manual}).
10826 @geindex -gnatwa (gcc)
10829 @table @asis
10831 @item @code{-gnatwa}
10833 @emph{Activate most optional warnings.}
10835 This switch activates most optional warning messages.  See the remaining list
10836 in this section for details on optional warning messages that can be
10837 individually controlled.  The warnings that are not turned on by this
10838 switch are:
10841 @itemize *
10843 @item 
10844 @code{-gnatwd} (implicit dereferencing)
10846 @item 
10847 @code{-gnatw.d} (tag warnings with -gnatw switch)
10849 @item 
10850 @code{-gnatwh} (hiding)
10852 @item 
10853 @code{-gnatw.h} (holes in record layouts)
10855 @item 
10856 @code{-gnatw.j} (late primitives of tagged types)
10858 @item 
10859 @code{-gnatw.k} (redefinition of names in standard)
10861 @item 
10862 @code{-gnatwl} (elaboration warnings)
10864 @item 
10865 @code{-gnatw.l} (inherited aspects)
10867 @item 
10868 @code{-gnatw.n} (atomic synchronization)
10870 @item 
10871 @code{-gnatwo} (address clause overlay)
10873 @item 
10874 @code{-gnatw.o} (values set by out parameters ignored)
10876 @item 
10877 @code{-gnatw.q} (questionable layout of record types)
10879 @item 
10880 @code{-gnatw.s} (overridden size clause)
10882 @item 
10883 @code{-gnatwt} (tracking of deleted conditional code)
10885 @item 
10886 @code{-gnatw.u} (unordered enumeration)
10888 @item 
10889 @code{-gnatw.w} (use of Warnings Off)
10891 @item 
10892 @code{-gnatw.y} (reasons for package needing body)
10893 @end itemize
10895 All other optional warnings are turned on.
10896 @end table
10898 @geindex -gnatwA (gcc)
10901 @table @asis
10903 @item @code{-gnatwA}
10905 @emph{Suppress all optional errors.}
10907 This switch suppresses all optional warning messages, see remaining list
10908 in this section for details on optional warning messages that can be
10909 individually controlled. Note that unlike switch @code{-gnatws}, the
10910 use of switch @code{-gnatwA} does not suppress warnings that are
10911 normally given unconditionally and cannot be individually controlled
10912 (for example, the warning about a missing exit path in a function).
10913 Also, again unlike switch @code{-gnatws}, warnings suppressed by
10914 the use of switch @code{-gnatwA} can be individually turned back
10915 on. For example the use of switch @code{-gnatwA} followed by
10916 switch @code{-gnatwd} will suppress all optional warnings except
10917 the warnings for implicit dereferencing.
10918 @end table
10920 @geindex -gnatw.a (gcc)
10923 @table @asis
10925 @item @code{-gnatw.a}
10927 @emph{Activate warnings on failing assertions.}
10929 @geindex Assert failures
10931 This switch activates warnings for assertions where the compiler can tell at
10932 compile time that the assertion will fail. Note that this warning is given
10933 even if assertions are disabled. The default is that such warnings are
10934 generated.
10935 @end table
10937 @geindex -gnatw.A (gcc)
10940 @table @asis
10942 @item @code{-gnatw.A}
10944 @emph{Suppress warnings on failing assertions.}
10946 @geindex Assert failures
10948 This switch suppresses warnings for assertions where the compiler can tell at
10949 compile time that the assertion will fail.
10950 @end table
10952 @geindex -gnatwb (gcc)
10955 @table @asis
10957 @item @code{-gnatwb}
10959 @emph{Activate warnings on bad fixed values.}
10961 @geindex Bad fixed values
10963 @geindex Fixed-point Small value
10965 @geindex Small value
10967 This switch activates warnings for static fixed-point expressions whose
10968 value is not an exact multiple of Small. Such values are implementation
10969 dependent, since an implementation is free to choose either of the multiples
10970 that surround the value. GNAT always chooses the closer one, but this is not
10971 required behavior, and it is better to specify a value that is an exact
10972 multiple, ensuring predictable execution. The default is that such warnings
10973 are not generated.
10974 @end table
10976 @geindex -gnatwB (gcc)
10979 @table @asis
10981 @item @code{-gnatwB}
10983 @emph{Suppress warnings on bad fixed values.}
10985 This switch suppresses warnings for static fixed-point expressions whose
10986 value is not an exact multiple of Small.
10987 @end table
10989 @geindex -gnatw.b (gcc)
10992 @table @asis
10994 @item @code{-gnatw.b}
10996 @emph{Activate warnings on biased representation.}
10998 @geindex Biased representation
11000 This switch activates warnings when a size clause, value size clause, component
11001 clause, or component size clause forces the use of biased representation for an
11002 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
11003 to represent 10/11). The default is that such warnings are generated.
11004 @end table
11006 @geindex -gnatwB (gcc)
11009 @table @asis
11011 @item @code{-gnatw.B}
11013 @emph{Suppress warnings on biased representation.}
11015 This switch suppresses warnings for representation clauses that force the use
11016 of biased representation.
11017 @end table
11019 @geindex -gnatwc (gcc)
11022 @table @asis
11024 @item @code{-gnatwc}
11026 @emph{Activate warnings on conditionals.}
11028 @geindex Conditionals
11029 @geindex constant
11031 This switch activates warnings for conditional expressions used in
11032 tests that are known to be True or False at compile time. The default
11033 is that such warnings are not generated.
11034 Note that this warning does
11035 not get issued for the use of boolean variables or constants whose
11036 values are known at compile time, since this is a standard technique
11037 for conditional compilation in Ada, and this would generate too many
11038 false positive warnings.
11040 This warning option also activates a special test for comparisons using
11041 the operators '>=' and' <='.
11042 If the compiler can tell that only the equality condition is possible,
11043 then it will warn that the '>' or '<' part of the test
11044 is useless and that the operator could be replaced by '='.
11045 An example would be comparing a @code{Natural} variable <= 0.
11047 This warning option also generates warnings if
11048 one or both tests is optimized away in a membership test for integer
11049 values if the result can be determined at compile time. Range tests on
11050 enumeration types are not included, since it is common for such tests
11051 to include an end point.
11053 This warning can also be turned on using @code{-gnatwa}.
11054 @end table
11056 @geindex -gnatwC (gcc)
11059 @table @asis
11061 @item @code{-gnatwC}
11063 @emph{Suppress warnings on conditionals.}
11065 This switch suppresses warnings for conditional expressions used in
11066 tests that are known to be True or False at compile time.
11067 @end table
11069 @geindex -gnatw.c (gcc)
11072 @table @asis
11074 @item @code{-gnatw.c}
11076 @emph{Activate warnings on missing component clauses.}
11078 @geindex Component clause
11079 @geindex missing
11081 This switch activates warnings for record components where a record
11082 representation clause is present and has component clauses for the
11083 majority, but not all, of the components. A warning is given for each
11084 component for which no component clause is present.
11085 @end table
11087 @geindex -gnatwC (gcc)
11090 @table @asis
11092 @item @code{-gnatw.C}
11094 @emph{Suppress warnings on missing component clauses.}
11096 This switch suppresses warnings for record components that are
11097 missing a component clause in the situation described above.
11098 @end table
11100 @geindex -gnatwd (gcc)
11103 @table @asis
11105 @item @code{-gnatwd}
11107 @emph{Activate warnings on implicit dereferencing.}
11109 If this switch is set, then the use of a prefix of an access type
11110 in an indexed component, slice, or selected component without an
11111 explicit @code{.all} will generate a warning. With this warning
11112 enabled, access checks occur only at points where an explicit
11113 @code{.all} appears in the source code (assuming no warnings are
11114 generated as a result of this switch). The default is that such
11115 warnings are not generated.
11116 @end table
11118 @geindex -gnatwD (gcc)
11121 @table @asis
11123 @item @code{-gnatwD}
11125 @emph{Suppress warnings on implicit dereferencing.}
11127 @geindex Implicit dereferencing
11129 @geindex Dereferencing
11130 @geindex implicit
11132 This switch suppresses warnings for implicit dereferences in
11133 indexed components, slices, and selected components.
11134 @end table
11136 @geindex -gnatw.d (gcc)
11139 @table @asis
11141 @item @code{-gnatw.d}
11143 @emph{Activate tagging of warning and info messages.}
11145 If this switch is set, then warning messages are tagged, with one of the
11146 following strings:
11148 @quotation
11151 @itemize -
11153 @item 
11154 @emph{[-gnatw?]}
11155 Used to tag warnings controlled by the switch @code{-gnatwx} where x
11156 is a letter a-z.
11158 @item 
11159 @emph{[-gnatw.?]}
11160 Used to tag warnings controlled by the switch @code{-gnatw.x} where x
11161 is a letter a-z.
11163 @item 
11164 @emph{[-gnatel]}
11165 Used to tag elaboration information (info) messages generated when the
11166 static model of elaboration is used and the @code{-gnatel} switch is set.
11168 @item 
11169 @emph{[restriction warning]}
11170 Used to tag warning messages for restriction violations, activated by use
11171 of the pragma @code{Restriction_Warnings}.
11173 @item 
11174 @emph{[warning-as-error]}
11175 Used to tag warning messages that have been converted to error messages by
11176 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
11177 the string "error: " rather than "warning: ".
11179 @item 
11180 @emph{[enabled by default]}
11181 Used to tag all other warnings that are always given by default, unless
11182 warnings are completely suppressed using pragma @emph{Warnings(Off)} or
11183 the switch @code{-gnatws}.
11184 @end itemize
11185 @end quotation
11186 @end table
11188 @geindex -gnatw.d (gcc)
11191 @table @asis
11193 @item @code{-gnatw.D}
11195 @emph{Deactivate tagging of warning and info messages messages.}
11197 If this switch is set, then warning messages return to the default
11198 mode in which warnings and info messages are not tagged as described above for
11199 @code{-gnatw.d}.
11200 @end table
11202 @geindex -gnatwe (gcc)
11204 @geindex Warnings
11205 @geindex treat as error
11208 @table @asis
11210 @item @code{-gnatwe}
11212 @emph{Treat warnings and style checks as errors.}
11214 This switch causes warning messages and style check messages to be
11215 treated as errors.
11216 The warning string still appears, but the warning messages are counted
11217 as errors, and prevent the generation of an object file. Note that this
11218 is the only -gnatw switch that affects the handling of style check messages.
11219 Note also that this switch has no effect on info (information) messages, which
11220 are not treated as errors if this switch is present.
11221 @end table
11223 @geindex -gnatw.e (gcc)
11226 @table @asis
11228 @item @code{-gnatw.e}
11230 @emph{Activate every optional warning.}
11232 @geindex Warnings
11233 @geindex activate every optional warning
11235 This switch activates all optional warnings, including those which
11236 are not activated by @code{-gnatwa}. The use of this switch is not
11237 recommended for normal use. If you turn this switch on, it is almost
11238 certain that you will get large numbers of useless warnings. The
11239 warnings that are excluded from @code{-gnatwa} are typically highly
11240 specialized warnings that are suitable for use only in code that has
11241 been specifically designed according to specialized coding rules.
11242 @end table
11244 @geindex -gnatwE (gcc)
11246 @geindex Warnings
11247 @geindex treat as error
11250 @table @asis
11252 @item @code{-gnatwE}
11254 @emph{Treat all run-time exception warnings as errors.}
11256 This switch causes warning messages regarding errors that will be raised
11257 during run-time execution to be treated as errors.
11258 @end table
11260 @geindex -gnatwf (gcc)
11263 @table @asis
11265 @item @code{-gnatwf}
11267 @emph{Activate warnings on unreferenced formals.}
11269 @geindex Formals
11270 @geindex unreferenced
11272 This switch causes a warning to be generated if a formal parameter
11273 is not referenced in the body of the subprogram. This warning can
11274 also be turned on using @code{-gnatwu}. The
11275 default is that these warnings are not generated.
11276 @end table
11278 @geindex -gnatwF (gcc)
11281 @table @asis
11283 @item @code{-gnatwF}
11285 @emph{Suppress warnings on unreferenced formals.}
11287 This switch suppresses warnings for unreferenced formal
11288 parameters. Note that the
11289 combination @code{-gnatwu} followed by @code{-gnatwF} has the
11290 effect of warning on unreferenced entities other than subprogram
11291 formals.
11292 @end table
11294 @geindex -gnatwg (gcc)
11297 @table @asis
11299 @item @code{-gnatwg}
11301 @emph{Activate warnings on unrecognized pragmas.}
11303 @geindex Pragmas
11304 @geindex unrecognized
11306 This switch causes a warning to be generated if an unrecognized
11307 pragma is encountered. Apart from issuing this warning, the
11308 pragma is ignored and has no effect. The default
11309 is that such warnings are issued (satisfying the Ada Reference
11310 Manual requirement that such warnings appear).
11311 @end table
11313 @geindex -gnatwG (gcc)
11316 @table @asis
11318 @item @code{-gnatwG}
11320 @emph{Suppress warnings on unrecognized pragmas.}
11322 This switch suppresses warnings for unrecognized pragmas.
11323 @end table
11325 @geindex -gnatw.g (gcc)
11328 @table @asis
11330 @item @code{-gnatw.g}
11332 @emph{Warnings used for GNAT sources.}
11334 This switch sets the warning categories that are used by the standard
11335 GNAT style. Currently this is equivalent to
11336 @code{-gnatwAao.q.s.CI.V.X.Z}
11337 but more warnings may be added in the future without advanced notice.
11338 @end table
11340 @geindex -gnatwh (gcc)
11343 @table @asis
11345 @item @code{-gnatwh}
11347 @emph{Activate warnings on hiding.}
11349 @geindex Hiding of Declarations
11351 This switch activates warnings on hiding declarations that are considered
11352 potentially confusing. Not all cases of hiding cause warnings; for example an
11353 overriding declaration hides an implicit declaration, which is just normal
11354 code. The default is that warnings on hiding are not generated.
11355 @end table
11357 @geindex -gnatwH (gcc)
11360 @table @asis
11362 @item @code{-gnatwH}
11364 @emph{Suppress warnings on hiding.}
11366 This switch suppresses warnings on hiding declarations.
11367 @end table
11369 @geindex -gnatw.h (gcc)
11372 @table @asis
11374 @item @code{-gnatw.h}
11376 @emph{Activate warnings on holes/gaps in records.}
11378 @geindex Record Representation (gaps)
11380 This switch activates warnings on component clauses in record
11381 representation clauses that leave holes (gaps) in the record layout.
11382 If this warning option is active, then record representation clauses
11383 should specify a contiguous layout, adding unused fill fields if needed.
11384 @end table
11386 @geindex -gnatw.H (gcc)
11389 @table @asis
11391 @item @code{-gnatw.H}
11393 @emph{Suppress warnings on holes/gaps in records.}
11395 This switch suppresses warnings on component clauses in record
11396 representation clauses that leave holes (haps) in the record layout.
11397 @end table
11399 @geindex -gnatwi (gcc)
11402 @table @asis
11404 @item @code{-gnatwi}
11406 @emph{Activate warnings on implementation units.}
11408 This switch activates warnings for a @emph{with} of an internal GNAT
11409 implementation unit, defined as any unit from the @code{Ada},
11410 @code{Interfaces}, @code{GNAT},
11411 or @code{System}
11412 hierarchies that is not
11413 documented in either the Ada Reference Manual or the GNAT
11414 Programmer's Reference Manual. Such units are intended only
11415 for internal implementation purposes and should not be @emph{with}ed
11416 by user programs. The default is that such warnings are generated
11417 @end table
11419 @geindex -gnatwI (gcc)
11422 @table @asis
11424 @item @code{-gnatwI}
11426 @emph{Disable warnings on implementation units.}
11428 This switch disables warnings for a @emph{with} of an internal GNAT
11429 implementation unit.
11430 @end table
11432 @geindex -gnatw.i (gcc)
11435 @table @asis
11437 @item @code{-gnatw.i}
11439 @emph{Activate warnings on overlapping actuals.}
11441 This switch enables a warning on statically detectable overlapping actuals in
11442 a subprogram call, when one of the actuals is an in-out parameter, and the
11443 types of the actuals are not by-copy types. This warning is off by default.
11444 @end table
11446 @geindex -gnatw.I (gcc)
11449 @table @asis
11451 @item @code{-gnatw.I}
11453 @emph{Disable warnings on overlapping actuals.}
11455 This switch disables warnings on overlapping actuals in a call..
11456 @end table
11458 @geindex -gnatwj (gcc)
11461 @table @asis
11463 @item @code{-gnatwj}
11465 @emph{Activate warnings on obsolescent features (Annex J).}
11467 @geindex Features
11468 @geindex obsolescent
11470 @geindex Obsolescent features
11472 If this warning option is activated, then warnings are generated for
11473 calls to subprograms marked with @code{pragma Obsolescent} and
11474 for use of features in Annex J of the Ada Reference Manual. In the
11475 case of Annex J, not all features are flagged. In particular use
11476 of the renamed packages (like @code{Text_IO}) and use of package
11477 @code{ASCII} are not flagged, since these are very common and
11478 would generate many annoying positive warnings. The default is that
11479 such warnings are not generated.
11481 In addition to the above cases, warnings are also generated for
11482 GNAT features that have been provided in past versions but which
11483 have been superseded (typically by features in the new Ada standard).
11484 For example, @code{pragma Ravenscar} will be flagged since its
11485 function is replaced by @code{pragma Profile(Ravenscar)}, and
11486 @code{pragma Interface_Name} will be flagged since its function
11487 is replaced by @code{pragma Import}.
11489 Note that this warning option functions differently from the
11490 restriction @code{No_Obsolescent_Features} in two respects.
11491 First, the restriction applies only to annex J features.
11492 Second, the restriction does flag uses of package @code{ASCII}.
11493 @end table
11495 @geindex -gnatwJ (gcc)
11498 @table @asis
11500 @item @code{-gnatwJ}
11502 @emph{Suppress warnings on obsolescent features (Annex J).}
11504 This switch disables warnings on use of obsolescent features.
11505 @end table
11507 @geindex -gnatw.j (gcc)
11510 @table @asis
11512 @item @code{-gnatw.j}
11514 @emph{Activate warnings on late declarations of tagged type primitives.}
11516 This switch activates warnings on visible primitives added to a
11517 tagged type after deriving a private extension from it.
11518 @end table
11520 @geindex -gnatw.J (gcc)
11523 @table @asis
11525 @item @code{-gnatw.J}
11527 @emph{Suppress warnings on late declarations of tagged type primitives.}
11529 This switch suppresses warnings on visible primitives added to a
11530 tagged type after deriving a private extension from it.
11531 @end table
11533 @geindex -gnatwk (gcc)
11536 @table @asis
11538 @item @code{-gnatwk}
11540 @emph{Activate warnings on variables that could be constants.}
11542 This switch activates warnings for variables that are initialized but
11543 never modified, and then could be declared constants. The default is that
11544 such warnings are not given.
11545 @end table
11547 @geindex -gnatwK (gcc)
11550 @table @asis
11552 @item @code{-gnatwK}
11554 @emph{Suppress warnings on variables that could be constants.}
11556 This switch disables warnings on variables that could be declared constants.
11557 @end table
11559 @geindex -gnatw.k (gcc)
11562 @table @asis
11564 @item @code{-gnatw.k}
11566 @emph{Activate warnings on redefinition of names in standard.}
11568 This switch activates warnings for declarations that declare a name that
11569 is defined in package Standard. Such declarations can be confusing,
11570 especially since the names in package Standard continue to be directly
11571 visible, meaning that use visibiliy on such redeclared names does not
11572 work as expected. Names of discriminants and components in records are
11573 not included in this check.
11574 @end table
11576 @geindex -gnatwK (gcc)
11579 @table @asis
11581 @item @code{-gnatw.K}
11583 @emph{Suppress warnings on redefinition of names in standard.}
11585 This switch activates warnings for declarations that declare a name that
11586 is defined in package Standard.
11587 @end table
11589 @geindex -gnatwl (gcc)
11592 @table @asis
11594 @item @code{-gnatwl}
11596 @emph{Activate warnings for elaboration pragmas.}
11598 @geindex Elaboration
11599 @geindex warnings
11601 This switch activates warnings for possible elaboration problems,
11602 including suspicious use
11603 of @code{Elaborate} pragmas, when using the static elaboration model, and
11604 possible situations that may raise @code{Program_Error} when using the
11605 dynamic elaboration model.
11606 See the section in this guide on elaboration checking for further details.
11607 The default is that such warnings
11608 are not generated.
11609 @end table
11611 @geindex -gnatwL (gcc)
11614 @table @asis
11616 @item @code{-gnatwL}
11618 @emph{Suppress warnings for elaboration pragmas.}
11620 This switch suppresses warnings for possible elaboration problems.
11621 @end table
11623 @geindex -gnatw.l (gcc)
11626 @table @asis
11628 @item @code{-gnatw.l}
11630 @emph{List inherited aspects.}
11632 This switch causes the compiler to list inherited invariants,
11633 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
11634 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
11635 @end table
11637 @geindex -gnatw.L (gcc)
11640 @table @asis
11642 @item @code{-gnatw.L}
11644 @emph{Suppress listing of inherited aspects.}
11646 This switch suppresses listing of inherited aspects.
11647 @end table
11649 @geindex -gnatwm (gcc)
11652 @table @asis
11654 @item @code{-gnatwm}
11656 @emph{Activate warnings on modified but unreferenced variables.}
11658 This switch activates warnings for variables that are assigned (using
11659 an initialization value or with one or more assignment statements) but
11660 whose value is never read. The warning is suppressed for volatile
11661 variables and also for variables that are renamings of other variables
11662 or for which an address clause is given.
11663 The default is that these warnings are not given.
11664 @end table
11666 @geindex -gnatwM (gcc)
11669 @table @asis
11671 @item @code{-gnatwM}
11673 @emph{Disable warnings on modified but unreferenced variables.}
11675 This switch disables warnings for variables that are assigned or
11676 initialized, but never read.
11677 @end table
11679 @geindex -gnatw.m (gcc)
11682 @table @asis
11684 @item @code{-gnatw.m}
11686 @emph{Activate warnings on suspicious modulus values.}
11688 This switch activates warnings for modulus values that seem suspicious.
11689 The cases caught are where the size is the same as the modulus (e.g.
11690 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11691 with no size clause. The guess in both cases is that 2**x was intended
11692 rather than x. In addition expressions of the form 2*x for small x
11693 generate a warning (the almost certainly accurate guess being that
11694 2**x was intended). The default is that these warnings are given.
11695 @end table
11697 @geindex -gnatw.M (gcc)
11700 @table @asis
11702 @item @code{-gnatw.M}
11704 @emph{Disable warnings on suspicious modulus values.}
11706 This switch disables warnings for suspicious modulus values.
11707 @end table
11709 @geindex -gnatwn (gcc)
11712 @table @asis
11714 @item @code{-gnatwn}
11716 @emph{Set normal warnings mode.}
11718 This switch sets normal warning mode, in which enabled warnings are
11719 issued and treated as warnings rather than errors. This is the default
11720 mode. the switch @code{-gnatwn} can be used to cancel the effect of
11721 an explicit @code{-gnatws} or
11722 @code{-gnatwe}. It also cancels the effect of the
11723 implicit @code{-gnatwe} that is activated by the
11724 use of @code{-gnatg}.
11725 @end table
11727 @geindex -gnatw.n (gcc)
11729 @geindex Atomic Synchronization
11730 @geindex warnings
11733 @table @asis
11735 @item @code{-gnatw.n}
11737 @emph{Activate warnings on atomic synchronization.}
11739 This switch actives warnings when an access to an atomic variable
11740 requires the generation of atomic synchronization code. These
11741 warnings are off by default.
11742 @end table
11744 @geindex -gnatw.N (gcc)
11747 @table @asis
11749 @item @code{-gnatw.N}
11751 @emph{Suppress warnings on atomic synchronization.}
11753 @geindex Atomic Synchronization
11754 @geindex warnings
11756 This switch suppresses warnings when an access to an atomic variable
11757 requires the generation of atomic synchronization code.
11758 @end table
11760 @geindex -gnatwo (gcc)
11762 @geindex Address Clauses
11763 @geindex warnings
11766 @table @asis
11768 @item @code{-gnatwo}
11770 @emph{Activate warnings on address clause overlays.}
11772 This switch activates warnings for possibly unintended initialization
11773 effects of defining address clauses that cause one variable to overlap
11774 another. The default is that such warnings are generated.
11775 @end table
11777 @geindex -gnatwO (gcc)
11780 @table @asis
11782 @item @code{-gnatwO}
11784 @emph{Suppress warnings on address clause overlays.}
11786 This switch suppresses warnings on possibly unintended initialization
11787 effects of defining address clauses that cause one variable to overlap
11788 another.
11789 @end table
11791 @geindex -gnatw.o (gcc)
11794 @table @asis
11796 @item @code{-gnatw.o}
11798 @emph{Activate warnings on modified but unreferenced out parameters.}
11800 This switch activates warnings for variables that are modified by using
11801 them as actuals for a call to a procedure with an out mode formal, where
11802 the resulting assigned value is never read. It is applicable in the case
11803 where there is more than one out mode formal. If there is only one out
11804 mode formal, the warning is issued by default (controlled by -gnatwu).
11805 The warning is suppressed for volatile
11806 variables and also for variables that are renamings of other variables
11807 or for which an address clause is given.
11808 The default is that these warnings are not given.
11809 @end table
11811 @geindex -gnatw.O (gcc)
11814 @table @asis
11816 @item @code{-gnatw.O}
11818 @emph{Disable warnings on modified but unreferenced out parameters.}
11820 This switch suppresses warnings for variables that are modified by using
11821 them as actuals for a call to a procedure with an out mode formal, where
11822 the resulting assigned value is never read.
11823 @end table
11825 @geindex -gnatwp (gcc)
11827 @geindex Inlining
11828 @geindex warnings
11831 @table @asis
11833 @item @code{-gnatwp}
11835 @emph{Activate warnings on ineffective pragma Inlines.}
11837 This switch activates warnings for failure of front end inlining
11838 (activated by @code{-gnatN}) to inline a particular call. There are
11839 many reasons for not being able to inline a call, including most
11840 commonly that the call is too complex to inline. The default is
11841 that such warnings are not given.
11842 Warnings on ineffective inlining by the gcc back-end can be activated
11843 separately, using the gcc switch -Winline.
11844 @end table
11846 @geindex -gnatwP (gcc)
11849 @table @asis
11851 @item @code{-gnatwP}
11853 @emph{Suppress warnings on ineffective pragma Inlines.}
11855 This switch suppresses warnings on ineffective pragma Inlines. If the
11856 inlining mechanism cannot inline a call, it will simply ignore the
11857 request silently.
11858 @end table
11860 @geindex -gnatw.p (gcc)
11862 @geindex Parameter order
11863 @geindex warnings
11866 @table @asis
11868 @item @code{-gnatw.p}
11870 @emph{Activate warnings on parameter ordering.}
11872 This switch activates warnings for cases of suspicious parameter
11873 ordering when the list of arguments are all simple identifiers that
11874 match the names of the formals, but are in a different order. The
11875 warning is suppressed if any use of named parameter notation is used,
11876 so this is the appropriate way to suppress a false positive (and
11877 serves to emphasize that the "misordering" is deliberate). The
11878 default is that such warnings are not given.
11879 @end table
11881 @geindex -gnatw.P (gcc)
11884 @table @asis
11886 @item @code{-gnatw.P}
11888 @emph{Suppress warnings on parameter ordering.}
11890 This switch suppresses warnings on cases of suspicious parameter
11891 ordering.
11892 @end table
11894 @geindex -gnatwq (gcc)
11896 @geindex Parentheses
11897 @geindex warnings
11900 @table @asis
11902 @item @code{-gnatwq}
11904 @emph{Activate warnings on questionable missing parentheses.}
11906 This switch activates warnings for cases where parentheses are not used and
11907 the result is potential ambiguity from a readers point of view. For example
11908 (not a > b) when a and b are modular means ((not a) > b) and very likely the
11909 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
11910 quite likely ((-x) mod 5) was intended. In such situations it seems best to
11911 follow the rule of always parenthesizing to make the association clear, and
11912 this warning switch warns if such parentheses are not present. The default
11913 is that these warnings are given.
11914 @end table
11916 @geindex -gnatwQ (gcc)
11919 @table @asis
11921 @item @code{-gnatwQ}
11923 @emph{Suppress warnings on questionable missing parentheses.}
11925 This switch suppresses warnings for cases where the association is not
11926 clear and the use of parentheses is preferred.
11927 @end table
11929 @geindex -gnatw.q (gcc)
11931 @geindex Layout
11932 @geindex warnings
11935 @table @asis
11937 @item @code{-gnatw.q}
11939 @emph{Activate warnings on questionable layout of record types.}
11941 This switch activates warnings for cases where the default layout of
11942 a record type, that is to say the layout of its components in textual
11943 order of the source code, would very likely cause inefficiencies in
11944 the code generated by the compiler, both in terms of space and speed
11945 during execution. One warning is issued for each problematic component
11946 without representation clause in the nonvariant part and then in each
11947 variant recursively, if any.
11949 The purpose of these warnings is neither to prescribe an optimal layout
11950 nor to force the use of representation clauses, but rather to get rid of
11951 the most blatant inefficiencies in the layout. Therefore, the default
11952 layout is matched against the following synthetic ordered layout and
11953 the deviations are flagged on a component-by-component basis:
11956 @itemize *
11958 @item 
11959 first all components or groups of components whose length is fixed
11960 and a multiple of the storage unit,
11962 @item 
11963 then the remaining components whose length is fixed and not a multiple
11964 of the storage unit,
11966 @item 
11967 then the remaining components whose length doesn't depend on discriminants
11968 (that is to say, with variable but uniform length for all objects),
11970 @item 
11971 then all components whose length depends on discriminants,
11973 @item 
11974 finally the variant part (if any),
11975 @end itemize
11977 for the nonvariant part and for each variant recursively, if any.
11979 The exact wording of the warning depends on whether the compiler is allowed
11980 to reorder the components in the record type or precluded from doing it by
11981 means of pragma @code{No_Component_Reordering}.
11983 The default is that these warnings are not given.
11984 @end table
11986 @geindex -gnatw.Q (gcc)
11989 @table @asis
11991 @item @code{-gnatw.Q}
11993 @emph{Suppress warnings on questionable layout of record types.}
11995 This switch suppresses warnings for cases where the default layout of
11996 a record type would very likely cause inefficiencies.
11997 @end table
11999 @geindex -gnatwr (gcc)
12002 @table @asis
12004 @item @code{-gnatwr}
12006 @emph{Activate warnings on redundant constructs.}
12008 This switch activates warnings for redundant constructs. The following
12009 is the current list of constructs regarded as redundant:
12012 @itemize *
12014 @item 
12015 Assignment of an item to itself.
12017 @item 
12018 Type conversion that converts an expression to its own type.
12020 @item 
12021 Use of the attribute @code{Base} where @code{typ'Base} is the same
12022 as @code{typ}.
12024 @item 
12025 Use of pragma @code{Pack} when all components are placed by a record
12026 representation clause.
12028 @item 
12029 Exception handler containing only a reraise statement (raise with no
12030 operand) which has no effect.
12032 @item 
12033 Use of the operator abs on an operand that is known at compile time
12034 to be non-negative
12036 @item 
12037 Comparison of an object or (unary or binary) operation of boolean type to
12038 an explicit True value.
12039 @end itemize
12041 The default is that warnings for redundant constructs are not given.
12042 @end table
12044 @geindex -gnatwR (gcc)
12047 @table @asis
12049 @item @code{-gnatwR}
12051 @emph{Suppress warnings on redundant constructs.}
12053 This switch suppresses warnings for redundant constructs.
12054 @end table
12056 @geindex -gnatw.r (gcc)
12059 @table @asis
12061 @item @code{-gnatw.r}
12063 @emph{Activate warnings for object renaming function.}
12065 This switch activates warnings for an object renaming that renames a
12066 function call, which is equivalent to a constant declaration (as
12067 opposed to renaming the function itself).  The default is that these
12068 warnings are given.
12069 @end table
12071 @geindex -gnatwT (gcc)
12074 @table @asis
12076 @item @code{-gnatw.R}
12078 @emph{Suppress warnings for object renaming function.}
12080 This switch suppresses warnings for object renaming function.
12081 @end table
12083 @geindex -gnatws (gcc)
12086 @table @asis
12088 @item @code{-gnatws}
12090 @emph{Suppress all warnings.}
12092 This switch completely suppresses the
12093 output of all warning messages from the GNAT front end, including
12094 both warnings that can be controlled by switches described in this
12095 section, and those that are normally given unconditionally. The
12096 effect of this suppress action can only be cancelled by a subsequent
12097 use of the switch @code{-gnatwn}.
12099 Note that switch @code{-gnatws} does not suppress
12100 warnings from the @code{gcc} back end.
12101 To suppress these back end warnings as well, use the switch @code{-w}
12102 in addition to @code{-gnatws}. Also this switch has no effect on the
12103 handling of style check messages.
12104 @end table
12106 @geindex -gnatw.s (gcc)
12108 @geindex Record Representation (component sizes)
12111 @table @asis
12113 @item @code{-gnatw.s}
12115 @emph{Activate warnings on overridden size clauses.}
12117 This switch activates warnings on component clauses in record
12118 representation clauses where the length given overrides that
12119 specified by an explicit size clause for the component type. A
12120 warning is similarly given in the array case if a specified
12121 component size overrides an explicit size clause for the array
12122 component type.
12123 @end table
12125 @geindex -gnatw.S (gcc)
12128 @table @asis
12130 @item @code{-gnatw.S}
12132 @emph{Suppress warnings on overridden size clauses.}
12134 This switch suppresses warnings on component clauses in record
12135 representation clauses that override size clauses, and similar
12136 warnings when an array component size overrides a size clause.
12137 @end table
12139 @geindex -gnatwt (gcc)
12141 @geindex Deactivated code
12142 @geindex warnings
12144 @geindex Deleted code
12145 @geindex warnings
12148 @table @asis
12150 @item @code{-gnatwt}
12152 @emph{Activate warnings for tracking of deleted conditional code.}
12154 This switch activates warnings for tracking of code in conditionals (IF and
12155 CASE statements) that is detected to be dead code which cannot be executed, and
12156 which is removed by the front end. This warning is off by default. This may be
12157 useful for detecting deactivated code in certified applications.
12158 @end table
12160 @geindex -gnatwT (gcc)
12163 @table @asis
12165 @item @code{-gnatwT}
12167 @emph{Suppress warnings for tracking of deleted conditional code.}
12169 This switch suppresses warnings for tracking of deleted conditional code.
12170 @end table
12172 @geindex -gnatw.t (gcc)
12175 @table @asis
12177 @item @code{-gnatw.t}
12179 @emph{Activate warnings on suspicious contracts.}
12181 This switch activates warnings on suspicious contracts. This includes
12182 warnings on suspicious postconditions (whether a pragma @code{Postcondition} or a
12183 @code{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
12184 @code{Contract_Cases}). A function postcondition or contract case is suspicious
12185 when no postcondition or contract case for this function mentions the result
12186 of the function.  A procedure postcondition or contract case is suspicious
12187 when it only refers to the pre-state of the procedure, because in that case
12188 it should rather be expressed as a precondition. This switch also controls
12189 warnings on suspicious cases of expressions typically found in contracts like
12190 quantified expressions and uses of Update attribute. The default is that such
12191 warnings are generated.
12192 @end table
12194 @geindex -gnatw.T (gcc)
12197 @table @asis
12199 @item @code{-gnatw.T}
12201 @emph{Suppress warnings on suspicious contracts.}
12203 This switch suppresses warnings on suspicious contracts.
12204 @end table
12206 @geindex -gnatwu (gcc)
12209 @table @asis
12211 @item @code{-gnatwu}
12213 @emph{Activate warnings on unused entities.}
12215 This switch activates warnings to be generated for entities that
12216 are declared but not referenced, and for units that are @emph{with}ed
12217 and not
12218 referenced. In the case of packages, a warning is also generated if
12219 no entities in the package are referenced. This means that if a with'ed
12220 package is referenced but the only references are in @code{use}
12221 clauses or @code{renames}
12222 declarations, a warning is still generated. A warning is also generated
12223 for a generic package that is @emph{with}ed but never instantiated.
12224 In the case where a package or subprogram body is compiled, and there
12225 is a @emph{with} on the corresponding spec
12226 that is only referenced in the body,
12227 a warning is also generated, noting that the
12228 @emph{with} can be moved to the body. The default is that
12229 such warnings are not generated.
12230 This switch also activates warnings on unreferenced formals
12231 (it includes the effect of @code{-gnatwf}).
12232 @end table
12234 @geindex -gnatwU (gcc)
12237 @table @asis
12239 @item @code{-gnatwU}
12241 @emph{Suppress warnings on unused entities.}
12243 This switch suppresses warnings for unused entities and packages.
12244 It also turns off warnings on unreferenced formals (and thus includes
12245 the effect of @code{-gnatwF}).
12246 @end table
12248 @geindex -gnatw.u (gcc)
12251 @table @asis
12253 @item @code{-gnatw.u}
12255 @emph{Activate warnings on unordered enumeration types.}
12257 This switch causes enumeration types to be considered as conceptually
12258 unordered, unless an explicit pragma @code{Ordered} is given for the type.
12259 The effect is to generate warnings in clients that use explicit comparisons
12260 or subranges, since these constructs both treat objects of the type as
12261 ordered. (A @emph{client} is defined as a unit that is other than the unit in
12262 which the type is declared, or its body or subunits.) Please refer to
12263 the description of pragma @code{Ordered} in the
12264 @cite{GNAT Reference Manual} for further details.
12265 The default is that such warnings are not generated.
12266 @end table
12268 @geindex -gnatw.U (gcc)
12271 @table @asis
12273 @item @code{-gnatw.U}
12275 @emph{Deactivate warnings on unordered enumeration types.}
12277 This switch causes all enumeration types to be considered as ordered, so
12278 that no warnings are given for comparisons or subranges for any type.
12279 @end table
12281 @geindex -gnatwv (gcc)
12283 @geindex Unassigned variable warnings
12286 @table @asis
12288 @item @code{-gnatwv}
12290 @emph{Activate warnings on unassigned variables.}
12292 This switch activates warnings for access to variables which
12293 may not be properly initialized. The default is that
12294 such warnings are generated.
12295 @end table
12297 @geindex -gnatwV (gcc)
12300 @table @asis
12302 @item @code{-gnatwV}
12304 @emph{Suppress warnings on unassigned variables.}
12306 This switch suppresses warnings for access to variables which
12307 may not be properly initialized.
12308 For variables of a composite type, the warning can also be suppressed in
12309 Ada 2005 by using a default initialization with a box. For example, if
12310 Table is an array of records whose components are only partially uninitialized,
12311 then the following code:
12313 @example
12314 Tab : Table := (others => <>);
12315 @end example
12317 will suppress warnings on subsequent statements that access components
12318 of variable Tab.
12319 @end table
12321 @geindex -gnatw.v (gcc)
12323 @geindex bit order warnings
12326 @table @asis
12328 @item @code{-gnatw.v}
12330 @emph{Activate info messages for non-default bit order.}
12332 This switch activates messages (labeled "info", they are not warnings,
12333 just informational messages) about the effects of non-default bit-order
12334 on records to which a component clause is applied. The effect of specifying
12335 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
12336 these messages, which are given by default, are useful in understanding the
12337 exact consequences of using this feature.
12338 @end table
12340 @geindex -gnatw.V (gcc)
12343 @table @asis
12345 @item @code{-gnatw.V}
12347 @emph{Suppress info messages for non-default bit order.}
12349 This switch suppresses information messages for the effects of specifying
12350 non-default bit order on record components with component clauses.
12351 @end table
12353 @geindex -gnatww (gcc)
12355 @geindex String indexing warnings
12358 @table @asis
12360 @item @code{-gnatww}
12362 @emph{Activate warnings on wrong low bound assumption.}
12364 This switch activates warnings for indexing an unconstrained string parameter
12365 with a literal or S'Length. This is a case where the code is assuming that the
12366 low bound is one, which is in general not true (for example when a slice is
12367 passed). The default is that such warnings are generated.
12368 @end table
12370 @geindex -gnatwW (gcc)
12373 @table @asis
12375 @item @code{-gnatwW}
12377 @emph{Suppress warnings on wrong low bound assumption.}
12379 This switch suppresses warnings for indexing an unconstrained string parameter
12380 with a literal or S'Length. Note that this warning can also be suppressed
12381 in a particular case by adding an assertion that the lower bound is 1,
12382 as shown in the following example:
12384 @example
12385 procedure K (S : String) is
12386    pragma Assert (S'First = 1);
12387    ...
12388 @end example
12389 @end table
12391 @geindex -gnatw.w (gcc)
12393 @geindex Warnings Off control
12396 @table @asis
12398 @item @code{-gnatw.w}
12400 @emph{Activate warnings on Warnings Off pragmas.}
12402 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
12403 where either the pragma is entirely useless (because it suppresses no
12404 warnings), or it could be replaced by @code{pragma Unreferenced} or
12405 @code{pragma Unmodified}.
12406 Also activates warnings for the case of
12407 Warnings (Off, String), where either there is no matching
12408 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12409 The default is that these warnings are not given.
12410 @end table
12412 @geindex -gnatw.W (gcc)
12415 @table @asis
12417 @item @code{-gnatw.W}
12419 @emph{Suppress warnings on unnecessary Warnings Off pragmas.}
12421 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
12422 @end table
12424 @geindex -gnatwx (gcc)
12426 @geindex Export/Import pragma warnings
12429 @table @asis
12431 @item @code{-gnatwx}
12433 @emph{Activate warnings on Export/Import pragmas.}
12435 This switch activates warnings on Export/Import pragmas when
12436 the compiler detects a possible conflict between the Ada and
12437 foreign language calling sequences. For example, the use of
12438 default parameters in a convention C procedure is dubious
12439 because the C compiler cannot supply the proper default, so
12440 a warning is issued. The default is that such warnings are
12441 generated.
12442 @end table
12444 @geindex -gnatwX (gcc)
12447 @table @asis
12449 @item @code{-gnatwX}
12451 @emph{Suppress warnings on Export/Import pragmas.}
12453 This switch suppresses warnings on Export/Import pragmas.
12454 The sense of this is that you are telling the compiler that
12455 you know what you are doing in writing the pragma, and it
12456 should not complain at you.
12457 @end table
12459 @geindex -gnatwm (gcc)
12462 @table @asis
12464 @item @code{-gnatw.x}
12466 @emph{Activate warnings for No_Exception_Propagation mode.}
12468 This switch activates warnings for exception usage when pragma Restrictions
12469 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
12470 explicit exception raises which are not covered by a local handler, and for
12471 exception handlers which do not cover a local raise. The default is that
12472 these warnings are given for units that contain exception handlers.
12474 @item @code{-gnatw.X}
12476 @emph{Disable warnings for No_Exception_Propagation mode.}
12478 This switch disables warnings for exception usage when pragma Restrictions
12479 (No_Exception_Propagation) is in effect.
12480 @end table
12482 @geindex -gnatwy (gcc)
12484 @geindex Ada compatibility issues warnings
12487 @table @asis
12489 @item @code{-gnatwy}
12491 @emph{Activate warnings for Ada compatibility issues.}
12493 For the most part, newer versions of Ada are upwards compatible
12494 with older versions. For example, Ada 2005 programs will almost
12495 always work when compiled as Ada 2012.
12496 However there are some exceptions (for example the fact that
12497 @code{some} is now a reserved word in Ada 2012). This
12498 switch activates several warnings to help in identifying
12499 and correcting such incompatibilities. The default is that
12500 these warnings are generated. Note that at one point Ada 2005
12501 was called Ada 0Y, hence the choice of character.
12502 @end table
12504 @geindex -gnatwY (gcc)
12506 @geindex Ada compatibility issues warnings
12509 @table @asis
12511 @item @code{-gnatwY}
12513 @emph{Disable warnings for Ada compatibility issues.}
12515 This switch suppresses the warnings intended to help in identifying
12516 incompatibilities between Ada language versions.
12517 @end table
12519 @geindex -gnatw.y (gcc)
12521 @geindex Package spec needing body
12524 @table @asis
12526 @item @code{-gnatw.y}
12528 @emph{Activate information messages for why package spec needs body.}
12530 There are a number of cases in which a package spec needs a body.
12531 For example, the use of pragma Elaborate_Body, or the declaration
12532 of a procedure specification requiring a completion. This switch
12533 causes information messages to be output showing why a package
12534 specification requires a body. This can be useful in the case of
12535 a large package specification which is unexpectedly requiring a
12536 body. The default is that such information messages are not output.
12537 @end table
12539 @geindex -gnatw.Y (gcc)
12541 @geindex No information messages for why package spec needs body
12544 @table @asis
12546 @item @code{-gnatw.Y}
12548 @emph{Disable information messages for why package spec needs body.}
12550 This switch suppresses the output of information messages showing why
12551 a package specification needs a body.
12552 @end table
12554 @geindex -gnatwz (gcc)
12556 @geindex Unchecked_Conversion warnings
12559 @table @asis
12561 @item @code{-gnatwz}
12563 @emph{Activate warnings on unchecked conversions.}
12565 This switch activates warnings for unchecked conversions
12566 where the types are known at compile time to have different
12567 sizes. The default is that such warnings are generated. Warnings are also
12568 generated for subprogram pointers with different conventions.
12569 @end table
12571 @geindex -gnatwZ (gcc)
12574 @table @asis
12576 @item @code{-gnatwZ}
12578 @emph{Suppress warnings on unchecked conversions.}
12580 This switch suppresses warnings for unchecked conversions
12581 where the types are known at compile time to have different
12582 sizes or conventions.
12583 @end table
12585 @geindex -gnatw.z (gcc)
12587 @geindex Size/Alignment warnings
12590 @table @asis
12592 @item @code{-gnatw.z}
12594 @emph{Activate warnings for size not a multiple of alignment.}
12596 This switch activates warnings for cases of record types with
12597 specified @code{Size} and @code{Alignment} attributes where the
12598 size is not a multiple of the alignment, resulting in an object
12599 size that is greater than the specified size. The default
12600 is that such warnings are generated.
12601 @end table
12603 @geindex -gnatw.Z (gcc)
12605 @geindex Size/Alignment warnings
12608 @table @asis
12610 @item @code{-gnatw.Z}
12612 @emph{Suppress warnings for size not a multiple of alignment.}
12614 This switch suppresses warnings for cases of record types with
12615 specified @code{Size} and @code{Alignment} attributes where the
12616 size is not a multiple of the alignment, resulting in an object
12617 size that is greater than the specified size.
12618 The warning can also be
12619 suppressed by giving an explicit @code{Object_Size} value.
12620 @end table
12622 @geindex -Wunused (gcc)
12625 @table @asis
12627 @item @code{-Wunused}
12629 The warnings controlled by the @code{-gnatw} switch are generated by
12630 the front end of the compiler. The GCC back end can provide
12631 additional warnings and they are controlled by the @code{-W} switch.
12632 For example, @code{-Wunused} activates back end
12633 warnings for entities that are declared but not referenced.
12634 @end table
12636 @geindex -Wuninitialized (gcc)
12639 @table @asis
12641 @item @code{-Wuninitialized}
12643 Similarly, @code{-Wuninitialized} activates
12644 the back end warning for uninitialized variables. This switch must be
12645 used in conjunction with an optimization level greater than zero.
12646 @end table
12648 @geindex -Wstack-usage (gcc)
12651 @table @asis
12653 @item @code{-Wstack-usage=@emph{len}}
12655 Warn if the stack usage of a subprogram might be larger than @code{len} bytes.
12656 See @ref{f5,,Static Stack Usage Analysis} for details.
12657 @end table
12659 @geindex -Wall (gcc)
12662 @table @asis
12664 @item @code{-Wall}
12666 This switch enables most warnings from the GCC back end.
12667 The code generator detects a number of warning situations that are missed
12668 by the GNAT front end, and this switch can be used to activate them.
12669 The use of this switch also sets the default front end warning mode to
12670 @code{-gnatwa}, that is, most front end warnings activated as well.
12671 @end table
12673 @geindex -w (gcc)
12676 @table @asis
12678 @item @code{-w}
12680 Conversely, this switch suppresses warnings from the GCC back end.
12681 The use of this switch also sets the default front end warning mode to
12682 @code{-gnatws}, that is, front end warnings suppressed as well.
12683 @end table
12685 @geindex -Werror (gcc)
12688 @table @asis
12690 @item @code{-Werror}
12692 This switch causes warnings from the GCC back end to be treated as
12693 errors.  The warning string still appears, but the warning messages are
12694 counted as errors, and prevent the generation of an object file.
12695 @end table
12697 A string of warning parameters can be used in the same parameter. For example:
12699 @example
12700 -gnatwaGe
12701 @end example
12703 will turn on all optional warnings except for unrecognized pragma warnings,
12704 and also specify that warnings should be treated as errors.
12706 When no switch @code{-gnatw} is used, this is equivalent to:
12708 @quotation
12711 @itemize *
12713 @item 
12714 @code{-gnatw.a}
12716 @item 
12717 @code{-gnatwB}
12719 @item 
12720 @code{-gnatw.b}
12722 @item 
12723 @code{-gnatwC}
12725 @item 
12726 @code{-gnatw.C}
12728 @item 
12729 @code{-gnatwD}
12731 @item 
12732 @code{-gnatw.D}
12734 @item 
12735 @code{-gnatwF}
12737 @item 
12738 @code{-gnatw.F}
12740 @item 
12741 @code{-gnatwg}
12743 @item 
12744 @code{-gnatwH}
12746 @item 
12747 @code{-gnatw.H}
12749 @item 
12750 @code{-gnatwi}
12752 @item 
12753 @code{-gnatwJ}
12755 @item 
12756 @code{-gnatw.J}
12758 @item 
12759 @code{-gnatwK}
12761 @item 
12762 @code{-gnatw.K}
12764 @item 
12765 @code{-gnatwL}
12767 @item 
12768 @code{-gnatw.L}
12770 @item 
12771 @code{-gnatwM}
12773 @item 
12774 @code{-gnatw.m}
12776 @item 
12777 @code{-gnatwn}
12779 @item 
12780 @code{-gnatw.N}
12782 @item 
12783 @code{-gnatwo}
12785 @item 
12786 @code{-gnatw.O}
12788 @item 
12789 @code{-gnatwP}
12791 @item 
12792 @code{-gnatw.P}
12794 @item 
12795 @code{-gnatwq}
12797 @item 
12798 @code{-gnatw.Q}
12800 @item 
12801 @code{-gnatwR}
12803 @item 
12804 @code{-gnatw.R}
12806 @item 
12807 @code{-gnatw.S}
12809 @item 
12810 @code{-gnatwT}
12812 @item 
12813 @code{-gnatw.t}
12815 @item 
12816 @code{-gnatwU}
12818 @item 
12819 @code{-gnatw.U}
12821 @item 
12822 @code{-gnatwv}
12824 @item 
12825 @code{-gnatw.v}
12827 @item 
12828 @code{-gnatww}
12830 @item 
12831 @code{-gnatw.W}
12833 @item 
12834 @code{-gnatwx}
12836 @item 
12837 @code{-gnatw.X}
12839 @item 
12840 @code{-gnatwy}
12842 @item 
12843 @code{-gnatw.Y}
12845 @item 
12846 @code{-gnatwz}
12848 @item 
12849 @code{-gnatw.z}
12850 @end itemize
12851 @end quotation
12853 @node Debugging and Assertion Control,Validity Checking,Warning Message Control,Compiler Switches
12854 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-and-assertion-control}@anchor{100}@anchor{gnat_ugn/building_executable_programs_with_gnat id16}@anchor{101}
12855 @subsection Debugging and Assertion Control
12858 @geindex -gnata (gcc)
12861 @table @asis
12863 @item @code{-gnata}
12865 @geindex Assert
12867 @geindex Debug
12869 @geindex Assertions
12871 @geindex Precondition
12873 @geindex Postcondition
12875 @geindex Type invariants
12877 @geindex Subtype predicates
12879 The @code{-gnata} option is equivalent to the following @code{Assertion_Policy} pragma:
12881 @example
12882 pragma Assertion_Policy (Check);
12883 @end example
12885 Which is a shorthand for:
12887 @example
12888 pragma Assertion_Policy
12889   (Assert               => Check,
12890    Static_Predicate     => Check,
12891    Dynamic_Predicate    => Check,
12892    Pre                  => Check,
12893    Pre'Class            => Check,
12894    Post                 => Check,
12895    Post'Class           => Check,
12896    Type_Invariant       => Check,
12897    Type_Invariant'Class => Check);
12898 @end example
12900 The pragmas @code{Assert} and @code{Debug} normally have no effect and
12901 are ignored. This switch, where @code{a} stands for 'assert', causes
12902 pragmas @code{Assert} and @code{Debug} to be activated. This switch also
12903 causes preconditions, postconditions, subtype predicates, and
12904 type invariants to be activated.
12906 The pragmas have the form:
12908 @example
12909 pragma Assert (<Boolean-expression> [, <static-string-expression>])
12910 pragma Debug (<procedure call>)
12911 pragma Type_Invariant (<type-local-name>, <Boolean-expression>)
12912 pragma Predicate (<type-local-name>, <Boolean-expression>)
12913 pragma Precondition (<Boolean-expression>, <string-expression>)
12914 pragma Postcondition (<Boolean-expression>, <string-expression>)
12915 @end example
12917 The aspects have the form:
12919 @example
12920 with [Pre|Post|Type_Invariant|Dynamic_Predicate|Static_Predicate]
12921   => <Boolean-expression>;
12922 @end example
12924 The @code{Assert} pragma causes @code{Boolean-expression} to be tested.
12925 If the result is @code{True}, the pragma has no effect (other than
12926 possible side effects from evaluating the expression). If the result is
12927 @code{False}, the exception @code{Assert_Failure} declared in the package
12928 @code{System.Assertions} is raised (passing @code{static-string-expression}, if
12929 present, as the message associated with the exception). If no string
12930 expression is given, the default is a string containing the file name and
12931 line number of the pragma.
12933 The @code{Debug} pragma causes @code{procedure} to be called. Note that
12934 @code{pragma Debug} may appear within a declaration sequence, allowing
12935 debugging procedures to be called between declarations.
12937 For the aspect specification, the @code{Boolean-expression} is evaluated.
12938 If the result is @code{True}, the aspect has no effect. If the result
12939 is @code{False}, the exception @code{Assert_Failure} is raised.
12940 @end table
12942 @node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
12943 @anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{102}
12944 @subsection Validity Checking
12947 @geindex Validity Checking
12949 The Ada Reference Manual defines the concept of invalid values (see
12950 RM 13.9.1). The primary source of invalid values is uninitialized
12951 variables. A scalar variable that is left uninitialized may contain
12952 an invalid value; the concept of invalid does not apply to access or
12953 composite types.
12955 It is an error to read an invalid value, but the RM does not require
12956 run-time checks to detect such errors, except for some minimal
12957 checking to prevent erroneous execution (i.e. unpredictable
12958 behavior). This corresponds to the @code{-gnatVd} switch below,
12959 which is the default. For example, by default, if the expression of a
12960 case statement is invalid, it will raise Constraint_Error rather than
12961 causing a wild jump, and if an array index on the left-hand side of an
12962 assignment is invalid, it will raise Constraint_Error rather than
12963 overwriting an arbitrary memory location.
12965 The @code{-gnatVa} may be used to enable additional validity checks,
12966 which are not required by the RM. These checks are often very
12967 expensive (which is why the RM does not require them). These checks
12968 are useful in tracking down uninitialized variables, but they are
12969 not usually recommended for production builds, and in particular
12970 we do not recommend using these extra validity checking options in
12971 combination with optimization, since this can confuse the optimizer.
12972 If performance is a consideration, leading to the need to optimize,
12973 then the validity checking options should not be used.
12975 The other @code{-gnatV@emph{x}} switches below allow finer-grained
12976 control; you can enable whichever validity checks you desire. However,
12977 for most debugging purposes, @code{-gnatVa} is sufficient, and the
12978 default @code{-gnatVd} (i.e. standard Ada behavior) is usually
12979 sufficient for non-debugging use.
12981 The @code{-gnatB} switch tells the compiler to assume that all
12982 values are valid (that is, within their declared subtype range)
12983 except in the context of a use of the Valid attribute. This means
12984 the compiler can generate more efficient code, since the range
12985 of values is better known at compile time. However, an uninitialized
12986 variable can cause wild jumps and memory corruption in this mode.
12988 The @code{-gnatV@emph{x}} switch allows control over the validity
12989 checking mode as described below.
12990 The @code{x} argument is a string of letters that
12991 indicate validity checks that are performed or not performed in addition
12992 to the default checks required by Ada as described above.
12994 @geindex -gnatVa (gcc)
12997 @table @asis
12999 @item @code{-gnatVa}
13001 @emph{All validity checks.}
13003 All validity checks are turned on.
13004 That is, @code{-gnatVa} is
13005 equivalent to @code{gnatVcdfimorst}.
13006 @end table
13008 @geindex -gnatVc (gcc)
13011 @table @asis
13013 @item @code{-gnatVc}
13015 @emph{Validity checks for copies.}
13017 The right hand side of assignments, and the initializing values of
13018 object declarations are validity checked.
13019 @end table
13021 @geindex -gnatVd (gcc)
13024 @table @asis
13026 @item @code{-gnatVd}
13028 @emph{Default (RM) validity checks.}
13030 Some validity checks are done by default following normal Ada semantics
13031 (RM 13.9.1 (9-11)).
13032 A check is done in case statements that the expression is within the range
13033 of the subtype. If it is not, Constraint_Error is raised.
13034 For assignments to array components, a check is done that the expression used
13035 as index is within the range. If it is not, Constraint_Error is raised.
13036 Both these validity checks may be turned off using switch @code{-gnatVD}.
13037 They are turned on by default. If @code{-gnatVD} is specified, a subsequent
13038 switch @code{-gnatVd} will leave the checks turned on.
13039 Switch @code{-gnatVD} should be used only if you are sure that all such
13040 expressions have valid values. If you use this switch and invalid values
13041 are present, then the program is erroneous, and wild jumps or memory
13042 overwriting may occur.
13043 @end table
13045 @geindex -gnatVe (gcc)
13048 @table @asis
13050 @item @code{-gnatVe}
13052 @emph{Validity checks for elementary components.}
13054 In the absence of this switch, assignments to record or array components are
13055 not validity checked, even if validity checks for assignments generally
13056 (@code{-gnatVc}) are turned on. In Ada, assignment of composite values do not
13057 require valid data, but assignment of individual components does. So for
13058 example, there is a difference between copying the elements of an array with a
13059 slice assignment, compared to assigning element by element in a loop. This
13060 switch allows you to turn off validity checking for components, even when they
13061 are assigned component by component.
13062 @end table
13064 @geindex -gnatVf (gcc)
13067 @table @asis
13069 @item @code{-gnatVf}
13071 @emph{Validity checks for floating-point values.}
13073 In the absence of this switch, validity checking occurs only for discrete
13074 values. If @code{-gnatVf} is specified, then validity checking also applies
13075 for floating-point values, and NaNs and infinities are considered invalid,
13076 as well as out of range values for constrained types. Note that this means
13077 that standard IEEE infinity mode is not allowed. The exact contexts
13078 in which floating-point values are checked depends on the setting of other
13079 options. For example, @code{-gnatVif} or @code{-gnatVfi}
13080 (the order does not matter) specifies that floating-point parameters of mode
13081 @code{in} should be validity checked.
13082 @end table
13084 @geindex -gnatVi (gcc)
13087 @table @asis
13089 @item @code{-gnatVi}
13091 @emph{Validity checks for `@w{`}in`@w{`} mode parameters.}
13093 Arguments for parameters of mode @code{in} are validity checked in function
13094 and procedure calls at the point of call.
13095 @end table
13097 @geindex -gnatVm (gcc)
13100 @table @asis
13102 @item @code{-gnatVm}
13104 @emph{Validity checks for `@w{`}in out`@w{`} mode parameters.}
13106 Arguments for parameters of mode @code{in out} are validity checked in
13107 procedure calls at the point of call. The @code{'m'} here stands for
13108 modify, since this concerns parameters that can be modified by the call.
13109 Note that there is no specific option to test @code{out} parameters,
13110 but any reference within the subprogram will be tested in the usual
13111 manner, and if an invalid value is copied back, any reference to it
13112 will be subject to validity checking.
13113 @end table
13115 @geindex -gnatVn (gcc)
13118 @table @asis
13120 @item @code{-gnatVn}
13122 @emph{No validity checks.}
13124 This switch turns off all validity checking, including the default checking
13125 for case statements and left hand side subscripts. Note that the use of
13126 the switch @code{-gnatp} suppresses all run-time checks, including
13127 validity checks, and thus implies @code{-gnatVn}. When this switch
13128 is used, it cancels any other @code{-gnatV} previously issued.
13129 @end table
13131 @geindex -gnatVo (gcc)
13134 @table @asis
13136 @item @code{-gnatVo}
13138 @emph{Validity checks for operator and attribute operands.}
13140 Arguments for predefined operators and attributes are validity checked.
13141 This includes all operators in package @code{Standard},
13142 the shift operators defined as intrinsic in package @code{Interfaces}
13143 and operands for attributes such as @code{Pos}. Checks are also made
13144 on individual component values for composite comparisons, and on the
13145 expressions in type conversions and qualified expressions. Checks are
13146 also made on explicit ranges using @code{..} (e.g., slices, loops etc).
13147 @end table
13149 @geindex -gnatVp (gcc)
13152 @table @asis
13154 @item @code{-gnatVp}
13156 @emph{Validity checks for parameters.}
13158 This controls the treatment of parameters within a subprogram (as opposed
13159 to @code{-gnatVi} and @code{-gnatVm} which control validity testing
13160 of parameters on a call. If either of these call options is used, then
13161 normally an assumption is made within a subprogram that the input arguments
13162 have been validity checking at the point of call, and do not need checking
13163 again within a subprogram). If @code{-gnatVp} is set, then this assumption
13164 is not made, and parameters are not assumed to be valid, so their validity
13165 will be checked (or rechecked) within the subprogram.
13166 @end table
13168 @geindex -gnatVr (gcc)
13171 @table @asis
13173 @item @code{-gnatVr}
13175 @emph{Validity checks for function returns.}
13177 The expression in @code{return} statements in functions is validity
13178 checked.
13179 @end table
13181 @geindex -gnatVs (gcc)
13184 @table @asis
13186 @item @code{-gnatVs}
13188 @emph{Validity checks for subscripts.}
13190 All subscripts expressions are checked for validity, whether they appear
13191 on the right side or left side (in default mode only left side subscripts
13192 are validity checked).
13193 @end table
13195 @geindex -gnatVt (gcc)
13198 @table @asis
13200 @item @code{-gnatVt}
13202 @emph{Validity checks for tests.}
13204 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
13205 statements are checked, as well as guard expressions in entry calls.
13206 @end table
13208 The @code{-gnatV} switch may be followed by a string of letters
13209 to turn on a series of validity checking options.
13210 For example, @code{-gnatVcr}
13211 specifies that in addition to the default validity checking, copies and
13212 function return expressions are to be validity checked.
13213 In order to make it easier to specify the desired combination of effects,
13214 the upper case letters @code{CDFIMORST} may
13215 be used to turn off the corresponding lower case option.
13216 Thus @code{-gnatVaM} turns on all validity checking options except for
13217 checking of @code{in out} parameters.
13219 The specification of additional validity checking generates extra code (and
13220 in the case of @code{-gnatVa} the code expansion can be substantial).
13221 However, these additional checks can be very useful in detecting
13222 uninitialized variables, incorrect use of unchecked conversion, and other
13223 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
13224 is useful in conjunction with the extra validity checking, since this
13225 ensures that wherever possible uninitialized variables have invalid values.
13227 See also the pragma @code{Validity_Checks} which allows modification of
13228 the validity checking mode at the program source level, and also allows for
13229 temporary disabling of validity checks.
13231 @node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
13232 @anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{103}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{fb}
13233 @subsection Style Checking
13236 @geindex Style checking
13238 @geindex -gnaty (gcc)
13240 The @code{-gnatyx} switch causes the compiler to
13241 enforce specified style rules. A limited set of style rules has been used
13242 in writing the GNAT sources themselves. This switch allows user programs
13243 to activate all or some of these checks. If the source program fails a
13244 specified style check, an appropriate message is given, preceded by
13245 the character sequence '(style)'. This message does not prevent
13246 successful compilation (unless the @code{-gnatwe} switch is used).
13248 Note that this is by no means intended to be a general facility for
13249 checking arbitrary coding standards. It is simply an embedding of the
13250 style rules we have chosen for the GNAT sources. If you are starting
13251 a project which does not have established style standards, you may
13252 find it useful to adopt the entire set of GNAT coding standards, or
13253 some subset of them.
13256 The string @code{x} is a sequence of letters or digits
13257 indicating the particular style
13258 checks to be performed. The following checks are defined:
13260 @geindex -gnaty[0-9] (gcc)
13263 @table @asis
13265 @item @code{-gnaty0}
13267 @emph{Specify indentation level.}
13269 If a digit from 1-9 appears
13270 in the string after @code{-gnaty}
13271 then proper indentation is checked, with the digit indicating the
13272 indentation level required. A value of zero turns off this style check.
13273 The general style of required indentation is as specified by
13274 the examples in the Ada Reference Manual. Full line comments must be
13275 aligned with the @code{--} starting on a column that is a multiple of
13276 the alignment level, or they may be aligned the same way as the following
13277 non-blank line (this is useful when full line comments appear in the middle
13278 of a statement, or they may be aligned with the source line on the previous
13279 non-blank line.
13280 @end table
13282 @geindex -gnatya (gcc)
13285 @table @asis
13287 @item @code{-gnatya}
13289 @emph{Check attribute casing.}
13291 Attribute names, including the case of keywords such as @code{digits}
13292 used as attributes names, must be written in mixed case, that is, the
13293 initial letter and any letter following an underscore must be uppercase.
13294 All other letters must be lowercase.
13295 @end table
13297 @geindex -gnatyA (gcc)
13300 @table @asis
13302 @item @code{-gnatyA}
13304 @emph{Use of array index numbers in array attributes.}
13306 When using the array attributes First, Last, Range,
13307 or Length, the index number must be omitted for one-dimensional arrays
13308 and is required for multi-dimensional arrays.
13309 @end table
13311 @geindex -gnatyb (gcc)
13314 @table @asis
13316 @item @code{-gnatyb}
13318 @emph{Blanks not allowed at statement end.}
13320 Trailing blanks are not allowed at the end of statements. The purpose of this
13321 rule, together with h (no horizontal tabs), is to enforce a canonical format
13322 for the use of blanks to separate source tokens.
13323 @end table
13325 @geindex -gnatyB (gcc)
13328 @table @asis
13330 @item @code{-gnatyB}
13332 @emph{Check Boolean operators.}
13334 The use of AND/OR operators is not permitted except in the cases of modular
13335 operands, array operands, and simple stand-alone boolean variables or
13336 boolean constants. In all other cases @code{and then}/@cite{or else} are
13337 required.
13338 @end table
13340 @geindex -gnatyc (gcc)
13343 @table @asis
13345 @item @code{-gnatyc}
13347 @emph{Check comments, double space.}
13349 Comments must meet the following set of rules:
13352 @itemize *
13354 @item 
13355 The @code{--} that starts the column must either start in column one,
13356 or else at least one blank must precede this sequence.
13358 @item 
13359 Comments that follow other tokens on a line must have at least one blank
13360 following the @code{--} at the start of the comment.
13362 @item 
13363 Full line comments must have at least two blanks following the
13364 @code{--} that starts the comment, with the following exceptions.
13366 @item 
13367 A line consisting only of the @code{--} characters, possibly preceded
13368 by blanks is permitted.
13370 @item 
13371 A comment starting with @code{--x} where @code{x} is a special character
13372 is permitted.
13373 This allows proper processing of the output from specialized tools
13374 such as @code{gnatprep} (where @code{--!} is used) and in earlier versions of the SPARK
13375 annotation
13376 language (where @code{--#} is used). For the purposes of this rule, a
13377 special character is defined as being in one of the ASCII ranges
13378 @code{16#21#...16#2F#} or @code{16#3A#...16#3F#}.
13379 Note that this usage is not permitted
13380 in GNAT implementation units (i.e., when @code{-gnatg} is used).
13382 @item 
13383 A line consisting entirely of minus signs, possibly preceded by blanks, is
13384 permitted. This allows the construction of box comments where lines of minus
13385 signs are used to form the top and bottom of the box.
13387 @item 
13388 A comment that starts and ends with @code{--} is permitted as long as at
13389 least one blank follows the initial @code{--}. Together with the preceding
13390 rule, this allows the construction of box comments, as shown in the following
13391 example:
13393 @example
13394 ---------------------------
13395 -- This is a box comment --
13396 -- with two text lines.  --
13397 ---------------------------
13398 @end example
13399 @end itemize
13400 @end table
13402 @geindex -gnatyC (gcc)
13405 @table @asis
13407 @item @code{-gnatyC}
13409 @emph{Check comments, single space.}
13411 This is identical to @code{c} except that only one space
13412 is required following the @code{--} of a comment instead of two.
13413 @end table
13415 @geindex -gnatyd (gcc)
13418 @table @asis
13420 @item @code{-gnatyd}
13422 @emph{Check no DOS line terminators present.}
13424 All lines must be terminated by a single ASCII.LF
13425 character (in particular the DOS line terminator sequence CR/LF is not
13426 allowed).
13427 @end table
13429 @geindex -gnatye (gcc)
13432 @table @asis
13434 @item @code{-gnatye}
13436 @emph{Check end/exit labels.}
13438 Optional labels on @code{end} statements ending subprograms and on
13439 @code{exit} statements exiting named loops, are required to be present.
13440 @end table
13442 @geindex -gnatyf (gcc)
13445 @table @asis
13447 @item @code{-gnatyf}
13449 @emph{No form feeds or vertical tabs.}
13451 Neither form feeds nor vertical tab characters are permitted
13452 in the source text.
13453 @end table
13455 @geindex -gnatyg (gcc)
13458 @table @asis
13460 @item @code{-gnatyg}
13462 @emph{GNAT style mode.}
13464 The set of style check switches is set to match that used by the GNAT sources.
13465 This may be useful when developing code that is eventually intended to be
13466 incorporated into GNAT. Currently this is equivalent to @code{-gnatwydISux})
13467 but additional style switches may be added to this set in the future without
13468 advance notice.
13469 @end table
13471 @geindex -gnatyh (gcc)
13474 @table @asis
13476 @item @code{-gnatyh}
13478 @emph{No horizontal tabs.}
13480 Horizontal tab characters are not permitted in the source text.
13481 Together with the b (no blanks at end of line) check, this
13482 enforces a canonical form for the use of blanks to separate
13483 source tokens.
13484 @end table
13486 @geindex -gnatyi (gcc)
13489 @table @asis
13491 @item @code{-gnatyi}
13493 @emph{Check if-then layout.}
13495 The keyword @code{then} must appear either on the same
13496 line as corresponding @code{if}, or on a line on its own, lined
13497 up under the @code{if}.
13498 @end table
13500 @geindex -gnatyI (gcc)
13503 @table @asis
13505 @item @code{-gnatyI}
13507 @emph{check mode IN keywords.}
13509 Mode @code{in} (the default mode) is not
13510 allowed to be given explicitly. @code{in out} is fine,
13511 but not @code{in} on its own.
13512 @end table
13514 @geindex -gnatyk (gcc)
13517 @table @asis
13519 @item @code{-gnatyk}
13521 @emph{Check keyword casing.}
13523 All keywords must be in lower case (with the exception of keywords
13524 such as @code{digits} used as attribute names to which this check
13525 does not apply).
13526 @end table
13528 @geindex -gnatyl (gcc)
13531 @table @asis
13533 @item @code{-gnatyl}
13535 @emph{Check layout.}
13537 Layout of statement and declaration constructs must follow the
13538 recommendations in the Ada Reference Manual, as indicated by the
13539 form of the syntax rules. For example an @code{else} keyword must
13540 be lined up with the corresponding @code{if} keyword.
13542 There are two respects in which the style rule enforced by this check
13543 option are more liberal than those in the Ada Reference Manual. First
13544 in the case of record declarations, it is permissible to put the
13545 @code{record} keyword on the same line as the @code{type} keyword, and
13546 then the @code{end} in @code{end record} must line up under @code{type}.
13547 This is also permitted when the type declaration is split on two lines.
13548 For example, any of the following three layouts is acceptable:
13550 @example
13551 type q is record
13552    a : integer;
13553    b : integer;
13554 end record;
13556 type q is
13557    record
13558       a : integer;
13559       b : integer;
13560    end record;
13562 type q is
13563    record
13564       a : integer;
13565       b : integer;
13566 end record;
13567 @end example
13569 Second, in the case of a block statement, a permitted alternative
13570 is to put the block label on the same line as the @code{declare} or
13571 @code{begin} keyword, and then line the @code{end} keyword up under
13572 the block label. For example both the following are permitted:
13574 @example
13575 Block : declare
13576    A : Integer := 3;
13577 begin
13578    Proc (A, A);
13579 end Block;
13581 Block :
13582    declare
13583       A : Integer := 3;
13584    begin
13585       Proc (A, A);
13586    end Block;
13587 @end example
13589 The same alternative format is allowed for loops. For example, both of
13590 the following are permitted:
13592 @example
13593 Clear : while J < 10 loop
13594    A (J) := 0;
13595 end loop Clear;
13597 Clear :
13598    while J < 10 loop
13599       A (J) := 0;
13600    end loop Clear;
13601 @end example
13602 @end table
13604 @geindex -gnatyLnnn (gcc)
13607 @table @asis
13609 @item @code{-gnatyL}
13611 @emph{Set maximum nesting level.}
13613 The maximum level of nesting of constructs (including subprograms, loops,
13614 blocks, packages, and conditionals) may not exceed the given value
13615 @emph{nnn}. A value of zero disconnects this style check.
13616 @end table
13618 @geindex -gnatym (gcc)
13621 @table @asis
13623 @item @code{-gnatym}
13625 @emph{Check maximum line length.}
13627 The length of source lines must not exceed 79 characters, including
13628 any trailing blanks. The value of 79 allows convenient display on an
13629 80 character wide device or window, allowing for possible special
13630 treatment of 80 character lines. Note that this count is of
13631 characters in the source text. This means that a tab character counts
13632 as one character in this count and a wide character sequence counts as
13633 a single character (however many bytes are needed in the encoding).
13634 @end table
13636 @geindex -gnatyMnnn (gcc)
13639 @table @asis
13641 @item @code{-gnatyM}
13643 @emph{Set maximum line length.}
13645 The length of lines must not exceed the
13646 given value @emph{nnn}. The maximum value that can be specified is 32767.
13647 If neither style option for setting the line length is used, then the
13648 default is 255. This also controls the maximum length of lexical elements,
13649 where the only restriction is that they must fit on a single line.
13650 @end table
13652 @geindex -gnatyn (gcc)
13655 @table @asis
13657 @item @code{-gnatyn}
13659 @emph{Check casing of entities in Standard.}
13661 Any identifier from Standard must be cased
13662 to match the presentation in the Ada Reference Manual (for example,
13663 @code{Integer} and @code{ASCII.NUL}).
13664 @end table
13666 @geindex -gnatyN (gcc)
13669 @table @asis
13671 @item @code{-gnatyN}
13673 @emph{Turn off all style checks.}
13675 All style check options are turned off.
13676 @end table
13678 @geindex -gnatyo (gcc)
13681 @table @asis
13683 @item @code{-gnatyo}
13685 @emph{Check order of subprogram bodies.}
13687 All subprogram bodies in a given scope
13688 (e.g., a package body) must be in alphabetical order. The ordering
13689 rule uses normal Ada rules for comparing strings, ignoring casing
13690 of letters, except that if there is a trailing numeric suffix, then
13691 the value of this suffix is used in the ordering (e.g., Junk2 comes
13692 before Junk10).
13693 @end table
13695 @geindex -gnatyO (gcc)
13698 @table @asis
13700 @item @code{-gnatyO}
13702 @emph{Check that overriding subprograms are explicitly marked as such.}
13704 This applies to all subprograms of a derived type that override a primitive
13705 operation of the type, for both tagged and untagged types. In particular,
13706 the declaration of a primitive operation of a type extension that overrides
13707 an inherited operation must carry an overriding indicator. Another case is
13708 the declaration of a function that overrides a predefined operator (such
13709 as an equality operator).
13710 @end table
13712 @geindex -gnatyp (gcc)
13715 @table @asis
13717 @item @code{-gnatyp}
13719 @emph{Check pragma casing.}
13721 Pragma names must be written in mixed case, that is, the
13722 initial letter and any letter following an underscore must be uppercase.
13723 All other letters must be lowercase. An exception is that SPARK_Mode is
13724 allowed as an alternative for Spark_Mode.
13725 @end table
13727 @geindex -gnatyr (gcc)
13730 @table @asis
13732 @item @code{-gnatyr}
13734 @emph{Check references.}
13736 All identifier references must be cased in the same way as the
13737 corresponding declaration. No specific casing style is imposed on
13738 identifiers. The only requirement is for consistency of references
13739 with declarations.
13740 @end table
13742 @geindex -gnatys (gcc)
13745 @table @asis
13747 @item @code{-gnatys}
13749 @emph{Check separate specs.}
13751 Separate declarations ('specs') are required for subprograms (a
13752 body is not allowed to serve as its own declaration). The only
13753 exception is that parameterless library level procedures are
13754 not required to have a separate declaration. This exception covers
13755 the most frequent form of main program procedures.
13756 @end table
13758 @geindex -gnatyS (gcc)
13761 @table @asis
13763 @item @code{-gnatyS}
13765 @emph{Check no statements after then/else.}
13767 No statements are allowed
13768 on the same line as a @code{then} or @code{else} keyword following the
13769 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
13770 affected, and a special exception allows a pragma to appear after @code{else}.
13771 @end table
13773 @geindex -gnatyt (gcc)
13776 @table @asis
13778 @item @code{-gnatyt}
13780 @emph{Check token spacing.}
13782 The following token spacing rules are enforced:
13785 @itemize *
13787 @item 
13788 The keywords @code{abs} and @code{not} must be followed by a space.
13790 @item 
13791 The token @code{=>} must be surrounded by spaces.
13793 @item 
13794 The token @code{<>} must be preceded by a space or a left parenthesis.
13796 @item 
13797 Binary operators other than @code{**} must be surrounded by spaces.
13798 There is no restriction on the layout of the @code{**} binary operator.
13800 @item 
13801 Colon must be surrounded by spaces.
13803 @item 
13804 Colon-equal (assignment, initialization) must be surrounded by spaces.
13806 @item 
13807 Comma must be the first non-blank character on the line, or be
13808 immediately preceded by a non-blank character, and must be followed
13809 by a space.
13811 @item 
13812 If the token preceding a left parenthesis ends with a letter or digit, then
13813 a space must separate the two tokens.
13815 @item 
13816 If the token following a right parenthesis starts with a letter or digit, then
13817 a space must separate the two tokens.
13819 @item 
13820 A right parenthesis must either be the first non-blank character on
13821 a line, or it must be preceded by a non-blank character.
13823 @item 
13824 A semicolon must not be preceded by a space, and must not be followed by
13825 a non-blank character.
13827 @item 
13828 A unary plus or minus may not be followed by a space.
13830 @item 
13831 A vertical bar must be surrounded by spaces.
13832 @end itemize
13834 Exactly one blank (and no other white space) must appear between
13835 a @code{not} token and a following @code{in} token.
13836 @end table
13838 @geindex -gnatyu (gcc)
13841 @table @asis
13843 @item @code{-gnatyu}
13845 @emph{Check unnecessary blank lines.}
13847 Unnecessary blank lines are not allowed. A blank line is considered
13848 unnecessary if it appears at the end of the file, or if more than
13849 one blank line occurs in sequence.
13850 @end table
13852 @geindex -gnatyx (gcc)
13855 @table @asis
13857 @item @code{-gnatyx}
13859 @emph{Check extra parentheses.}
13861 Unnecessary extra level of parentheses (C-style) are not allowed
13862 around conditions in @code{if} statements, @code{while} statements and
13863 @code{exit} statements.
13864 @end table
13866 @geindex -gnatyy (gcc)
13869 @table @asis
13871 @item @code{-gnatyy}
13873 @emph{Set all standard style check options.}
13875 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
13876 options enabled with the exception of @code{-gnatyB}, @code{-gnatyd},
13877 @code{-gnatyI}, @code{-gnatyLnnn}, @code{-gnatyo}, @code{-gnatyO},
13878 @code{-gnatyS}, @code{-gnatyu}, and @code{-gnatyx}.
13879 @end table
13881 @geindex -gnaty- (gcc)
13884 @table @asis
13886 @item @code{-gnaty-}
13888 @emph{Remove style check options.}
13890 This causes any subsequent options in the string to act as canceling the
13891 corresponding style check option. To cancel maximum nesting level control,
13892 use the @code{L} parameter without any integer value after that, because any
13893 digit following @emph{-} in the parameter string of the @code{-gnaty}
13894 option will be treated as canceling the indentation check. The same is true
13895 for the @code{M} parameter. @code{y} and @code{N} parameters are not
13896 allowed after @emph{-}.
13897 @end table
13899 @geindex -gnaty+ (gcc)
13902 @table @asis
13904 @item @code{-gnaty+}
13906 @emph{Enable style check options.}
13908 This causes any subsequent options in the string to enable the corresponding
13909 style check option. That is, it cancels the effect of a previous -,
13910 if any.
13911 @end table
13913 @c end of switch description (leave this comment to ease automatic parsing for
13915 @c GPS
13917 In the above rules, appearing in column one is always permitted, that is,
13918 counts as meeting either a requirement for a required preceding space,
13919 or as meeting a requirement for no preceding space.
13921 Appearing at the end of a line is also always permitted, that is, counts
13922 as meeting either a requirement for a following space, or as meeting
13923 a requirement for no following space.
13925 If any of these style rules is violated, a message is generated giving
13926 details on the violation. The initial characters of such messages are
13927 always '@cite{(style)}'. Note that these messages are treated as warning
13928 messages, so they normally do not prevent the generation of an object
13929 file. The @code{-gnatwe} switch can be used to treat warning messages,
13930 including style messages, as fatal errors.
13932 The switch @code{-gnaty} on its own (that is not
13933 followed by any letters or digits) is equivalent
13934 to the use of @code{-gnatyy} as described above, that is all
13935 built-in standard style check options are enabled.
13937 The switch @code{-gnatyN} clears any previously set style checks.
13939 @node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
13940 @anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{f9}@anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{104}
13941 @subsection Run-Time Checks
13944 @geindex Division by zero
13946 @geindex Access before elaboration
13948 @geindex Checks
13949 @geindex division by zero
13951 @geindex Checks
13952 @geindex access before elaboration
13954 @geindex Checks
13955 @geindex stack overflow checking
13957 By default, the following checks are suppressed: stack overflow
13958 checks, and checks for access before elaboration on subprogram
13959 calls. All other checks, including overflow checks, range checks and
13960 array bounds checks, are turned on by default. The following @code{gcc}
13961 switches refine this default behavior.
13963 @geindex -gnatp (gcc)
13966 @table @asis
13968 @item @code{-gnatp}
13970 @geindex Suppressing checks
13972 @geindex Checks
13973 @geindex suppressing
13975 This switch causes the unit to be compiled
13976 as though @code{pragma Suppress (All_checks)}
13977 had been present in the source. Validity checks are also eliminated (in
13978 other words @code{-gnatp} also implies @code{-gnatVn}.
13979 Use this switch to improve the performance
13980 of the code at the expense of safety in the presence of invalid data or
13981 program bugs.
13983 Note that when checks are suppressed, the compiler is allowed, but not
13984 required, to omit the checking code. If the run-time cost of the
13985 checking code is zero or near-zero, the compiler will generate it even
13986 if checks are suppressed. In particular, if the compiler can prove
13987 that a certain check will necessarily fail, it will generate code to
13988 do an unconditional 'raise', even if checks are suppressed. The
13989 compiler warns in this case. Another case in which checks may not be
13990 eliminated is when they are embedded in certain run time routines such
13991 as math library routines.
13993 Of course, run-time checks are omitted whenever the compiler can prove
13994 that they will not fail, whether or not checks are suppressed.
13996 Note that if you suppress a check that would have failed, program
13997 execution is erroneous, which means the behavior is totally
13998 unpredictable. The program might crash, or print wrong answers, or
13999 do anything else. It might even do exactly what you wanted it to do
14000 (and then it might start failing mysteriously next week or next
14001 year). The compiler will generate code based on the assumption that
14002 the condition being checked is true, which can result in erroneous
14003 execution if that assumption is wrong.
14005 The checks subject to suppression include all the checks defined by the Ada
14006 standard, the additional implementation defined checks @code{Alignment_Check},
14007 @code{Duplicated_Tag_Check}, @code{Predicate_Check}, @code{Container_Checks}, @code{Tampering_Check},
14008 and @code{Validity_Check}, as well as any checks introduced using @code{pragma Check_Name}.
14009 Note that @code{Atomic_Synchronization} is not automatically suppressed by use of this option.
14011 If the code depends on certain checks being active, you can use
14012 pragma @code{Unsuppress} either as a configuration pragma or as
14013 a local pragma to make sure that a specified check is performed
14014 even if @code{gnatp} is specified.
14016 The @code{-gnatp} switch has no effect if a subsequent
14017 @code{-gnat-p} switch appears.
14018 @end table
14020 @geindex -gnat-p (gcc)
14022 @geindex Suppressing checks
14024 @geindex Checks
14025 @geindex suppressing
14027 @geindex Suppress
14030 @table @asis
14032 @item @code{-gnat-p}
14034 This switch cancels the effect of a previous @code{gnatp} switch.
14035 @end table
14037 @geindex -gnato?? (gcc)
14039 @geindex Overflow checks
14041 @geindex Overflow mode
14043 @geindex Check
14044 @geindex overflow
14047 @table @asis
14049 @item @code{-gnato??}
14051 This switch controls the mode used for computing intermediate
14052 arithmetic integer operations, and also enables overflow checking.
14053 For a full description of overflow mode and checking control, see
14054 the 'Overflow Check Handling in GNAT' appendix in this
14055 User's Guide.
14057 Overflow checks are always enabled by this switch. The argument
14058 controls the mode, using the codes
14061 @table @asis
14063 @item @emph{1 = STRICT}
14065 In STRICT mode, intermediate operations are always done using the
14066 base type, and overflow checking ensures that the result is within
14067 the base type range.
14069 @item @emph{2 = MINIMIZED}
14071 In MINIMIZED mode, overflows in intermediate operations are avoided
14072 where possible by using a larger integer type for the computation
14073 (typically @code{Long_Long_Integer}). Overflow checking ensures that
14074 the result fits in this larger integer type.
14076 @item @emph{3 = ELIMINATED}
14078 In ELIMINATED mode, overflows in intermediate operations are avoided
14079 by using multi-precision arithmetic. In this case, overflow checking
14080 has no effect on intermediate operations (since overflow is impossible).
14081 @end table
14083 If two digits are present after @code{-gnato} then the first digit
14084 sets the mode for expressions outside assertions, and the second digit
14085 sets the mode for expressions within assertions. Here assertions is used
14086 in the technical sense (which includes for example precondition and
14087 postcondition expressions).
14089 If one digit is present, the corresponding mode is applicable to both
14090 expressions within and outside assertion expressions.
14092 If no digits are present, the default is to enable overflow checks
14093 and set STRICT mode for both kinds of expressions. This is compatible
14094 with the use of @code{-gnato} in previous versions of GNAT.
14096 @geindex Machine_Overflows
14098 Note that the @code{-gnato??} switch does not affect the code generated
14099 for any floating-point operations; it applies only to integer semantics.
14100 For floating-point, GNAT has the @code{Machine_Overflows}
14101 attribute set to @code{False} and the normal mode of operation is to
14102 generate IEEE NaN and infinite values on overflow or invalid operations
14103 (such as dividing 0.0 by 0.0).
14105 The reason that we distinguish overflow checking from other kinds of
14106 range constraint checking is that a failure of an overflow check, unlike
14107 for example the failure of a range check, can result in an incorrect
14108 value, but cannot cause random memory destruction (like an out of range
14109 subscript), or a wild jump (from an out of range case value). Overflow
14110 checking is also quite expensive in time and space, since in general it
14111 requires the use of double length arithmetic.
14113 Note again that the default is @code{-gnato11} (equivalent to @code{-gnato1}),
14114 so overflow checking is performed in STRICT mode by default.
14115 @end table
14117 @geindex -gnatE (gcc)
14119 @geindex Elaboration checks
14121 @geindex Check
14122 @geindex elaboration
14125 @table @asis
14127 @item @code{-gnatE}
14129 Enables dynamic checks for access-before-elaboration
14130 on subprogram calls and generic instantiations.
14131 Note that @code{-gnatE} is not necessary for safety, because in the
14132 default mode, GNAT ensures statically that the checks would not fail.
14133 For full details of the effect and use of this switch,
14134 @ref{1c,,Compiling with gcc}.
14135 @end table
14137 @geindex -fstack-check (gcc)
14139 @geindex Stack Overflow Checking
14141 @geindex Checks
14142 @geindex stack overflow checking
14145 @table @asis
14147 @item @code{-fstack-check}
14149 Activates stack overflow checking. For full details of the effect and use of
14150 this switch see @ref{f4,,Stack Overflow Checking}.
14151 @end table
14153 @geindex Unsuppress
14155 The setting of these switches only controls the default setting of the
14156 checks. You may modify them using either @code{Suppress} (to remove
14157 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
14158 the program source.
14160 @node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
14161 @anchor{gnat_ugn/building_executable_programs_with_gnat id20}@anchor{105}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-syntax-checking}@anchor{106}
14162 @subsection Using @code{gcc} for Syntax Checking
14165 @geindex -gnats (gcc)
14168 @table @asis
14170 @item @code{-gnats}
14172 The @code{s} stands for 'syntax'.
14174 Run GNAT in syntax checking only mode. For
14175 example, the command
14177 @example
14178 $ gcc -c -gnats x.adb
14179 @end example
14181 compiles file @code{x.adb} in syntax-check-only mode. You can check a
14182 series of files in a single command
14183 , and can use wild cards to specify such a group of files.
14184 Note that you must specify the @code{-c} (compile
14185 only) flag in addition to the @code{-gnats} flag.
14187 You may use other switches in conjunction with @code{-gnats}. In
14188 particular, @code{-gnatl} and @code{-gnatv} are useful to control the
14189 format of any generated error messages.
14191 When the source file is empty or contains only empty lines and/or comments,
14192 the output is a warning:
14194 @example
14195 $ gcc -c -gnats -x ada toto.txt
14196 toto.txt:1:01: warning: empty file, contains no compilation units
14198 @end example
14200 Otherwise, the output is simply the error messages, if any. No object file or
14201 ALI file is generated by a syntax-only compilation. Also, no units other
14202 than the one specified are accessed. For example, if a unit @code{X}
14203 @emph{with}s a unit @code{Y}, compiling unit @code{X} in syntax
14204 check only mode does not access the source file containing unit
14205 @code{Y}.
14207 @geindex Multiple units
14208 @geindex syntax checking
14210 Normally, GNAT allows only a single unit in a source file. However, this
14211 restriction does not apply in syntax-check-only mode, and it is possible
14212 to check a file containing multiple compilation units concatenated
14213 together. This is primarily used by the @code{gnatchop} utility
14214 (@ref{36,,Renaming Files with gnatchop}).
14215 @end table
14217 @node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
14218 @anchor{gnat_ugn/building_executable_programs_with_gnat id21}@anchor{107}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-semantic-checking}@anchor{108}
14219 @subsection Using @code{gcc} for Semantic Checking
14222 @geindex -gnatc (gcc)
14225 @table @asis
14227 @item @code{-gnatc}
14229 The @code{c} stands for 'check'.
14230 Causes the compiler to operate in semantic check mode,
14231 with full checking for all illegalities specified in the
14232 Ada Reference Manual, but without generation of any object code
14233 (no object file is generated).
14235 Because dependent files must be accessed, you must follow the GNAT
14236 semantic restrictions on file structuring to operate in this mode:
14239 @itemize *
14241 @item 
14242 The needed source files must be accessible
14243 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
14245 @item 
14246 Each file must contain only one compilation unit.
14248 @item 
14249 The file name and unit name must match (@ref{52,,File Naming Rules}).
14250 @end itemize
14252 The output consists of error messages as appropriate. No object file is
14253 generated. An @code{ALI} file is generated for use in the context of
14254 cross-reference tools, but this file is marked as not being suitable
14255 for binding (since no object file is generated).
14256 The checking corresponds exactly to the notion of
14257 legality in the Ada Reference Manual.
14259 Any unit can be compiled in semantics-checking-only mode, including
14260 units that would not normally be compiled (subunits,
14261 and specifications where a separate body is present).
14262 @end table
14264 @node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
14265 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-different-versions-of-ada}@anchor{6}@anchor{gnat_ugn/building_executable_programs_with_gnat id22}@anchor{109}
14266 @subsection Compiling Different Versions of Ada
14269 The switches described in this section allow you to explicitly specify
14270 the version of the Ada language that your programs are written in.
14271 The default mode is Ada 2012,
14272 but you can also specify Ada 95, Ada 2005 mode, or
14273 indicate Ada 83 compatibility mode.
14275 @geindex Compatibility with Ada 83
14277 @geindex -gnat83 (gcc)
14279 @geindex ACVC
14280 @geindex Ada 83 tests
14282 @geindex Ada 83 mode
14285 @table @asis
14287 @item @code{-gnat83} (Ada 83 Compatibility Mode)
14289 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
14290 specifies that the program is to be compiled in Ada 83 mode. With
14291 @code{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
14292 semantics where this can be done easily.
14293 It is not possible to guarantee this switch does a perfect
14294 job; some subtle tests, such as are
14295 found in earlier ACVC tests (and that have been removed from the ACATS suite
14296 for Ada 95), might not compile correctly.
14297 Nevertheless, this switch may be useful in some circumstances, for example
14298 where, due to contractual reasons, existing code needs to be maintained
14299 using only Ada 83 features.
14301 With few exceptions (most notably the need to use @code{<>} on
14302 unconstrained 
14303 @geindex Generic formal parameters
14304 generic formal parameters,
14305 the use of the new Ada 95 / Ada 2005
14306 reserved words, and the use of packages
14307 with optional bodies), it is not necessary to specify the
14308 @code{-gnat83} switch when compiling Ada 83 programs, because, with rare
14309 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
14310 a correct Ada 83 program is usually also a correct program
14311 in these later versions of the language standard. For further information
14312 please refer to the @emph{Compatibility and Porting Guide} chapter in the
14313 @cite{GNAT Reference Manual}.
14314 @end table
14316 @geindex -gnat95 (gcc)
14318 @geindex Ada 95 mode
14321 @table @asis
14323 @item @code{-gnat95} (Ada 95 mode)
14325 This switch directs the compiler to implement the Ada 95 version of the
14326 language.
14327 Since Ada 95 is almost completely upwards
14328 compatible with Ada 83, Ada 83 programs may generally be compiled using
14329 this switch (see the description of the @code{-gnat83} switch for further
14330 information about Ada 83 mode).
14331 If an Ada 2005 program is compiled in Ada 95 mode,
14332 uses of the new Ada 2005 features will cause error
14333 messages or warnings.
14335 This switch also can be used to cancel the effect of a previous
14336 @code{-gnat83}, @code{-gnat05/2005}, or @code{-gnat12/2012}
14337 switch earlier in the command line.
14338 @end table
14340 @geindex -gnat05 (gcc)
14342 @geindex -gnat2005 (gcc)
14344 @geindex Ada 2005 mode
14347 @table @asis
14349 @item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
14351 This switch directs the compiler to implement the Ada 2005 version of the
14352 language, as documented in the official Ada standards document.
14353 Since Ada 2005 is almost completely upwards
14354 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
14355 may generally be compiled using this switch (see the description of the
14356 @code{-gnat83} and @code{-gnat95} switches for further
14357 information).
14358 @end table
14360 @geindex -gnat12 (gcc)
14362 @geindex -gnat2012 (gcc)
14364 @geindex Ada 2012 mode
14367 @table @asis
14369 @item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
14371 This switch directs the compiler to implement the Ada 2012 version of the
14372 language (also the default).
14373 Since Ada 2012 is almost completely upwards
14374 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
14375 Ada 83 and Ada 95 programs
14376 may generally be compiled using this switch (see the description of the
14377 @code{-gnat83}, @code{-gnat95}, and @code{-gnat05/2005} switches
14378 for further information).
14379 @end table
14381 @geindex -gnatX (gcc)
14383 @geindex Ada language extensions
14385 @geindex GNAT extensions
14388 @table @asis
14390 @item @code{-gnatX} (Enable GNAT Extensions)
14392 This switch directs the compiler to implement the latest version of the
14393 language (currently Ada 2012) and also to enable certain GNAT implementation
14394 extensions that are not part of any Ada standard. For a full list of these
14395 extensions, see the GNAT reference manual.
14396 @end table
14398 @node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14399 @anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{10a}@anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{48}
14400 @subsection Character Set Control
14403 @geindex -gnati (gcc)
14406 @table @asis
14408 @item @code{-gnati@emph{c}}
14410 Normally GNAT recognizes the Latin-1 character set in source program
14411 identifiers, as described in the Ada Reference Manual.
14412 This switch causes
14413 GNAT to recognize alternate character sets in identifiers. @code{c} is a
14414 single character  indicating the character set, as follows:
14417 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14418 @item
14420 @emph{1}
14422 @tab
14424 ISO 8859-1 (Latin-1) identifiers
14426 @item
14428 @emph{2}
14430 @tab
14432 ISO 8859-2 (Latin-2) letters allowed in identifiers
14434 @item
14436 @emph{3}
14438 @tab
14440 ISO 8859-3 (Latin-3) letters allowed in identifiers
14442 @item
14444 @emph{4}
14446 @tab
14448 ISO 8859-4 (Latin-4) letters allowed in identifiers
14450 @item
14452 @emph{5}
14454 @tab
14456 ISO 8859-5 (Cyrillic) letters allowed in identifiers
14458 @item
14460 @emph{9}
14462 @tab
14464 ISO 8859-15 (Latin-9) letters allowed in identifiers
14466 @item
14468 @emph{p}
14470 @tab
14472 IBM PC letters (code page 437) allowed in identifiers
14474 @item
14476 @emph{8}
14478 @tab
14480 IBM PC letters (code page 850) allowed in identifiers
14482 @item
14484 @emph{f}
14486 @tab
14488 Full upper-half codes allowed in identifiers
14490 @item
14492 @emph{n}
14494 @tab
14496 No upper-half codes allowed in identifiers
14498 @item
14500 @emph{w}
14502 @tab
14504 Wide-character codes (that is, codes greater than 255)
14505 allowed in identifiers
14507 @end multitable
14510 See @ref{3e,,Foreign Language Representation} for full details on the
14511 implementation of these character sets.
14512 @end table
14514 @geindex -gnatW (gcc)
14517 @table @asis
14519 @item @code{-gnatW@emph{e}}
14521 Specify the method of encoding for wide characters.
14522 @code{e} is one of the following:
14525 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14526 @item
14528 @emph{h}
14530 @tab
14532 Hex encoding (brackets coding also recognized)
14534 @item
14536 @emph{u}
14538 @tab
14540 Upper half encoding (brackets encoding also recognized)
14542 @item
14544 @emph{s}
14546 @tab
14548 Shift/JIS encoding (brackets encoding also recognized)
14550 @item
14552 @emph{e}
14554 @tab
14556 EUC encoding (brackets encoding also recognized)
14558 @item
14560 @emph{8}
14562 @tab
14564 UTF-8 encoding (brackets encoding also recognized)
14566 @item
14568 @emph{b}
14570 @tab
14572 Brackets encoding only (default value)
14574 @end multitable
14577 For full details on these encoding
14578 methods see @ref{4e,,Wide_Character Encodings}.
14579 Note that brackets coding is always accepted, even if one of the other
14580 options is specified, so for example @code{-gnatW8} specifies that both
14581 brackets and UTF-8 encodings will be recognized. The units that are
14582 with'ed directly or indirectly will be scanned using the specified
14583 representation scheme, and so if one of the non-brackets scheme is
14584 used, it must be used consistently throughout the program. However,
14585 since brackets encoding is always recognized, it may be conveniently
14586 used in standard libraries, allowing these libraries to be used with
14587 any of the available coding schemes.
14589 Note that brackets encoding only applies to program text. Within comments,
14590 brackets are considered to be normal graphic characters, and bracket sequences
14591 are never recognized as wide characters.
14593 If no @code{-gnatW?} parameter is present, then the default
14594 representation is normally Brackets encoding only. However, if the
14595 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14596 byte order mark or BOM for UTF-8), then these three characters are
14597 skipped and the default representation for the file is set to UTF-8.
14599 Note that the wide character representation that is specified (explicitly
14600 or by default) for the main program also acts as the default encoding used
14601 for Wide_Text_IO files if not specifically overridden by a WCEM form
14602 parameter.
14603 @end table
14605 When no @code{-gnatW?} is specified, then characters (other than wide
14606 characters represented using brackets notation) are treated as 8-bit
14607 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14608 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14609 characters in the range 16#00#..16#1F# are not accepted in program text
14610 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14611 in program text, but allowed and ignored in comments. Note in particular
14612 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14613 as an end of line in this default mode. If your source program contains
14614 instances of the NEL character used as a line terminator,
14615 you must use UTF-8 encoding for the whole
14616 source program. In default mode, all lines must be ended by a standard
14617 end of line sequence (CR, CR/LF, or LF).
14619 Note that the convention of simply accepting all upper half characters in
14620 comments means that programs that use standard ASCII for program text, but
14621 UTF-8 encoding for comments are accepted in default mode, providing that the
14622 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14623 This is a common mode for many programs with foreign language comments.
14625 @node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14626 @anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{10b}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{10c}
14627 @subsection File Naming Control
14630 @geindex -gnatk (gcc)
14633 @table @asis
14635 @item @code{-gnatk@emph{n}}
14637 Activates file name 'krunching'. @code{n}, a decimal integer in the range
14638 1-999, indicates the maximum allowable length of a file name (not
14639 including the @code{.ads} or @code{.adb} extension). The default is not
14640 to enable file name krunching.
14642 For the source file naming rules, @ref{52,,File Naming Rules}.
14643 @end table
14645 @node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14646 @anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{10d}@anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{10e}
14647 @subsection Subprogram Inlining Control
14650 @geindex -gnatn (gcc)
14653 @table @asis
14655 @item @code{-gnatn[12]}
14657 The @code{n} here is intended to suggest the first syllable of the word 'inline'.
14658 GNAT recognizes and processes @code{Inline} pragmas. However, for inlining to
14659 actually occur, optimization must be enabled and, by default, inlining of
14660 subprograms across modules is not performed. If you want to additionally
14661 enable inlining of subprograms specified by pragma @code{Inline} across modules,
14662 you must also specify this switch.
14664 In the absence of this switch, GNAT does not attempt inlining across modules
14665 and does not access the bodies of subprograms for which @code{pragma Inline} is
14666 specified if they are not in the current unit.
14668 You can optionally specify the inlining level: 1 for moderate inlining across
14669 modules, which is a good compromise between compilation times and performances
14670 at run time, or 2 for full inlining across modules, which may bring about
14671 longer compilation times. If no inlining level is specified, the compiler will
14672 pick it based on the optimization level: 1 for @code{-O1}, @code{-O2} or
14673 @code{-Os} and 2 for @code{-O3}.
14675 If you specify this switch the compiler will access these bodies,
14676 creating an extra source dependency for the resulting object file, and
14677 where possible, the call will be inlined.
14678 For further details on when inlining is possible
14679 see @ref{10f,,Inlining of Subprograms}.
14680 @end table
14682 @geindex -gnatN (gcc)
14685 @table @asis
14687 @item @code{-gnatN}
14689 This switch activates front-end inlining which also
14690 generates additional dependencies.
14692 When using a gcc-based back end (in practice this means using any version
14693 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
14694 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
14695 Historically front end inlining was more extensive than the gcc back end
14696 inlining, but that is no longer the case.
14697 @end table
14699 @node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14700 @anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{110}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{111}
14701 @subsection Auxiliary Output Control
14704 @geindex -gnatt (gcc)
14706 @geindex Writing internal trees
14708 @geindex Internal trees
14709 @geindex writing to file
14712 @table @asis
14714 @item @code{-gnatt}
14716 Causes GNAT to write the internal tree for a unit to a file (with the
14717 extension @code{.adt}.
14718 This not normally required, but is used by separate analysis tools.
14719 Typically
14720 these tools do the necessary compilations automatically, so you should
14721 not have to specify this switch in normal operation.
14722 Note that the combination of switches @code{-gnatct}
14723 generates a tree in the form required by ASIS applications.
14724 @end table
14726 @geindex -gnatu (gcc)
14729 @table @asis
14731 @item @code{-gnatu}
14733 Print a list of units required by this compilation on @code{stdout}.
14734 The listing includes all units on which the unit being compiled depends
14735 either directly or indirectly.
14736 @end table
14738 @geindex -pass-exit-codes (gcc)
14741 @table @asis
14743 @item @code{-pass-exit-codes}
14745 If this switch is not used, the exit code returned by @code{gcc} when
14746 compiling multiple files indicates whether all source files have
14747 been successfully used to generate object files or not.
14749 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
14750 exit status and allows an integrated development environment to better
14751 react to a compilation failure. Those exit status are:
14754 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14755 @item
14757 @emph{5}
14759 @tab
14761 There was an error in at least one source file.
14763 @item
14765 @emph{3}
14767 @tab
14769 At least one source file did not generate an object file.
14771 @item
14773 @emph{2}
14775 @tab
14777 The compiler died unexpectedly (internal error for example).
14779 @item
14781 @emph{0}
14783 @tab
14785 An object file has been generated for every source file.
14787 @end multitable
14789 @end table
14791 @node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
14792 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{112}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{113}
14793 @subsection Debugging Control
14796 @quotation
14798 @geindex Debugging options
14799 @end quotation
14801 @geindex -gnatd (gcc)
14804 @table @asis
14806 @item @code{-gnatd@emph{x}}
14808 Activate internal debugging switches. @code{x} is a letter or digit, or
14809 string of letters or digits, which specifies the type of debugging
14810 outputs desired. Normally these are used only for internal development
14811 or system debugging purposes. You can find full documentation for these
14812 switches in the body of the @code{Debug} unit in the compiler source
14813 file @code{debug.adb}.
14814 @end table
14816 @geindex -gnatG (gcc)
14819 @table @asis
14821 @item @code{-gnatG[=@emph{nn}]}
14823 This switch causes the compiler to generate auxiliary output containing
14824 a pseudo-source listing of the generated expanded code. Like most Ada
14825 compilers, GNAT works by first transforming the high level Ada code into
14826 lower level constructs. For example, tasking operations are transformed
14827 into calls to the tasking run-time routines. A unique capability of GNAT
14828 is to list this expanded code in a form very close to normal Ada source.
14829 This is very useful in understanding the implications of various Ada
14830 usage on the efficiency of the generated code. There are many cases in
14831 Ada (e.g., the use of controlled types), where simple Ada statements can
14832 generate a lot of run-time code. By using @code{-gnatG} you can identify
14833 these cases, and consider whether it may be desirable to modify the coding
14834 approach to improve efficiency.
14836 The optional parameter @code{nn} if present after -gnatG specifies an
14837 alternative maximum line length that overrides the normal default of 72.
14838 This value is in the range 40-999999, values less than 40 being silently
14839 reset to 40. The equal sign is optional.
14841 The format of the output is very similar to standard Ada source, and is
14842 easily understood by an Ada programmer. The following special syntactic
14843 additions correspond to low level features used in the generated code that
14844 do not have any exact analogies in pure Ada source form. The following
14845 is a partial list of these special constructions. See the spec
14846 of package @code{Sprint} in file @code{sprint.ads} for a full list.
14848 @geindex -gnatL (gcc)
14850 If the switch @code{-gnatL} is used in conjunction with
14851 @code{-gnatG}, then the original source lines are interspersed
14852 in the expanded source (as comment lines with the original line number).
14855 @table @asis
14857 @item @code{new @emph{xxx} [storage_pool = @emph{yyy}]}
14859 Shows the storage pool being used for an allocator.
14861 @item @code{at end @emph{procedure-name};}
14863 Shows the finalization (cleanup) procedure for a scope.
14865 @item @code{(if @emph{expr} then @emph{expr} else @emph{expr})}
14867 Conditional expression equivalent to the @code{x?y:z} construction in C.
14869 @item @code{@emph{target}^(@emph{source})}
14871 A conversion with floating-point truncation instead of rounding.
14873 @item @code{@emph{target}?(@emph{source})}
14875 A conversion that bypasses normal Ada semantic checking. In particular
14876 enumeration types and fixed-point types are treated simply as integers.
14878 @item @code{@emph{target}?^(@emph{source})}
14880 Combines the above two cases.
14881 @end table
14883 @code{@emph{x} #/ @emph{y}}
14885 @code{@emph{x} #mod @emph{y}}
14887 @code{@emph{x} # @emph{y}}
14890 @table @asis
14892 @item @code{@emph{x} #rem @emph{y}}
14894 A division or multiplication of fixed-point values which are treated as
14895 integers without any kind of scaling.
14897 @item @code{free @emph{expr} [storage_pool = @emph{xxx}]}
14899 Shows the storage pool associated with a @code{free} statement.
14901 @item @code{[subtype or type declaration]}
14903 Used to list an equivalent declaration for an internally generated
14904 type that is referenced elsewhere in the listing.
14906 @item @code{freeze @emph{type-name} [@emph{actions}]}
14908 Shows the point at which @code{type-name} is frozen, with possible
14909 associated actions to be performed at the freeze point.
14911 @item @code{reference @emph{itype}}
14913 Reference (and hence definition) to internal type @code{itype}.
14915 @item @code{@emph{function-name}! (@emph{arg}, @emph{arg}, @emph{arg})}
14917 Intrinsic function call.
14919 @item @code{@emph{label-name} : label}
14921 Declaration of label @code{labelname}.
14923 @item @code{#$ @emph{subprogram-name}}
14925 An implicit call to a run-time support routine
14926 (to meet the requirement of H.3.1(9) in a
14927 convenient manner).
14929 @item @code{@emph{expr} && @emph{expr} && @emph{expr} ... && @emph{expr}}
14931 A multiple concatenation (same effect as @code{expr} & @code{expr} &
14932 @code{expr}, but handled more efficiently).
14934 @item @code{[constraint_error]}
14936 Raise the @code{Constraint_Error} exception.
14938 @item @code{@emph{expression}'reference}
14940 A pointer to the result of evaluating @{expression@}.
14942 @item @code{@emph{target-type}!(@emph{source-expression})}
14944 An unchecked conversion of @code{source-expression} to @code{target-type}.
14946 @item @code{[@emph{numerator}/@emph{denominator}]}
14948 Used to represent internal real literals (that) have no exact
14949 representation in base 2-16 (for example, the result of compile time
14950 evaluation of the expression 1.0/27.0).
14951 @end table
14952 @end table
14954 @geindex -gnatD (gcc)
14957 @table @asis
14959 @item @code{-gnatD[=nn]}
14961 When used in conjunction with @code{-gnatG}, this switch causes
14962 the expanded source, as described above for
14963 @code{-gnatG} to be written to files with names
14964 @code{xxx.dg}, where @code{xxx} is the normal file name,
14965 instead of to the standard output file. For
14966 example, if the source file name is @code{hello.adb}, then a file
14967 @code{hello.adb.dg} will be written.  The debugging
14968 information generated by the @code{gcc} @code{-g} switch
14969 will refer to the generated @code{xxx.dg} file. This allows
14970 you to do source level debugging using the generated code which is
14971 sometimes useful for complex code, for example to find out exactly
14972 which part of a complex construction raised an exception. This switch
14973 also suppresses generation of cross-reference information (see
14974 @code{-gnatx}) since otherwise the cross-reference information
14975 would refer to the @code{.dg} file, which would cause
14976 confusion since this is not the original source file.
14978 Note that @code{-gnatD} actually implies @code{-gnatG}
14979 automatically, so it is not necessary to give both options.
14980 In other words @code{-gnatD} is equivalent to @code{-gnatDG}).
14982 @geindex -gnatL (gcc)
14984 If the switch @code{-gnatL} is used in conjunction with
14985 @code{-gnatDG}, then the original source lines are interspersed
14986 in the expanded source (as comment lines with the original line number).
14988 The optional parameter @code{nn} if present after -gnatD specifies an
14989 alternative maximum line length that overrides the normal default of 72.
14990 This value is in the range 40-999999, values less than 40 being silently
14991 reset to 40. The equal sign is optional.
14992 @end table
14994 @geindex -gnatr (gcc)
14996 @geindex pragma Restrictions
14999 @table @asis
15001 @item @code{-gnatr}
15003 This switch causes pragma Restrictions to be treated as Restriction_Warnings
15004 so that violation of restrictions causes warnings rather than illegalities.
15005 This is useful during the development process when new restrictions are added
15006 or investigated. The switch also causes pragma Profile to be treated as
15007 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
15008 restriction warnings rather than restrictions.
15009 @end table
15011 @geindex -gnatR (gcc)
15014 @table @asis
15016 @item @code{-gnatR[0|1|2|3][e][m][s]}
15018 This switch controls output from the compiler of a listing showing
15019 representation information for declared types, objects and subprograms.
15020 For @code{-gnatR0}, no information is output (equivalent to omitting
15021 the @code{-gnatR} switch). For @code{-gnatR1} (which is the default,
15022 so @code{-gnatR} with no parameter has the same effect), size and
15023 alignment information is listed for declared array and record types.
15024 For @code{-gnatR2}, size and alignment information is listed for all
15025 declared types and objects. The @code{Linker_Section} is also listed for any
15026 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
15027 latter case occurs for objects of a type for which a @code{Linker_Section}
15028 is set).
15030 For @code{-gnatR3}, symbolic expressions for values that are computed
15031 at run time for records are included. These symbolic expressions have
15032 a mostly obvious format with #n being used to represent the value of the
15033 n'th discriminant. See source files @code{repinfo.ads/adb} in the
15034 GNAT sources for full details on the format of @code{-gnatR3} output.
15036 If the switch is followed by an @code{e} (e.g. @code{-gnatR2e}), then
15037 extended representation information for record sub-components of records
15038 are included.
15040 If the switch is followed by an @code{m} (e.g. @code{-gnatRm}), then
15041 subprogram conventions and parameter passing mechanisms for all the
15042 subprograms are included.
15044 If the switch is followed by an @code{s} (e.g., @code{-gnatR3s}), then
15045 the output is to a file with the name @code{file.rep} where file is
15046 the name of the corresponding source file.
15048 Note that it is possible for record components to have zero size. In
15049 this case, the component clause uses an obvious extension of permitted
15050 Ada syntax, for example @code{at 0 range 0 .. -1}.
15051 @end table
15053 @geindex -gnatS (gcc)
15056 @table @asis
15058 @item @code{-gnatS}
15060 The use of the switch @code{-gnatS} for an
15061 Ada compilation will cause the compiler to output a
15062 representation of package Standard in a form very
15063 close to standard Ada. It is not quite possible to
15064 do this entirely in standard Ada (since new
15065 numeric base types cannot be created in standard
15066 Ada), but the output is easily
15067 readable to any Ada programmer, and is useful to
15068 determine the characteristics of target dependent
15069 types in package Standard.
15070 @end table
15072 @geindex -gnatx (gcc)
15075 @table @asis
15077 @item @code{-gnatx}
15079 Normally the compiler generates full cross-referencing information in
15080 the @code{ALI} file. This information is used by a number of tools,
15081 including @code{gnatfind} and @code{gnatxref}. The @code{-gnatx} switch
15082 suppresses this information. This saves some space and may slightly
15083 speed up compilation, but means that these tools cannot be used.
15084 @end table
15086 @node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
15087 @anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{114}@anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{115}
15088 @subsection Exception Handling Control
15091 GNAT uses two methods for handling exceptions at run-time. The
15092 @code{setjmp/longjmp} method saves the context when entering
15093 a frame with an exception handler. Then when an exception is
15094 raised, the context can be restored immediately, without the
15095 need for tracing stack frames. This method provides very fast
15096 exception propagation, but introduces significant overhead for
15097 the use of exception handlers, even if no exception is raised.
15099 The other approach is called 'zero cost' exception handling.
15100 With this method, the compiler builds static tables to describe
15101 the exception ranges. No dynamic code is required when entering
15102 a frame containing an exception handler. When an exception is
15103 raised, the tables are used to control a back trace of the
15104 subprogram invocation stack to locate the required exception
15105 handler. This method has considerably poorer performance for
15106 the propagation of exceptions, but there is no overhead for
15107 exception handlers if no exception is raised. Note that in this
15108 mode and in the context of mixed Ada and C/C++ programming,
15109 to propagate an exception through a C/C++ code, the C/C++ code
15110 must be compiled with the @code{-funwind-tables} GCC's
15111 option.
15113 The following switches may be used to control which of the
15114 two exception handling methods is used.
15116 @geindex --RTS=sjlj (gnatmake)
15119 @table @asis
15121 @item @code{--RTS=sjlj}
15123 This switch causes the setjmp/longjmp run-time (when available) to be used
15124 for exception handling. If the default
15125 mechanism for the target is zero cost exceptions, then
15126 this switch can be used to modify this default, and must be
15127 used for all units in the partition.
15128 This option is rarely used. One case in which it may be
15129 advantageous is if you have an application where exception
15130 raising is common and the overall performance of the
15131 application is improved by favoring exception propagation.
15132 @end table
15134 @geindex --RTS=zcx (gnatmake)
15136 @geindex Zero Cost Exceptions
15139 @table @asis
15141 @item @code{--RTS=zcx}
15143 This switch causes the zero cost approach to be used
15144 for exception handling. If this is the default mechanism for the
15145 target (see below), then this switch is unneeded. If the default
15146 mechanism for the target is setjmp/longjmp exceptions, then
15147 this switch can be used to modify this default, and must be
15148 used for all units in the partition.
15149 This option can only be used if the zero cost approach
15150 is available for the target in use, otherwise it will generate an error.
15151 @end table
15153 The same option @code{--RTS} must be used both for @code{gcc}
15154 and @code{gnatbind}. Passing this option to @code{gnatmake}
15155 (@ref{dc,,Switches for gnatmake}) will ensure the required consistency
15156 through the compilation and binding steps.
15158 @node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
15159 @anchor{gnat_ugn/building_executable_programs_with_gnat id29}@anchor{116}@anchor{gnat_ugn/building_executable_programs_with_gnat units-to-sources-mapping-files}@anchor{f7}
15160 @subsection Units to Sources Mapping Files
15163 @geindex -gnatem (gcc)
15166 @table @asis
15168 @item @code{-gnatem=@emph{path}}
15170 A mapping file is a way to communicate to the compiler two mappings:
15171 from unit names to file names (without any directory information) and from
15172 file names to path names (with full directory information). These mappings
15173 are used by the compiler to short-circuit the path search.
15175 The use of mapping files is not required for correct operation of the
15176 compiler, but mapping files can improve efficiency, particularly when
15177 sources are read over a slow network connection. In normal operation,
15178 you need not be concerned with the format or use of mapping files,
15179 and the @code{-gnatem} switch is not a switch that you would use
15180 explicitly. It is intended primarily for use by automatic tools such as
15181 @code{gnatmake} running under the project file facility. The
15182 description here of the format of mapping files is provided
15183 for completeness and for possible use by other tools.
15185 A mapping file is a sequence of sets of three lines. In each set, the
15186 first line is the unit name, in lower case, with @code{%s} appended
15187 for specs and @code{%b} appended for bodies; the second line is the
15188 file name; and the third line is the path name.
15190 Example:
15192 @example
15193 main%b
15194 main.2.ada
15195 /gnat/project1/sources/main.2.ada
15196 @end example
15198 When the switch @code{-gnatem} is specified, the compiler will
15199 create in memory the two mappings from the specified file. If there is
15200 any problem (nonexistent file, truncated file or duplicate entries),
15201 no mapping will be created.
15203 Several @code{-gnatem} switches may be specified; however, only the
15204 last one on the command line will be taken into account.
15206 When using a project file, @code{gnatmake} creates a temporary
15207 mapping file and communicates it to the compiler using this switch.
15208 @end table
15210 @node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
15211 @anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{117}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{118}
15212 @subsection Code Generation Control
15215 The GCC technology provides a wide range of target dependent
15216 @code{-m} switches for controlling
15217 details of code generation with respect to different versions of
15218 architectures. This includes variations in instruction sets (e.g.,
15219 different members of the power pc family), and different requirements
15220 for optimal arrangement of instructions (e.g., different members of
15221 the x86 family). The list of available @code{-m} switches may be
15222 found in the GCC documentation.
15224 Use of these @code{-m} switches may in some cases result in improved
15225 code performance.
15227 The GNAT technology is tested and qualified without any
15228 @code{-m} switches,
15229 so generally the most reliable approach is to avoid the use of these
15230 switches. However, we generally expect most of these switches to work
15231 successfully with GNAT, and many customers have reported successful
15232 use of these options.
15234 Our general advice is to avoid the use of @code{-m} switches unless
15235 special needs lead to requirements in this area. In particular,
15236 there is no point in using @code{-m} switches to improve performance
15237 unless you actually see a performance improvement.
15239 @node Linker Switches,Binding with gnatbind,Compiler Switches,Building Executable Programs with GNAT
15240 @anchor{gnat_ugn/building_executable_programs_with_gnat linker-switches}@anchor{119}@anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{11a}
15241 @section Linker Switches
15244 Linker switches can be specified after @code{-largs} builder switch.
15246 @geindex -fuse-ld=name
15249 @table @asis
15251 @item @code{-fuse-ld=@emph{name}}
15253 Linker to be used. The default is @code{bfd} for @code{ld.bfd},
15254 the alternative being @code{gold} for @code{ld.gold}. The later is
15255 a more recent and faster linker, but only available on GNU/Linux
15256 platforms.
15257 @end table
15259 @node Binding with gnatbind,Linking with gnatlink,Linker Switches,Building Executable Programs with GNAT
15260 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{1d}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{11b}
15261 @section Binding with @code{gnatbind}
15264 @geindex gnatbind
15266 This chapter describes the GNAT binder, @code{gnatbind}, which is used
15267 to bind compiled GNAT objects.
15269 The @code{gnatbind} program performs four separate functions:
15272 @itemize *
15274 @item 
15275 Checks that a program is consistent, in accordance with the rules in
15276 Chapter 10 of the Ada Reference Manual. In particular, error
15277 messages are generated if a program uses inconsistent versions of a
15278 given unit.
15280 @item 
15281 Checks that an acceptable order of elaboration exists for the program
15282 and issues an error message if it cannot find an order of elaboration
15283 that satisfies the rules in Chapter 10 of the Ada Language Manual.
15285 @item 
15286 Generates a main program incorporating the given elaboration order.
15287 This program is a small Ada package (body and spec) that
15288 must be subsequently compiled
15289 using the GNAT compiler. The necessary compilation step is usually
15290 performed automatically by @code{gnatlink}. The two most important
15291 functions of this program
15292 are to call the elaboration routines of units in an appropriate order
15293 and to call the main program.
15295 @item 
15296 Determines the set of object files required by the given main program.
15297 This information is output in the forms of comments in the generated program,
15298 to be read by the @code{gnatlink} utility used to link the Ada application.
15299 @end itemize
15301 @menu
15302 * Running gnatbind:: 
15303 * Switches for gnatbind:: 
15304 * Command-Line Access:: 
15305 * Search Paths for gnatbind:: 
15306 * Examples of gnatbind Usage:: 
15308 @end menu
15310 @node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
15311 @anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{11c}@anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{11d}
15312 @subsection Running @code{gnatbind}
15315 The form of the @code{gnatbind} command is
15317 @example
15318 $ gnatbind [ switches ] mainprog[.ali] [ switches ]
15319 @end example
15321 where @code{mainprog.adb} is the Ada file containing the main program
15322 unit body. @code{gnatbind} constructs an Ada
15323 package in two files whose names are
15324 @code{b~mainprog.ads}, and @code{b~mainprog.adb}.
15325 For example, if given the
15326 parameter @code{hello.ali}, for a main program contained in file
15327 @code{hello.adb}, the binder output files would be @code{b~hello.ads}
15328 and @code{b~hello.adb}.
15330 When doing consistency checking, the binder takes into consideration
15331 any source files it can locate. For example, if the binder determines
15332 that the given main program requires the package @code{Pack}, whose
15333 @code{.ALI}
15334 file is @code{pack.ali} and whose corresponding source spec file is
15335 @code{pack.ads}, it attempts to locate the source file @code{pack.ads}
15336 (using the same search path conventions as previously described for the
15337 @code{gcc} command). If it can locate this source file, it checks that
15338 the time stamps
15339 or source checksums of the source and its references to in @code{ALI} files
15340 match. In other words, any @code{ALI} files that mentions this spec must have
15341 resulted from compiling this version of the source file (or in the case
15342 where the source checksums match, a version close enough that the
15343 difference does not matter).
15345 @geindex Source files
15346 @geindex use by binder
15348 The effect of this consistency checking, which includes source files, is
15349 that the binder ensures that the program is consistent with the latest
15350 version of the source files that can be located at bind time. Editing a
15351 source file without compiling files that depend on the source file cause
15352 error messages to be generated by the binder.
15354 For example, suppose you have a main program @code{hello.adb} and a
15355 package @code{P}, from file @code{p.ads} and you perform the following
15356 steps:
15359 @itemize *
15361 @item 
15362 Enter @code{gcc -c hello.adb} to compile the main program.
15364 @item 
15365 Enter @code{gcc -c p.ads} to compile package @code{P}.
15367 @item 
15368 Edit file @code{p.ads}.
15370 @item 
15371 Enter @code{gnatbind hello}.
15372 @end itemize
15374 At this point, the file @code{p.ali} contains an out-of-date time stamp
15375 because the file @code{p.ads} has been edited. The attempt at binding
15376 fails, and the binder generates the following error messages:
15378 @example
15379 error: "hello.adb" must be recompiled ("p.ads" has been modified)
15380 error: "p.ads" has been modified and must be recompiled
15381 @end example
15383 Now both files must be recompiled as indicated, and then the bind can
15384 succeed, generating a main program. You need not normally be concerned
15385 with the contents of this file, but for reference purposes a sample
15386 binder output file is given in @ref{e,,Example of Binder Output File}.
15388 In most normal usage, the default mode of @code{gnatbind} which is to
15389 generate the main package in Ada, as described in the previous section.
15390 In particular, this means that any Ada programmer can read and understand
15391 the generated main program. It can also be debugged just like any other
15392 Ada code provided the @code{-g} switch is used for
15393 @code{gnatbind} and @code{gnatlink}.
15395 @node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
15396 @anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{11e}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{11f}
15397 @subsection Switches for @code{gnatbind}
15400 The following switches are available with @code{gnatbind}; details will
15401 be presented in subsequent sections.
15403 @geindex --version (gnatbind)
15406 @table @asis
15408 @item @code{--version}
15410 Display Copyright and version, then exit disregarding all other options.
15411 @end table
15413 @geindex --help (gnatbind)
15416 @table @asis
15418 @item @code{--help}
15420 If @code{--version} was not used, display usage, then exit disregarding
15421 all other options.
15422 @end table
15424 @geindex -a (gnatbind)
15427 @table @asis
15429 @item @code{-a}
15431 Indicates that, if supported by the platform, the adainit procedure should
15432 be treated as an initialisation routine by the linker (a constructor). This
15433 is intended to be used by the Project Manager to automatically initialize
15434 shared Stand-Alone Libraries.
15435 @end table
15437 @geindex -aO (gnatbind)
15440 @table @asis
15442 @item @code{-aO}
15444 Specify directory to be searched for ALI files.
15445 @end table
15447 @geindex -aI (gnatbind)
15450 @table @asis
15452 @item @code{-aI}
15454 Specify directory to be searched for source file.
15455 @end table
15457 @geindex -A (gnatbind)
15460 @table @asis
15462 @item @code{-A[=@emph{filename}]}
15464 Output ALI list (to standard output or to the named file).
15465 @end table
15467 @geindex -b (gnatbind)
15470 @table @asis
15472 @item @code{-b}
15474 Generate brief messages to @code{stderr} even if verbose mode set.
15475 @end table
15477 @geindex -c (gnatbind)
15480 @table @asis
15482 @item @code{-c}
15484 Check only, no generation of binder output file.
15485 @end table
15487 @geindex -dnn[k|m] (gnatbind)
15490 @table @asis
15492 @item @code{-d@emph{nn}[k|m]}
15494 This switch can be used to change the default task stack size value
15495 to a specified size @code{nn}, which is expressed in bytes by default, or
15496 in kilobytes when suffixed with @code{k} or in megabytes when suffixed
15497 with @code{m}.
15498 In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15499 in effect, to completing all task specs with
15501 @example
15502 pragma Storage_Size (nn);
15503 @end example
15505 When they do not already have such a pragma.
15506 @end table
15508 @geindex -D (gnatbind)
15511 @table @asis
15513 @item @code{-D@emph{nn}[k|m]}
15515 This switch can be used to change the default secondary stack size value
15516 to a specified size @code{nn}, which is expressed in bytes by default, or
15517 in kilobytes when suffixed with @code{k} or in megabytes when suffixed
15518 with @code{m}.
15520 The secondary stack is used to deal with functions that return a variable
15521 sized result, for example a function returning an unconstrained
15522 String. There are two ways in which this secondary stack is allocated.
15524 For most targets, the secondary stack grows on demand and is allocated
15525 as a chain of blocks in the heap. The -D option is not very
15526 relevant. It only give some control over the size of the allocated
15527 blocks (whose size is the minimum of the default secondary stack size value,
15528 and the actual size needed for the current allocation request).
15530 For certain targets, notably VxWorks 653 and bare board targets,
15531 the secondary stack is allocated by carving off a chunk of the primary task
15532 stack. By default this is a fixed percentage of the primary task stack as
15533 defined by System.Parameter.Sec_Stack_Percentage. This can be overridden per
15534 task using the Secondary_Stack_Size pragma/aspect. The -D option is used to
15535 define the size of the environment task's secondary stack.
15536 @end table
15538 @geindex -e (gnatbind)
15541 @table @asis
15543 @item @code{-e}
15545 Output complete list of elaboration-order dependencies.
15546 @end table
15548 @geindex -Ea (gnatbind)
15551 @table @asis
15553 @item @code{-Ea}
15555 Store tracebacks in exception occurrences when the target supports it.
15556 The "a" is for "address"; tracebacks will contain hexadecimal addresses,
15557 unless symbolic tracebacks are enabled.
15559 See also the packages @code{GNAT.Traceback} and
15560 @code{GNAT.Traceback.Symbolic} for more information.
15561 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
15562 @code{gcc} option.
15563 @end table
15565 @geindex -Es (gnatbind)
15568 @table @asis
15570 @item @code{-Es}
15572 Store tracebacks in exception occurrences when the target supports it.
15573 The "s" is for "symbolic"; symbolic tracebacks are enabled.
15574 @end table
15576 @geindex -E (gnatbind)
15579 @table @asis
15581 @item @code{-E}
15583 Currently the same as @code{-Ea}.
15584 @end table
15586 @geindex -f (gnatbind)
15589 @table @asis
15591 @item @code{-f@emph{elab-order}}
15593 Force elaboration order.
15594 @end table
15596 @geindex -F (gnatbind)
15599 @table @asis
15601 @item @code{-F}
15603 Force the checks of elaboration flags. @code{gnatbind} does not normally
15604 generate checks of elaboration flags for the main executable, except when
15605 a Stand-Alone Library is used. However, there are cases when this cannot be
15606 detected by gnatbind. An example is importing an interface of a Stand-Alone
15607 Library through a pragma Import and only specifying through a linker switch
15608 this Stand-Alone Library. This switch is used to guarantee that elaboration
15609 flag checks are generated.
15610 @end table
15612 @geindex -h (gnatbind)
15615 @table @asis
15617 @item @code{-h}
15619 Output usage (help) information.
15621 @geindex -H32 (gnatbind)
15623 @item @code{-H32}
15625 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
15626 For further details see @ref{120,,Dynamic Allocation Control}.
15628 @geindex -H64 (gnatbind)
15630 @geindex __gnat_malloc
15632 @item @code{-H64}
15634 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
15635 For further details see @ref{120,,Dynamic Allocation Control}.
15637 @geindex -I (gnatbind)
15639 @item @code{-I}
15641 Specify directory to be searched for source and ALI files.
15643 @geindex -I- (gnatbind)
15645 @item @code{-I-}
15647 Do not look for sources in the current directory where @code{gnatbind} was
15648 invoked, and do not look for ALI files in the directory containing the
15649 ALI file named in the @code{gnatbind} command line.
15651 @geindex -l (gnatbind)
15653 @item @code{-l}
15655 Output chosen elaboration order.
15657 @geindex -L (gnatbind)
15659 @item @code{-L@emph{xxx}}
15661 Bind the units for library building. In this case the @code{adainit} and
15662 @code{adafinal} procedures (@ref{b4,,Binding with Non-Ada Main Programs})
15663 are renamed to @code{@emph{xxx}init} and
15664 @code{@emph{xxx}final}.
15665 Implies -n.
15666 (@ref{15,,GNAT and Libraries}, for more details.)
15668 @geindex -M (gnatbind)
15670 @item @code{-M@emph{xyz}}
15672 Rename generated main program from main to xyz. This option is
15673 supported on cross environments only.
15675 @geindex -m (gnatbind)
15677 @item @code{-m@emph{n}}
15679 Limit number of detected errors or warnings to @code{n}, where @code{n} is
15680 in the range 1..999999. The default value if no switch is
15681 given is 9999. If the number of warnings reaches this limit, then a
15682 message is output and further warnings are suppressed, the bind
15683 continues in this case. If the number of errors reaches this
15684 limit, then a message is output and the bind is abandoned.
15685 A value of zero means that no limit is enforced. The equal
15686 sign is optional.
15688 @geindex -n (gnatbind)
15690 @item @code{-n}
15692 No main program.
15694 @geindex -nostdinc (gnatbind)
15696 @item @code{-nostdinc}
15698 Do not look for sources in the system default directory.
15700 @geindex -nostdlib (gnatbind)
15702 @item @code{-nostdlib}
15704 Do not look for library files in the system default directory.
15706 @geindex --RTS (gnatbind)
15708 @item @code{--RTS=@emph{rts-path}}
15710 Specifies the default location of the runtime library. Same meaning as the
15711 equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
15713 @geindex -o (gnatbind)
15715 @item @code{-o @emph{file}}
15717 Name the output file @code{file} (default is @code{b~`xxx}.adb`).
15718 Note that if this option is used, then linking must be done manually,
15719 gnatlink cannot be used.
15721 @geindex -O (gnatbind)
15723 @item @code{-O[=@emph{filename}]}
15725 Output object list (to standard output or to the named file).
15727 @geindex -p (gnatbind)
15729 @item @code{-p}
15731 Pessimistic (worst-case) elaboration order.
15733 @geindex -P (gnatbind)
15735 @item @code{-P}
15737 Generate binder file suitable for CodePeer.
15739 @geindex -R (gnatbind)
15741 @item @code{-R}
15743 Output closure source list, which includes all non-run-time units that are
15744 included in the bind.
15746 @geindex -Ra (gnatbind)
15748 @item @code{-Ra}
15750 Like @code{-R} but the list includes run-time units.
15752 @geindex -s (gnatbind)
15754 @item @code{-s}
15756 Require all source files to be present.
15758 @geindex -S (gnatbind)
15760 @item @code{-S@emph{xxx}}
15762 Specifies the value to be used when detecting uninitialized scalar
15763 objects with pragma Initialize_Scalars.
15764 The @code{xxx} string specified with the switch is one of:
15767 @itemize *
15769 @item 
15770 @code{in} for an invalid value.
15772 If zero is invalid for the discrete type in question,
15773 then the scalar value is set to all zero bits.
15774 For signed discrete types, the largest possible negative value of
15775 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15776 For unsigned discrete types, the underlying scalar value is set to all
15777 one bits. For floating-point types, a NaN value is set
15778 (see body of package System.Scalar_Values for exact values).
15780 @item 
15781 @code{lo} for low value.
15783 If zero is invalid for the discrete type in question,
15784 then the scalar value is set to all zero bits.
15785 For signed discrete types, the largest possible negative value of
15786 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15787 For unsigned discrete types, the underlying scalar value is set to all
15788 zero bits. For floating-point, a small value is set
15789 (see body of package System.Scalar_Values for exact values).
15791 @item 
15792 @code{hi} for high value.
15794 If zero is invalid for the discrete type in question,
15795 then the scalar value is set to all one bits.
15796 For signed discrete types, the largest possible positive value of
15797 the underlying scalar is set (i.e. a zero bit followed by all one bits).
15798 For unsigned discrete types, the underlying scalar value is set to all
15799 one bits. For floating-point, a large value is set
15800 (see body of package System.Scalar_Values for exact values).
15802 @item 
15803 @code{xx} for hex value (two hex digits).
15805 The underlying scalar is set to a value consisting of repeated bytes, whose
15806 value corresponds to the given value. For example if @code{BF} is given,
15807 then a 32-bit scalar value will be set to the bit patterm @code{16#BFBFBFBF#}.
15808 @end itemize
15810 @geindex GNAT_INIT_SCALARS
15812 In addition, you can specify @code{-Sev} to indicate that the value is
15813 to be set at run time. In this case, the program will look for an environment
15814 variable of the form @code{GNAT_INIT_SCALARS=@emph{yy}}, where @code{yy} is one
15815 of @code{in/lo/hi/@emph{xx}} with the same meanings as above.
15816 If no environment variable is found, or if it does not have a valid value,
15817 then the default is @code{in} (invalid values).
15818 @end table
15820 @geindex -static (gnatbind)
15823 @table @asis
15825 @item @code{-static}
15827 Link against a static GNAT run time.
15829 @geindex -shared (gnatbind)
15831 @item @code{-shared}
15833 Link against a shared GNAT run time when available.
15835 @geindex -t (gnatbind)
15837 @item @code{-t}
15839 Tolerate time stamp and other consistency errors.
15841 @geindex -T (gnatbind)
15843 @item @code{-T@emph{n}}
15845 Set the time slice value to @code{n} milliseconds. If the system supports
15846 the specification of a specific time slice value, then the indicated value
15847 is used. If the system does not support specific time slice values, but
15848 does support some general notion of round-robin scheduling, then any
15849 nonzero value will activate round-robin scheduling.
15851 A value of zero is treated specially. It turns off time
15852 slicing, and in addition, indicates to the tasking run time that the
15853 semantics should match as closely as possible the Annex D
15854 requirements of the Ada RM, and in particular sets the default
15855 scheduling policy to @code{FIFO_Within_Priorities}.
15857 @geindex -u (gnatbind)
15859 @item @code{-u@emph{n}}
15861 Enable dynamic stack usage, with @code{n} results stored and displayed
15862 at program termination. A result is generated when a task
15863 terminates. Results that can't be stored are displayed on the fly, at
15864 task termination. This option is currently not supported on Itanium
15865 platforms. (See @ref{121,,Dynamic Stack Usage Analysis} for details.)
15867 @geindex -v (gnatbind)
15869 @item @code{-v}
15871 Verbose mode. Write error messages, header, summary output to
15872 @code{stdout}.
15874 @geindex -V (gnatbind)
15876 @item @code{-V@emph{key}=@emph{value}}
15878 Store the given association of @code{key} to @code{value} in the bind environment.
15879 Values stored this way can be retrieved at run time using
15880 @code{GNAT.Bind_Environment}.
15882 @geindex -w (gnatbind)
15884 @item @code{-w@emph{x}}
15886 Warning mode; @code{x} = s/e for suppress/treat as error.
15888 @geindex -Wx (gnatbind)
15890 @item @code{-Wx@emph{e}}
15892 Override default wide character encoding for standard Text_IO files.
15894 @geindex -x (gnatbind)
15896 @item @code{-x}
15898 Exclude source files (check object consistency only).
15900 @geindex -Xnnn (gnatbind)
15902 @item @code{-X@emph{nnn}}
15904 Set default exit status value, normally 0 for POSIX compliance.
15906 @geindex -y (gnatbind)
15908 @item @code{-y}
15910 Enable leap seconds support in @code{Ada.Calendar} and its children.
15912 @geindex -z (gnatbind)
15914 @item @code{-z}
15916 No main subprogram.
15917 @end table
15919 You may obtain this listing of switches by running @code{gnatbind} with
15920 no arguments.
15922 @menu
15923 * Consistency-Checking Modes:: 
15924 * Binder Error Message Control:: 
15925 * Elaboration Control:: 
15926 * Output Control:: 
15927 * Dynamic Allocation Control:: 
15928 * Binding with Non-Ada Main Programs:: 
15929 * Binding Programs with No Main Subprogram:: 
15931 @end menu
15933 @node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
15934 @anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{122}@anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{123}
15935 @subsubsection Consistency-Checking Modes
15938 As described earlier, by default @code{gnatbind} checks
15939 that object files are consistent with one another and are consistent
15940 with any source files it can locate. The following switches control binder
15941 access to sources.
15943 @quotation
15945 @geindex -s (gnatbind)
15946 @end quotation
15949 @table @asis
15951 @item @code{-s}
15953 Require source files to be present. In this mode, the binder must be
15954 able to locate all source files that are referenced, in order to check
15955 their consistency. In normal mode, if a source file cannot be located it
15956 is simply ignored. If you specify this switch, a missing source
15957 file is an error.
15959 @geindex -Wx (gnatbind)
15961 @item @code{-Wx@emph{e}}
15963 Override default wide character encoding for standard Text_IO files.
15964 Normally the default wide character encoding method used for standard
15965 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
15966 the main source input (see description of switch
15967 @code{-gnatWx} for the compiler). The
15968 use of this switch for the binder (which has the same set of
15969 possible arguments) overrides this default as specified.
15971 @geindex -x (gnatbind)
15973 @item @code{-x}
15975 Exclude source files. In this mode, the binder only checks that ALI
15976 files are consistent with one another. Source files are not accessed.
15977 The binder runs faster in this mode, and there is still a guarantee that
15978 the resulting program is self-consistent.
15979 If a source file has been edited since it was last compiled, and you
15980 specify this switch, the binder will not detect that the object
15981 file is out of date with respect to the source file. Note that this is the
15982 mode that is automatically used by @code{gnatmake} because in this
15983 case the checking against sources has already been performed by
15984 @code{gnatmake} in the course of compilation (i.e., before binding).
15985 @end table
15987 @node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
15988 @anchor{gnat_ugn/building_executable_programs_with_gnat id36}@anchor{124}@anchor{gnat_ugn/building_executable_programs_with_gnat binder-error-message-control}@anchor{125}
15989 @subsubsection Binder Error Message Control
15992 The following switches provide control over the generation of error
15993 messages from the binder:
15995 @quotation
15997 @geindex -v (gnatbind)
15998 @end quotation
16001 @table @asis
16003 @item @code{-v}
16005 Verbose mode. In the normal mode, brief error messages are generated to
16006 @code{stderr}. If this switch is present, a header is written
16007 to @code{stdout} and any error messages are directed to @code{stdout}.
16008 All that is written to @code{stderr} is a brief summary message.
16010 @geindex -b (gnatbind)
16012 @item @code{-b}
16014 Generate brief error messages to @code{stderr} even if verbose mode is
16015 specified. This is relevant only when used with the
16016 @code{-v} switch.
16018 @geindex -m (gnatbind)
16020 @item @code{-m@emph{n}}
16022 Limits the number of error messages to @code{n}, a decimal integer in the
16023 range 1-999. The binder terminates immediately if this limit is reached.
16025 @geindex -M (gnatbind)
16027 @item @code{-M@emph{xxx}}
16029 Renames the generated main program from @code{main} to @code{xxx}.
16030 This is useful in the case of some cross-building environments, where
16031 the actual main program is separate from the one generated
16032 by @code{gnatbind}.
16034 @geindex -ws (gnatbind)
16036 @geindex Warnings
16038 @item @code{-ws}
16040 Suppress all warning messages.
16042 @geindex -we (gnatbind)
16044 @item @code{-we}
16046 Treat any warning messages as fatal errors.
16048 @geindex -t (gnatbind)
16050 @geindex Time stamp checks
16051 @geindex in binder
16053 @geindex Binder consistency checks
16055 @geindex Consistency checks
16056 @geindex in binder
16058 @item @code{-t}
16060 The binder performs a number of consistency checks including:
16063 @itemize *
16065 @item 
16066 Check that time stamps of a given source unit are consistent
16068 @item 
16069 Check that checksums of a given source unit are consistent
16071 @item 
16072 Check that consistent versions of @code{GNAT} were used for compilation
16074 @item 
16075 Check consistency of configuration pragmas as required
16076 @end itemize
16078 Normally failure of such checks, in accordance with the consistency
16079 requirements of the Ada Reference Manual, causes error messages to be
16080 generated which abort the binder and prevent the output of a binder
16081 file and subsequent link to obtain an executable.
16083 The @code{-t} switch converts these error messages
16084 into warnings, so that
16085 binding and linking can continue to completion even in the presence of such
16086 errors. The result may be a failed link (due to missing symbols), or a
16087 non-functional executable which has undefined semantics.
16089 @cartouche
16090 @quotation Note 
16091 This means that @code{-t} should be used only in unusual situations,
16092 with extreme care.
16093 @end quotation
16094 @end cartouche
16095 @end table
16097 @node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
16098 @anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{126}@anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{127}
16099 @subsubsection Elaboration Control
16102 The following switches provide additional control over the elaboration
16103 order. For full details see @ref{f,,Elaboration Order Handling in GNAT}.
16105 @geindex -f (gnatbind)
16108 @table @asis
16110 @item @code{-f@emph{elab-order}}
16112 Force elaboration order.
16114 @code{elab-order} should be the name of a "forced elaboration order file", that
16115 is, a text file containing library item names, one per line. A name of the
16116 form "some.unit%s" or "some.unit (spec)" denotes the spec of Some.Unit. A
16117 name of the form "some.unit%b" or "some.unit (body)" denotes the body of
16118 Some.Unit. Each pair of lines is taken to mean that there is an elaboration
16119 dependence of the second line on the first. For example, if the file
16120 contains:
16122 @example
16123 this (spec)
16124 this (body)
16125 that (spec)
16126 that (body)
16127 @end example
16129 then the spec of This will be elaborated before the body of This, and the
16130 body of This will be elaborated before the spec of That, and the spec of That
16131 will be elaborated before the body of That. The first and last of these three
16132 dependences are already required by Ada rules, so this file is really just
16133 forcing the body of This to be elaborated before the spec of That.
16135 The given order must be consistent with Ada rules, or else @code{gnatbind} will
16136 give elaboration cycle errors. For example, if you say x (body) should be
16137 elaborated before x (spec), there will be a cycle, because Ada rules require
16138 x (spec) to be elaborated before x (body); you can't have the spec and body
16139 both elaborated before each other.
16141 If you later add "with That;" to the body of This, there will be a cycle, in
16142 which case you should erase either "this (body)" or "that (spec)" from the
16143 above forced elaboration order file.
16145 Blank lines and Ada-style comments are ignored. Unit names that do not exist
16146 in the program are ignored. Units in the GNAT predefined library are also
16147 ignored.
16149 @geindex -p (gnatbind)
16151 @item @code{-p}
16153 Normally the binder attempts to choose an elaboration order that is
16154 likely to minimize the likelihood of an elaboration order error resulting
16155 in raising a @code{Program_Error} exception. This switch reverses the
16156 action of the binder, and requests that it deliberately choose an order
16157 that is likely to maximize the likelihood of an elaboration error.
16158 This is useful in ensuring portability and avoiding dependence on
16159 accidental fortuitous elaboration ordering.
16161 Normally it only makes sense to use the @code{-p}
16162 switch if dynamic
16163 elaboration checking is used (@code{-gnatE} switch used for compilation).
16164 This is because in the default static elaboration mode, all necessary
16165 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
16166 These implicit pragmas are still respected by the binder in
16167 @code{-p} mode, so a
16168 safe elaboration order is assured.
16170 Note that @code{-p} is not intended for
16171 production use; it is more for debugging/experimental use.
16172 @end table
16174 @node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
16175 @anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{128}@anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{129}
16176 @subsubsection Output Control
16179 The following switches allow additional control over the output
16180 generated by the binder.
16182 @quotation
16184 @geindex -c (gnatbind)
16185 @end quotation
16188 @table @asis
16190 @item @code{-c}
16192 Check only. Do not generate the binder output file. In this mode the
16193 binder performs all error checks but does not generate an output file.
16195 @geindex -e (gnatbind)
16197 @item @code{-e}
16199 Output complete list of elaboration-order dependencies, showing the
16200 reason for each dependency. This output can be rather extensive but may
16201 be useful in diagnosing problems with elaboration order. The output is
16202 written to @code{stdout}.
16204 @geindex -h (gnatbind)
16206 @item @code{-h}
16208 Output usage information. The output is written to @code{stdout}.
16210 @geindex -K (gnatbind)
16212 @item @code{-K}
16214 Output linker options to @code{stdout}. Includes library search paths,
16215 contents of pragmas Ident and Linker_Options, and libraries added
16216 by @code{gnatbind}.
16218 @geindex -l (gnatbind)
16220 @item @code{-l}
16222 Output chosen elaboration order. The output is written to @code{stdout}.
16224 @geindex -O (gnatbind)
16226 @item @code{-O}
16228 Output full names of all the object files that must be linked to provide
16229 the Ada component of the program. The output is written to @code{stdout}.
16230 This list includes the files explicitly supplied and referenced by the user
16231 as well as implicitly referenced run-time unit files. The latter are
16232 omitted if the corresponding units reside in shared libraries. The
16233 directory names for the run-time units depend on the system configuration.
16235 @geindex -o (gnatbind)
16237 @item @code{-o @emph{file}}
16239 Set name of output file to @code{file} instead of the normal
16240 @code{b~`mainprog}.adb` default. Note that @code{file} denote the Ada
16241 binder generated body filename.
16242 Note that if this option is used, then linking must be done manually.
16243 It is not possible to use gnatlink in this case, since it cannot locate
16244 the binder file.
16246 @geindex -r (gnatbind)
16248 @item @code{-r}
16250 Generate list of @code{pragma Restrictions} that could be applied to
16251 the current unit. This is useful for code audit purposes, and also may
16252 be used to improve code generation in some cases.
16253 @end table
16255 @node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
16256 @anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{120}@anchor{gnat_ugn/building_executable_programs_with_gnat id39}@anchor{12a}
16257 @subsubsection Dynamic Allocation Control
16260 The heap control switches -- @code{-H32} and @code{-H64} --
16261 determine whether dynamic allocation uses 32-bit or 64-bit memory.
16262 They only affect compiler-generated allocations via @code{__gnat_malloc};
16263 explicit calls to @code{malloc} and related functions from the C
16264 run-time library are unaffected.
16267 @table @asis
16269 @item @code{-H32}
16271 Allocate memory on 32-bit heap
16273 @item @code{-H64}
16275 Allocate memory on 64-bit heap.  This is the default
16276 unless explicitly overridden by a @code{'Size} clause on the access type.
16277 @end table
16279 These switches are only effective on VMS platforms.
16281 @node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
16282 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-non-ada-main-programs}@anchor{b4}@anchor{gnat_ugn/building_executable_programs_with_gnat id40}@anchor{12b}
16283 @subsubsection Binding with Non-Ada Main Programs
16286 The description so far has assumed that the main
16287 program is in Ada, and that the task of the binder is to generate a
16288 corresponding function @code{main} that invokes this Ada main
16289 program. GNAT also supports the building of executable programs where
16290 the main program is not in Ada, but some of the called routines are
16291 written in Ada and compiled using GNAT (@ref{44,,Mixed Language Programming}).
16292 The following switch is used in this situation:
16294 @quotation
16296 @geindex -n (gnatbind)
16297 @end quotation
16300 @table @asis
16302 @item @code{-n}
16304 No main program. The main program is not in Ada.
16305 @end table
16307 In this case, most of the functions of the binder are still required,
16308 but instead of generating a main program, the binder generates a file
16309 containing the following callable routines:
16311 @quotation
16313 @geindex adainit
16316 @table @asis
16318 @item @code{adainit}
16320 You must call this routine to initialize the Ada part of the program by
16321 calling the necessary elaboration routines. A call to @code{adainit} is
16322 required before the first call to an Ada subprogram.
16324 Note that it is assumed that the basic execution environment must be setup
16325 to be appropriate for Ada execution at the point where the first Ada
16326 subprogram is called. In particular, if the Ada code will do any
16327 floating-point operations, then the FPU must be setup in an appropriate
16328 manner. For the case of the x86, for example, full precision mode is
16329 required. The procedure GNAT.Float_Control.Reset may be used to ensure
16330 that the FPU is in the right state.
16331 @end table
16333 @geindex adafinal
16336 @table @asis
16338 @item @code{adafinal}
16340 You must call this routine to perform any library-level finalization
16341 required by the Ada subprograms. A call to @code{adafinal} is required
16342 after the last call to an Ada subprogram, and before the program
16343 terminates.
16344 @end table
16345 @end quotation
16347 @geindex -n (gnatbind)
16349 @geindex Binder
16350 @geindex multiple input files
16352 If the @code{-n} switch
16353 is given, more than one ALI file may appear on
16354 the command line for @code{gnatbind}. The normal @code{closure}
16355 calculation is performed for each of the specified units. Calculating
16356 the closure means finding out the set of units involved by tracing
16357 @emph{with} references. The reason it is necessary to be able to
16358 specify more than one ALI file is that a given program may invoke two or
16359 more quite separate groups of Ada units.
16361 The binder takes the name of its output file from the last specified ALI
16362 file, unless overridden by the use of the @code{-o file}.
16364 @geindex -o (gnatbind)
16366 The output is an Ada unit in source form that can be compiled with GNAT.
16367 This compilation occurs automatically as part of the @code{gnatlink}
16368 processing.
16370 Currently the GNAT run time requires a FPU using 80 bits mode
16371 precision. Under targets where this is not the default it is required to
16372 call GNAT.Float_Control.Reset before using floating point numbers (this
16373 include float computation, float input and output) in the Ada code. A
16374 side effect is that this could be the wrong mode for the foreign code
16375 where floating point computation could be broken after this call.
16377 @node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
16378 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-programs-with-no-main-subprogram}@anchor{12c}@anchor{gnat_ugn/building_executable_programs_with_gnat id41}@anchor{12d}
16379 @subsubsection Binding Programs with No Main Subprogram
16382 It is possible to have an Ada program which does not have a main
16383 subprogram. This program will call the elaboration routines of all the
16384 packages, then the finalization routines.
16386 The following switch is used to bind programs organized in this manner:
16388 @quotation
16390 @geindex -z (gnatbind)
16391 @end quotation
16394 @table @asis
16396 @item @code{-z}
16398 Normally the binder checks that the unit name given on the command line
16399 corresponds to a suitable main subprogram. When this switch is used,
16400 a list of ALI files can be given, and the execution of the program
16401 consists of elaboration of these units in an appropriate order. Note
16402 that the default wide character encoding method for standard Text_IO
16403 files is always set to Brackets if this switch is set (you can use
16404 the binder switch
16405 @code{-Wx} to override this default).
16406 @end table
16408 @node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
16409 @anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{12e}@anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{12f}
16410 @subsection Command-Line Access
16413 The package @code{Ada.Command_Line} provides access to the command-line
16414 arguments and program name. In order for this interface to operate
16415 correctly, the two variables
16417 @example
16418 int gnat_argc;
16419 char **gnat_argv;
16420 @end example
16422 @geindex gnat_argv
16424 @geindex gnat_argc
16426 are declared in one of the GNAT library routines. These variables must
16427 be set from the actual @code{argc} and @code{argv} values passed to the
16428 main program. With no @emph{n} present, @code{gnatbind}
16429 generates the C main program to automatically set these variables.
16430 If the @emph{n} switch is used, there is no automatic way to
16431 set these variables. If they are not set, the procedures in
16432 @code{Ada.Command_Line} will not be available, and any attempt to use
16433 them will raise @code{Constraint_Error}. If command line access is
16434 required, your main program must set @code{gnat_argc} and
16435 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
16438 @node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
16439 @anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-for-gnatbind}@anchor{8c}@anchor{gnat_ugn/building_executable_programs_with_gnat id43}@anchor{130}
16440 @subsection Search Paths for @code{gnatbind}
16443 The binder takes the name of an ALI file as its argument and needs to
16444 locate source files as well as other ALI files to verify object consistency.
16446 For source files, it follows exactly the same search rules as @code{gcc}
16447 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
16448 directories searched are:
16451 @itemize *
16453 @item 
16454 The directory containing the ALI file named in the command line, unless
16455 the switch @code{-I-} is specified.
16457 @item 
16458 All directories specified by @code{-I}
16459 switches on the @code{gnatbind}
16460 command line, in the order given.
16462 @geindex ADA_PRJ_OBJECTS_FILE
16464 @item 
16465 Each of the directories listed in the text file whose name is given
16466 by the 
16467 @geindex ADA_PRJ_OBJECTS_FILE
16468 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16469 @code{ADA_PRJ_OBJECTS_FILE} environment variable.
16471 @geindex ADA_PRJ_OBJECTS_FILE
16472 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16473 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
16474 driver when project files are used. It should not normally be set
16475 by other means.
16477 @geindex ADA_OBJECTS_PATH
16479 @item 
16480 Each of the directories listed in the value of the
16481 @geindex ADA_OBJECTS_PATH
16482 @geindex environment variable; ADA_OBJECTS_PATH
16483 @code{ADA_OBJECTS_PATH} environment variable.
16484 Construct this value
16485 exactly as the 
16486 @geindex PATH
16487 @geindex environment variable; PATH
16488 @code{PATH} environment variable: a list of directory
16489 names separated by colons (semicolons when working with the NT version
16490 of GNAT).
16492 @item 
16493 The content of the @code{ada_object_path} file which is part of the GNAT
16494 installation tree and is used to store standard libraries such as the
16495 GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is
16496 specified. See @ref{87,,Installing a library}
16497 @end itemize
16499 @geindex -I (gnatbind)
16501 @geindex -aI (gnatbind)
16503 @geindex -aO (gnatbind)
16505 In the binder the switch @code{-I}
16506 is used to specify both source and
16507 library file paths. Use @code{-aI}
16508 instead if you want to specify
16509 source paths only, and @code{-aO}
16510 if you want to specify library paths
16511 only. This means that for the binder
16512 @code{-I@emph{dir}} is equivalent to
16513 @code{-aI@emph{dir}}
16514 @code{-aO`@emph{dir}}.
16515 The binder generates the bind file (a C language source file) in the
16516 current working directory.
16518 @geindex Ada
16520 @geindex System
16522 @geindex Interfaces
16524 @geindex GNAT
16526 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
16527 children make up the GNAT Run-Time Library, together with the package
16528 GNAT and its children, which contain a set of useful additional
16529 library functions provided by GNAT. The sources for these units are
16530 needed by the compiler and are kept together in one directory. The ALI
16531 files and object files generated by compiling the RTL are needed by the
16532 binder and the linker and are kept together in one directory, typically
16533 different from the directory containing the sources. In a normal
16534 installation, you need not specify these directory names when compiling
16535 or binding. Either the environment variables or the built-in defaults
16536 cause these files to be found.
16538 Besides simplifying access to the RTL, a major use of search paths is
16539 in compiling sources from multiple directories. This can make
16540 development environments much more flexible.
16542 @node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16543 @anchor{gnat_ugn/building_executable_programs_with_gnat id44}@anchor{131}@anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatbind-usage}@anchor{132}
16544 @subsection Examples of @code{gnatbind} Usage
16547 Here are some examples of @code{gnatbind} invovations:
16549 @quotation
16551 @example
16552 gnatbind hello
16553 @end example
16555 The main program @code{Hello} (source program in @code{hello.adb}) is
16556 bound using the standard switch settings. The generated main program is
16557 @code{b~hello.adb}. This is the normal, default use of the binder.
16559 @example
16560 gnatbind hello -o mainprog.adb
16561 @end example
16563 The main program @code{Hello} (source program in @code{hello.adb}) is
16564 bound using the standard switch settings. The generated main program is
16565 @code{mainprog.adb} with the associated spec in
16566 @code{mainprog.ads}. Note that you must specify the body here not the
16567 spec. Note that if this option is used, then linking must be done manually,
16568 since gnatlink will not be able to find the generated file.
16569 @end quotation
16571 @node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16572 @anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{133}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{1e}
16573 @section Linking with @code{gnatlink}
16576 @geindex gnatlink
16578 This chapter discusses @code{gnatlink}, a tool that links
16579 an Ada program and builds an executable file. This utility
16580 invokes the system linker (via the @code{gcc} command)
16581 with a correct list of object files and library references.
16582 @code{gnatlink} automatically determines the list of files and
16583 references for the Ada part of a program. It uses the binder file
16584 generated by the @code{gnatbind} to determine this list.
16586 @menu
16587 * Running gnatlink:: 
16588 * Switches for gnatlink:: 
16590 @end menu
16592 @node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16593 @anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{134}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{135}
16594 @subsection Running @code{gnatlink}
16597 The form of the @code{gnatlink} command is
16599 @example
16600 $ gnatlink [ switches ] mainprog [.ali]
16601            [ non-Ada objects ] [ linker options ]
16602 @end example
16604 The arguments of @code{gnatlink} (switches, main @code{ALI} file,
16605 non-Ada objects
16606 or linker options) may be in any order, provided that no non-Ada object may
16607 be mistaken for a main @code{ALI} file.
16608 Any file name @code{F} without the @code{.ali}
16609 extension will be taken as the main @code{ALI} file if a file exists
16610 whose name is the concatenation of @code{F} and @code{.ali}.
16612 @code{mainprog.ali} references the ALI file of the main program.
16613 The @code{.ali} extension of this file can be omitted. From this
16614 reference, @code{gnatlink} locates the corresponding binder file
16615 @code{b~mainprog.adb} and, using the information in this file along
16616 with the list of non-Ada objects and linker options, constructs a
16617 linker command file to create the executable.
16619 The arguments other than the @code{gnatlink} switches and the main
16620 @code{ALI} file are passed to the linker uninterpreted.
16621 They typically include the names of
16622 object files for units written in other languages than Ada and any library
16623 references required to resolve references in any of these foreign language
16624 units, or in @code{Import} pragmas in any Ada units.
16626 @code{linker options} is an optional list of linker specific
16627 switches.
16628 The default linker called by gnatlink is @code{gcc} which in
16629 turn calls the appropriate system linker.
16631 One useful option for the linker is @code{-s}: it reduces the size of the
16632 executable by removing all symbol table and relocation information from the
16633 executable.
16635 Standard options for the linker such as @code{-lmy_lib} or
16636 @code{-Ldir} can be added as is.
16637 For options that are not recognized by
16638 @code{gcc} as linker options, use the @code{gcc} switches
16639 @code{-Xlinker} or @code{-Wl,}.
16641 Refer to the GCC documentation for
16642 details.
16644 Here is an example showing how to generate a linker map:
16646 @example
16647 $ gnatlink my_prog -Wl,-Map,MAPFILE
16648 @end example
16650 Using @code{linker options} it is possible to set the program stack and
16651 heap size.
16652 See @ref{136,,Setting Stack Size from gnatlink} and
16653 @ref{137,,Setting Heap Size from gnatlink}.
16655 @code{gnatlink} determines the list of objects required by the Ada
16656 program and prepends them to the list of objects passed to the linker.
16657 @code{gnatlink} also gathers any arguments set by the use of
16658 @code{pragma Linker_Options} and adds them to the list of arguments
16659 presented to the linker.
16661 @node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
16662 @anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{138}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{139}
16663 @subsection Switches for @code{gnatlink}
16666 The following switches are available with the @code{gnatlink} utility:
16668 @geindex --version (gnatlink)
16671 @table @asis
16673 @item @code{--version}
16675 Display Copyright and version, then exit disregarding all other options.
16676 @end table
16678 @geindex --help (gnatlink)
16681 @table @asis
16683 @item @code{--help}
16685 If @code{--version} was not used, display usage, then exit disregarding
16686 all other options.
16687 @end table
16689 @geindex Command line length
16691 @geindex -f (gnatlink)
16694 @table @asis
16696 @item @code{-f}
16698 On some targets, the command line length is limited, and @code{gnatlink}
16699 will generate a separate file for the linker if the list of object files
16700 is too long.
16701 The @code{-f} switch forces this file
16702 to be generated even if
16703 the limit is not exceeded. This is useful in some cases to deal with
16704 special situations where the command line length is exceeded.
16705 @end table
16707 @geindex Debugging information
16708 @geindex including
16710 @geindex -g (gnatlink)
16713 @table @asis
16715 @item @code{-g}
16717 The option to include debugging information causes the Ada bind file (in
16718 other words, @code{b~mainprog.adb}) to be compiled with @code{-g}.
16719 In addition, the binder does not delete the @code{b~mainprog.adb},
16720 @code{b~mainprog.o} and @code{b~mainprog.ali} files.
16721 Without @code{-g}, the binder removes these files by default.
16722 @end table
16724 @geindex -n (gnatlink)
16727 @table @asis
16729 @item @code{-n}
16731 Do not compile the file generated by the binder. This may be used when
16732 a link is rerun with different options, but there is no need to recompile
16733 the binder file.
16734 @end table
16736 @geindex -v (gnatlink)
16739 @table @asis
16741 @item @code{-v}
16743 Verbose mode. Causes additional information to be output, including a full
16744 list of the included object files.
16745 This switch option is most useful when you want
16746 to see what set of object files are being used in the link step.
16747 @end table
16749 @geindex -v -v (gnatlink)
16752 @table @asis
16754 @item @code{-v -v}
16756 Very verbose mode. Requests that the compiler operate in verbose mode when
16757 it compiles the binder file, and that the system linker run in verbose mode.
16758 @end table
16760 @geindex -o (gnatlink)
16763 @table @asis
16765 @item @code{-o @emph{exec-name}}
16767 @code{exec-name} specifies an alternate name for the generated
16768 executable program. If this switch is omitted, the executable has the same
16769 name as the main unit. For example, @code{gnatlink try.ali} creates
16770 an executable called @code{try}.
16771 @end table
16773 @geindex -b (gnatlink)
16776 @table @asis
16778 @item @code{-b @emph{target}}
16780 Compile your program to run on @code{target}, which is the name of a
16781 system configuration. You must have a GNAT cross-compiler built if
16782 @code{target} is not the same as your host system.
16783 @end table
16785 @geindex -B (gnatlink)
16788 @table @asis
16790 @item @code{-B@emph{dir}}
16792 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
16793 from @code{dir} instead of the default location. Only use this switch
16794 when multiple versions of the GNAT compiler are available.
16795 See the @code{Directory Options} section in @cite{The_GNU_Compiler_Collection}
16796 for further details. You would normally use the @code{-b} or
16797 @code{-V} switch instead.
16798 @end table
16800 @geindex -M (gnatlink)
16803 @table @asis
16805 @item @code{-M}
16807 When linking an executable, create a map file. The name of the map file
16808 has the same name as the executable with extension ".map".
16809 @end table
16811 @geindex -M= (gnatlink)
16814 @table @asis
16816 @item @code{-M=@emph{mapfile}}
16818 When linking an executable, create a map file. The name of the map file is
16819 @code{mapfile}.
16820 @end table
16822 @geindex --GCC=compiler_name (gnatlink)
16825 @table @asis
16827 @item @code{--GCC=@emph{compiler_name}}
16829 Program used for compiling the binder file. The default is
16830 @code{gcc}. You need to use quotes around @code{compiler_name} if
16831 @code{compiler_name} contains spaces or other separator characters.
16832 As an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to
16833 use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
16834 inserted after your command name. Thus in the above example the compiler
16835 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
16836 A limitation of this syntax is that the name and path name of the executable
16837 itself must not include any embedded spaces. If the compiler executable is
16838 different from the default one (gcc or <prefix>-gcc), then the back-end
16839 switches in the ALI file are not used to compile the binder generated source.
16840 For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
16841 switches will be used for @code{--GCC="gcc -gnatv"}. If several
16842 @code{--GCC=compiler_name} are used, only the last @code{compiler_name}
16843 is taken into account. However, all the additional switches are also taken
16844 into account. Thus,
16845 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
16846 @code{--GCC="bar -x -y -z -t"}.
16847 @end table
16849 @geindex --LINK= (gnatlink)
16852 @table @asis
16854 @item @code{--LINK=@emph{name}}
16856 @code{name} is the name of the linker to be invoked. This is especially
16857 useful in mixed language programs since languages such as C++ require
16858 their own linker to be used. When this switch is omitted, the default
16859 name for the linker is @code{gcc}. When this switch is used, the
16860 specified linker is called instead of @code{gcc} with exactly the same
16861 parameters that would have been passed to @code{gcc} so if the desired
16862 linker requires different parameters it is necessary to use a wrapper
16863 script that massages the parameters before invoking the real linker. It
16864 may be useful to control the exact invocation by using the verbose
16865 switch.
16866 @end table
16868 @node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
16869 @anchor{gnat_ugn/building_executable_programs_with_gnat using-the-gnu-make-utility}@anchor{1f}@anchor{gnat_ugn/building_executable_programs_with_gnat id48}@anchor{13a}
16870 @section Using the GNU @code{make} Utility
16873 @geindex make (GNU)
16874 @geindex GNU make
16876 This chapter offers some examples of makefiles that solve specific
16877 problems. It does not explain how to write a makefile, nor does it try to replace the
16878 @code{gnatmake} utility (@ref{1b,,Building with gnatmake}).
16880 All the examples in this section are specific to the GNU version of
16881 make. Although @code{make} is a standard utility, and the basic language
16882 is the same, these examples use some advanced features found only in
16883 @code{GNU make}.
16885 @menu
16886 * Using gnatmake in a Makefile:: 
16887 * Automatically Creating a List of Directories:: 
16888 * Generating the Command Line Switches:: 
16889 * Overcoming Command Line Length Limits:: 
16891 @end menu
16893 @node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
16894 @anchor{gnat_ugn/building_executable_programs_with_gnat using-gnatmake-in-a-makefile}@anchor{13b}@anchor{gnat_ugn/building_executable_programs_with_gnat id49}@anchor{13c}
16895 @subsection Using gnatmake in a Makefile
16898 @c index makefile (GNU make)
16900 Complex project organizations can be handled in a very powerful way by
16901 using GNU make combined with gnatmake. For instance, here is a Makefile
16902 which allows you to build each subsystem of a big project into a separate
16903 shared library. Such a makefile allows you to significantly reduce the link
16904 time of very big applications while maintaining full coherence at
16905 each step of the build process.
16907 The list of dependencies are handled automatically by
16908 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
16909 the appropriate directories.
16911 Note that you should also read the example on how to automatically
16912 create the list of directories
16913 (@ref{13d,,Automatically Creating a List of Directories})
16914 which might help you in case your project has a lot of subdirectories.
16916 @example
16917 ## This Makefile is intended to be used with the following directory
16918 ## configuration:
16919 ##  - The sources are split into a series of csc (computer software components)
16920 ##    Each of these csc is put in its own directory.
16921 ##    Their name are referenced by the directory names.
16922 ##    They will be compiled into shared library (although this would also work
16923 ##    with static libraries
16924 ##  - The main program (and possibly other packages that do not belong to any
16925 ##    csc is put in the top level directory (where the Makefile is).
16926 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16927 ##                    \\_ second_csc (sources) __ lib (will contain the library)
16928 ##                    \\_ ...
16929 ## Although this Makefile is build for shared library, it is easy to modify
16930 ## to build partial link objects instead (modify the lines with -shared and
16931 ## gnatlink below)
16933 ## With this makefile, you can change any file in the system or add any new
16934 ## file, and everything will be recompiled correctly (only the relevant shared
16935 ## objects will be recompiled, and the main program will be re-linked).
16937 # The list of computer software component for your project. This might be
16938 # generated automatically.
16939 CSC_LIST=aa bb cc
16941 # Name of the main program (no extension)
16942 MAIN=main
16944 # If we need to build objects with -fPIC, uncomment the following line
16945 #NEED_FPIC=-fPIC
16947 # The following variable should give the directory containing libgnat.so
16948 # You can get this directory through 'gnatls -v'. This is usually the last
16949 # directory in the Object_Path.
16950 GLIB=...
16952 # The directories for the libraries
16953 # (This macro expands the list of CSC to the list of shared libraries, you
16954 # could simply use the expanded form:
16955 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16956 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16958 $@{MAIN@}: objects $@{LIB_DIR@}
16959     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16960     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16962 objects::
16963     # recompile the sources
16964     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16966 # Note: In a future version of GNAT, the following commands will be simplified
16967 # by a new tool, gnatmlib
16968 $@{LIB_DIR@}:
16969     mkdir -p $@{dir $@@ @}
16970     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16971     cd $@{dir $@@ @} && cp -f ../*.ali .
16973 # The dependencies for the modules
16974 # Note that we have to force the expansion of *.o, since in some cases
16975 # make won't be able to do it itself.
16976 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16977 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16978 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16980 # Make sure all of the shared libraries are in the path before starting the
16981 # program
16982 run::
16983     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16985 clean::
16986     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16987     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16988     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16989     $@{RM@} *.o *.ali $@{MAIN@}
16990 @end example
16992 @node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
16993 @anchor{gnat_ugn/building_executable_programs_with_gnat id50}@anchor{13e}@anchor{gnat_ugn/building_executable_programs_with_gnat automatically-creating-a-list-of-directories}@anchor{13d}
16994 @subsection Automatically Creating a List of Directories
16997 In most makefiles, you will have to specify a list of directories, and
16998 store it in a variable. For small projects, it is often easier to
16999 specify each of them by hand, since you then have full control over what
17000 is the proper order for these directories, which ones should be
17001 included.
17003 However, in larger projects, which might involve hundreds of
17004 subdirectories, it might be more convenient to generate this list
17005 automatically.
17007 The example below presents two methods. The first one, although less
17008 general, gives you more control over the list. It involves wildcard
17009 characters, that are automatically expanded by @code{make}. Its
17010 shortcoming is that you need to explicitly specify some of the
17011 organization of your project, such as for instance the directory tree
17012 depth, whether some directories are found in a separate tree, etc.
17014 The second method is the most general one. It requires an external
17015 program, called @code{find}, which is standard on all Unix systems. All
17016 the directories found under a given root directory will be added to the
17017 list.
17019 @example
17020 # The examples below are based on the following directory hierarchy:
17021 # All the directories can contain any number of files
17022 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17023 #                       ->  ab
17024 #                       ->  ac
17025 #                ->  b  ->  ba  ->  baa
17026 #                       ->  bb
17027 #                       ->  bc
17028 # This Makefile creates a variable called DIRS, that can be reused any time
17029 # you need this list (see the other examples in this section)
17031 # The root of your project's directory hierarchy
17032 ROOT_DIRECTORY=.
17034 ####
17035 # First method: specify explicitly the list of directories
17036 # This allows you to specify any subset of all the directories you need.
17037 ####
17039 DIRS := a/aa/ a/ab/ b/ba/
17041 ####
17042 # Second method: use wildcards
17043 # Note that the argument(s) to wildcard below should end with a '/'.
17044 # Since wildcards also return file names, we have to filter them out
17045 # to avoid duplicate directory names.
17046 # We thus use make's `@w{`}dir`@w{`} and `@w{`}sort`@w{`} functions.
17047 # It sets DIRs to the following value (note that the directories aaa and baa
17048 # are not given, unless you change the arguments to wildcard).
17049 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17050 ####
17052 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17053                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17055 ####
17056 # Third method: use an external program
17057 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17058 # This is the most complete command: it sets DIRs to the following value:
17059 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17060 ####
17062 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17063 @end example
17065 @node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
17066 @anchor{gnat_ugn/building_executable_programs_with_gnat id51}@anchor{13f}@anchor{gnat_ugn/building_executable_programs_with_gnat generating-the-command-line-switches}@anchor{140}
17067 @subsection Generating the Command Line Switches
17070 Once you have created the list of directories as explained in the
17071 previous section (@ref{13d,,Automatically Creating a List of Directories}),
17072 you can easily generate the command line arguments to pass to gnatmake.
17074 For the sake of completeness, this example assumes that the source path
17075 is not the same as the object path, and that you have two separate lists
17076 of directories.
17078 @example
17079 # see "Automatically creating a list of directories" to create
17080 # these variables
17081 SOURCE_DIRS=
17082 OBJECT_DIRS=
17084 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17085 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17087 all:
17088         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17089 @end example
17091 @node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
17092 @anchor{gnat_ugn/building_executable_programs_with_gnat overcoming-command-line-length-limits}@anchor{141}@anchor{gnat_ugn/building_executable_programs_with_gnat id52}@anchor{142}
17093 @subsection Overcoming Command Line Length Limits
17096 One problem that might be encountered on big projects is that many
17097 operating systems limit the length of the command line. It is thus hard to give
17098 gnatmake the list of source and object directories.
17100 This example shows how you can set up environment variables, which will
17101 make @code{gnatmake} behave exactly as if the directories had been
17102 specified on the command line, but have a much higher length limit (or
17103 even none on most systems).
17105 It assumes that you have created a list of directories in your Makefile,
17106 using one of the methods presented in
17107 @ref{13d,,Automatically Creating a List of Directories}.
17108 For the sake of completeness, we assume that the object
17109 path (where the ALI files are found) is different from the sources patch.
17111 Note a small trick in the Makefile below: for efficiency reasons, we
17112 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17113 expanded immediately by @code{make}. This way we overcome the standard
17114 make behavior which is to expand the variables only when they are
17115 actually used.
17117 On Windows, if you are using the standard Windows command shell, you must
17118 replace colons with semicolons in the assignments to these variables.
17120 @example
17121 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17122 # This is the same thing as putting the -I arguments on the command line.
17123 # (the equivalent of using -aI on the command line would be to define
17124 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17125 # You can of course have different values for these variables.
17127 # Note also that we need to keep the previous values of these variables, since
17128 # they might have been set before running 'make' to specify where the GNAT
17129 # library is installed.
17131 # see "Automatically creating a list of directories" to create these
17132 # variables
17133 SOURCE_DIRS=
17134 OBJECT_DIRS=
17136 empty:=
17137 space:=$@{empty@} $@{empty@}
17138 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17139 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17140 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17141 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17142 export ADA_INCLUDE_PATH
17143 export ADA_OBJECTS_PATH
17145 all:
17146         gnatmake main_unit
17147 @end example
17149 @node GNAT Utility Programs,GNAT and Program Execution,Building Executable Programs with GNAT,Top
17150 @anchor{gnat_ugn/gnat_utility_programs doc}@anchor{143}@anchor{gnat_ugn/gnat_utility_programs gnat-utility-programs}@anchor{b}@anchor{gnat_ugn/gnat_utility_programs id1}@anchor{144}
17151 @chapter GNAT Utility Programs
17154 This chapter describes a number of utility programs:
17158 @itemize *
17160 @item 
17161 @ref{20,,The File Cleanup Utility gnatclean}
17163 @item 
17164 @ref{21,,The GNAT Library Browser gnatls}
17166 @item 
17167 @ref{22,,The Cross-Referencing Tools gnatxref and gnatfind}
17169 @item 
17170 @ref{23,,The Ada to HTML Converter gnathtml}
17171 @end itemize
17173 Other GNAT utilities are described elsewhere in this manual:
17176 @itemize *
17178 @item 
17179 @ref{59,,Handling Arbitrary File Naming Conventions with gnatname}
17181 @item 
17182 @ref{63,,File Name Krunching with gnatkr}
17184 @item 
17185 @ref{36,,Renaming Files with gnatchop}
17187 @item 
17188 @ref{17,,Preprocessing with gnatprep}
17189 @end itemize
17191 @menu
17192 * The File Cleanup Utility gnatclean:: 
17193 * The GNAT Library Browser gnatls:: 
17194 * The Cross-Referencing Tools gnatxref and gnatfind:: 
17195 * The Ada to HTML Converter gnathtml:: 
17197 @end menu
17199 @node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
17200 @anchor{gnat_ugn/gnat_utility_programs id2}@anchor{145}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{20}
17201 @section The File Cleanup Utility @code{gnatclean}
17204 @geindex File cleanup tool
17206 @geindex gnatclean
17208 @code{gnatclean} is a tool that allows the deletion of files produced by the
17209 compiler, binder and linker, including ALI files, object files, tree files,
17210 expanded source files, library files, interface copy source files, binder
17211 generated files and executable files.
17213 @menu
17214 * Running gnatclean:: 
17215 * Switches for gnatclean:: 
17217 @end menu
17219 @node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
17220 @anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{146}@anchor{gnat_ugn/gnat_utility_programs id3}@anchor{147}
17221 @subsection Running @code{gnatclean}
17224 The @code{gnatclean} command has the form:
17226 @quotation
17228 @example
17229 $ gnatclean switches names
17230 @end example
17231 @end quotation
17233 where @code{names} is a list of source file names. Suffixes @code{.ads} and
17234 @code{adb} may be omitted. If a project file is specified using switch
17235 @code{-P}, then @code{names} may be completely omitted.
17237 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17238 if switch @code{-c} is not specified, by the binder and
17239 the linker. In informative-only mode, specified by switch
17240 @code{-n}, the list of files that would have been deleted in
17241 normal mode is listed, but no file is actually deleted.
17243 @node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
17244 @anchor{gnat_ugn/gnat_utility_programs id4}@anchor{148}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{149}
17245 @subsection Switches for @code{gnatclean}
17248 @code{gnatclean} recognizes the following switches:
17250 @geindex --version (gnatclean)
17253 @table @asis
17255 @item @code{--version}
17257 Display Copyright and version, then exit disregarding all other options.
17258 @end table
17260 @geindex --help (gnatclean)
17263 @table @asis
17265 @item @code{--help}
17267 If @code{--version} was not used, display usage, then exit disregarding
17268 all other options.
17270 @item @code{--subdirs=@emph{subdir}}
17272 Actual object directory of each project file is the subdirectory subdir of the
17273 object directory specified or defaulted in the project file.
17275 @item @code{--unchecked-shared-lib-imports}
17277 By default, shared library projects are not allowed to import static library
17278 projects. When this switch is used on the command line, this restriction is
17279 relaxed.
17280 @end table
17282 @geindex -c (gnatclean)
17285 @table @asis
17287 @item @code{-c}
17289 Only attempt to delete the files produced by the compiler, not those produced
17290 by the binder or the linker. The files that are not to be deleted are library
17291 files, interface copy files, binder generated files and executable files.
17292 @end table
17294 @geindex -D (gnatclean)
17297 @table @asis
17299 @item @code{-D @emph{dir}}
17301 Indicate that ALI and object files should normally be found in directory @code{dir}.
17302 @end table
17304 @geindex -F (gnatclean)
17307 @table @asis
17309 @item @code{-F}
17311 When using project files, if some errors or warnings are detected during
17312 parsing and verbose mode is not in effect (no use of switch
17313 -v), then error lines start with the full path name of the project
17314 file, rather than its simple file name.
17315 @end table
17317 @geindex -h (gnatclean)
17320 @table @asis
17322 @item @code{-h}
17324 Output a message explaining the usage of @code{gnatclean}.
17325 @end table
17327 @geindex -n (gnatclean)
17330 @table @asis
17332 @item @code{-n}
17334 Informative-only mode. Do not delete any files. Output the list of the files
17335 that would have been deleted if this switch was not specified.
17336 @end table
17338 @geindex -P (gnatclean)
17341 @table @asis
17343 @item @code{-P@emph{project}}
17345 Use project file @code{project}. Only one such switch can be used.
17346 When cleaning a project file, the files produced by the compilation of the
17347 immediate sources or inherited sources of the project files are to be
17348 deleted. This is not depending on the presence or not of executable names
17349 on the command line.
17350 @end table
17352 @geindex -q (gnatclean)
17355 @table @asis
17357 @item @code{-q}
17359 Quiet output. If there are no errors, do not output anything, except in
17360 verbose mode (switch -v) or in informative-only mode
17361 (switch -n).
17362 @end table
17364 @geindex -r (gnatclean)
17367 @table @asis
17369 @item @code{-r}
17371 When a project file is specified (using switch -P),
17372 clean all imported and extended project files, recursively. If this switch
17373 is not specified, only the files related to the main project file are to be
17374 deleted. This switch has no effect if no project file is specified.
17375 @end table
17377 @geindex -v (gnatclean)
17380 @table @asis
17382 @item @code{-v}
17384 Verbose mode.
17385 @end table
17387 @geindex -vP (gnatclean)
17390 @table @asis
17392 @item @code{-vP@emph{x}}
17394 Indicates the verbosity of the parsing of GNAT project files.
17395 @ref{de,,Switches Related to Project Files}.
17396 @end table
17398 @geindex -X (gnatclean)
17401 @table @asis
17403 @item @code{-X@emph{name}=@emph{value}}
17405 Indicates that external variable @code{name} has the value @code{value}.
17406 The Project Manager will use this value for occurrences of
17407 @code{external(name)} when parsing the project file.
17408 See @ref{de,,Switches Related to Project Files}.
17409 @end table
17411 @geindex -aO (gnatclean)
17414 @table @asis
17416 @item @code{-aO@emph{dir}}
17418 When searching for ALI and object files, look in directory @code{dir}.
17419 @end table
17421 @geindex -I (gnatclean)
17424 @table @asis
17426 @item @code{-I@emph{dir}}
17428 Equivalent to @code{-aO@emph{dir}}.
17429 @end table
17431 @geindex -I- (gnatclean)
17433 @geindex Source files
17434 @geindex suppressing search
17437 @table @asis
17439 @item @code{-I-}
17441 Do not look for ALI or object files in the directory
17442 where @code{gnatclean} was invoked.
17443 @end table
17445 @node The GNAT Library Browser gnatls,The Cross-Referencing Tools gnatxref and gnatfind,The File Cleanup Utility gnatclean,GNAT Utility Programs
17446 @anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{21}@anchor{gnat_ugn/gnat_utility_programs id5}@anchor{14a}
17447 @section The GNAT Library Browser @code{gnatls}
17450 @geindex Library browser
17452 @geindex gnatls
17454 @code{gnatls} is a tool that outputs information about compiled
17455 units. It gives the relationship between objects, unit names and source
17456 files. It can also be used to check the source dependencies of a unit
17457 as well as various characteristics.
17459 @menu
17460 * Running gnatls:: 
17461 * Switches for gnatls:: 
17462 * Example of gnatls Usage:: 
17464 @end menu
17466 @node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
17467 @anchor{gnat_ugn/gnat_utility_programs id6}@anchor{14b}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{14c}
17468 @subsection Running @code{gnatls}
17471 The @code{gnatls} command has the form
17473 @quotation
17475 @example
17476 $ gnatls switches object_or_ali_file
17477 @end example
17478 @end quotation
17480 The main argument is the list of object or @code{ali} files
17481 (see @ref{42,,The Ada Library Information Files})
17482 for which information is requested.
17484 In normal mode, without additional option, @code{gnatls} produces a
17485 four-column listing. Each line represents information for a specific
17486 object. The first column gives the full path of the object, the second
17487 column gives the name of the principal unit in this object, the third
17488 column gives the status of the source and the fourth column gives the
17489 full path of the source representing this unit.
17490 Here is a simple example of use:
17492 @quotation
17494 @example
17495 $ gnatls *.o
17496 ./demo1.o            demo1            DIF demo1.adb
17497 ./demo2.o            demo2             OK demo2.adb
17498 ./hello.o            h1                OK hello.adb
17499 ./instr-child.o      instr.child      MOK instr-child.adb
17500 ./instr.o            instr             OK instr.adb
17501 ./tef.o              tef              DIF tef.adb
17502 ./text_io_example.o  text_io_example   OK text_io_example.adb
17503 ./tgef.o             tgef             DIF tgef.adb
17504 @end example
17505 @end quotation
17507 The first line can be interpreted as follows: the main unit which is
17508 contained in
17509 object file @code{demo1.o} is demo1, whose main source is in
17510 @code{demo1.adb}. Furthermore, the version of the source used for the
17511 compilation of demo1 has been modified (DIF). Each source file has a status
17512 qualifier which can be:
17515 @table @asis
17517 @item @emph{OK (unchanged)}
17519 The version of the source file used for the compilation of the
17520 specified unit corresponds exactly to the actual source file.
17522 @item @emph{MOK (slightly modified)}
17524 The version of the source file used for the compilation of the
17525 specified unit differs from the actual source file but not enough to
17526 require recompilation. If you use gnatmake with the option
17527 @code{-m} (minimal recompilation), a file marked
17528 MOK will not be recompiled.
17530 @item @emph{DIF (modified)}
17532 No version of the source found on the path corresponds to the source
17533 used to build this object.
17535 @item @emph{??? (file not found)}
17537 No source file was found for this unit.
17539 @item @emph{HID (hidden,  unchanged version not first on PATH)}
17541 The version of the source that corresponds exactly to the source used
17542 for compilation has been found on the path but it is hidden by another
17543 version of the same source that has been modified.
17544 @end table
17546 @node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
17547 @anchor{gnat_ugn/gnat_utility_programs id7}@anchor{14d}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{14e}
17548 @subsection Switches for @code{gnatls}
17551 @code{gnatls} recognizes the following switches:
17553 @geindex --version (gnatls)
17556 @table @asis
17558 @item @code{--version}
17560 Display Copyright and version, then exit disregarding all other options.
17561 @end table
17563 @geindex --help (gnatls)
17566 @table @asis
17568 @item @code{--help}
17570 If @code{--version} was not used, display usage, then exit disregarding
17571 all other options.
17572 @end table
17574 @geindex -a (gnatls)
17577 @table @asis
17579 @item @code{-a}
17581 Consider all units, including those of the predefined Ada library.
17582 Especially useful with @code{-d}.
17583 @end table
17585 @geindex -d (gnatls)
17588 @table @asis
17590 @item @code{-d}
17592 List sources from which specified units depend on.
17593 @end table
17595 @geindex -h (gnatls)
17598 @table @asis
17600 @item @code{-h}
17602 Output the list of options.
17603 @end table
17605 @geindex -o (gnatls)
17608 @table @asis
17610 @item @code{-o}
17612 Only output information about object files.
17613 @end table
17615 @geindex -s (gnatls)
17618 @table @asis
17620 @item @code{-s}
17622 Only output information about source files.
17623 @end table
17625 @geindex -u (gnatls)
17628 @table @asis
17630 @item @code{-u}
17632 Only output information about compilation units.
17633 @end table
17635 @geindex -files (gnatls)
17638 @table @asis
17640 @item @code{-files=@emph{file}}
17642 Take as arguments the files listed in text file @code{file}.
17643 Text file @code{file} may contain empty lines that are ignored.
17644 Each nonempty line should contain the name of an existing file.
17645 Several such switches may be specified simultaneously.
17646 @end table
17648 @geindex -aO (gnatls)
17650 @geindex -aI (gnatls)
17652 @geindex -I (gnatls)
17654 @geindex -I- (gnatls)
17657 @table @asis
17659 @item @code{-aO@emph{dir}}, @code{-aI@emph{dir}}, @code{-I@emph{dir}}, @code{-I-}, @code{-nostdinc}
17661 Source path manipulation. Same meaning as the equivalent @code{gnatmake}
17662 flags (@ref{dc,,Switches for gnatmake}).
17663 @end table
17665 @geindex -aP (gnatls)
17668 @table @asis
17670 @item @code{-aP@emph{dir}}
17672 Add @code{dir} at the beginning of the project search dir.
17673 @end table
17675 @geindex --RTS (gnatls)
17678 @table @asis
17680 @item @code{--RTS=@emph{rts-path}}
17682 Specifies the default location of the runtime library. Same meaning as the
17683 equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
17684 @end table
17686 @geindex -v (gnatls)
17689 @table @asis
17691 @item @code{-v}
17693 Verbose mode. Output the complete source, object and project paths. Do not use
17694 the default column layout but instead use long format giving as much as
17695 information possible on each requested units, including special
17696 characteristics such as:
17699 @itemize *
17701 @item 
17702 @emph{Preelaborable}: The unit is preelaborable in the Ada sense.
17704 @item 
17705 @emph{No_Elab_Code}:  No elaboration code has been produced by the compiler for this unit.
17707 @item 
17708 @emph{Pure}: The unit is pure in the Ada sense.
17710 @item 
17711 @emph{Elaborate_Body}: The unit contains a pragma Elaborate_Body.
17713 @item 
17714 @emph{Remote_Types}: The unit contains a pragma Remote_Types.
17716 @item 
17717 @emph{Shared_Passive}: The unit contains a pragma Shared_Passive.
17719 @item 
17720 @emph{Predefined}: This unit is part of the predefined environment and cannot be modified
17721 by the user.
17723 @item 
17724 @emph{Remote_Call_Interface}: The unit contains a pragma Remote_Call_Interface.
17725 @end itemize
17726 @end table
17728 @node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
17729 @anchor{gnat_ugn/gnat_utility_programs id8}@anchor{14f}@anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{150}
17730 @subsection Example of @code{gnatls} Usage
17733 Example of using the verbose switch. Note how the source and
17734 object paths are affected by the -I switch.
17736 @quotation
17738 @example
17739 $ gnatls -v -I.. demo1.o
17741 GNATLS 5.03w (20041123-34)
17742 Copyright 1997-2004 Free Software Foundation, Inc.
17744 Source Search Path:
17745    <Current_Directory>
17746    ../
17747    /home/comar/local/adainclude/
17749 Object Search Path:
17750    <Current_Directory>
17751    ../
17752    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17754 Project Search Path:
17755    <Current_Directory>
17756    /home/comar/local/lib/gnat/
17758 ./demo1.o
17759    Unit =>
17760      Name   => demo1
17761      Kind   => subprogram body
17762      Flags  => No_Elab_Code
17763      Source => demo1.adb    modified
17764 @end example
17765 @end quotation
17767 The following is an example of use of the dependency list.
17768 Note the use of the -s switch
17769 which gives a straight list of source files. This can be useful for
17770 building specialized scripts.
17772 @quotation
17774 @example
17775 $ gnatls -d demo2.o
17776 ./demo2.o   demo2        OK demo2.adb
17777                          OK gen_list.ads
17778                          OK gen_list.adb
17779                          OK instr.ads
17780                          OK instr-child.ads
17782 $ gnatls -d -s -a demo1.o
17783 demo1.adb
17784 /home/comar/local/adainclude/ada.ads
17785 /home/comar/local/adainclude/a-finali.ads
17786 /home/comar/local/adainclude/a-filico.ads
17787 /home/comar/local/adainclude/a-stream.ads
17788 /home/comar/local/adainclude/a-tags.ads
17789 gen_list.ads
17790 gen_list.adb
17791 /home/comar/local/adainclude/gnat.ads
17792 /home/comar/local/adainclude/g-io.ads
17793 instr.ads
17794 /home/comar/local/adainclude/system.ads
17795 /home/comar/local/adainclude/s-exctab.ads
17796 /home/comar/local/adainclude/s-finimp.ads
17797 /home/comar/local/adainclude/s-finroo.ads
17798 /home/comar/local/adainclude/s-secsta.ads
17799 /home/comar/local/adainclude/s-stalib.ads
17800 /home/comar/local/adainclude/s-stoele.ads
17801 /home/comar/local/adainclude/s-stratt.ads
17802 /home/comar/local/adainclude/s-tasoli.ads
17803 /home/comar/local/adainclude/s-unstyp.ads
17804 /home/comar/local/adainclude/unchconv.ads
17805 @end example
17806 @end quotation
17808 @node The Cross-Referencing Tools gnatxref and gnatfind,The Ada to HTML Converter gnathtml,The GNAT Library Browser gnatls,GNAT Utility Programs
17809 @anchor{gnat_ugn/gnat_utility_programs the-cross-referencing-tools-gnatxref-and-gnatfind}@anchor{22}@anchor{gnat_ugn/gnat_utility_programs id9}@anchor{151}
17810 @section The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
17813 @geindex gnatxref
17815 @geindex gnatfind
17817 The compiler generates cross-referencing information (unless
17818 you set the @code{-gnatx} switch), which are saved in the @code{.ali} files.
17819 This information indicates where in the source each entity is declared and
17820 referenced. Note that entities in package Standard are not included, but
17821 entities in all other predefined units are included in the output.
17823 Before using any of these two tools, you need to compile successfully your
17824 application, so that GNAT gets a chance to generate the cross-referencing
17825 information.
17827 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
17828 information to provide the user with the capability to easily locate the
17829 declaration and references to an entity. These tools are quite similar,
17830 the difference being that @code{gnatfind} is intended for locating
17831 definitions and/or references to a specified entity or entities, whereas
17832 @code{gnatxref} is oriented to generating a full report of all
17833 cross-references.
17835 To use these tools, you must not compile your application using the
17836 @code{-gnatx} switch on the @code{gnatmake} command line
17837 (see @ref{1b,,Building with gnatmake}). Otherwise, cross-referencing
17838 information will not be generated.
17840 @menu
17841 * gnatxref Switches:: 
17842 * gnatfind Switches:: 
17843 * Configuration Files for gnatxref and gnatfind:: 
17844 * Regular Expressions in gnatfind and gnatxref:: 
17845 * Examples of gnatxref Usage:: 
17846 * Examples of gnatfind Usage:: 
17848 @end menu
17850 @node gnatxref Switches,gnatfind Switches,,The Cross-Referencing Tools gnatxref and gnatfind
17851 @anchor{gnat_ugn/gnat_utility_programs id10}@anchor{152}@anchor{gnat_ugn/gnat_utility_programs gnatxref-switches}@anchor{153}
17852 @subsection @code{gnatxref} Switches
17855 The command invocation for @code{gnatxref} is:
17857 @quotation
17859 @example
17860 $ gnatxref [ switches ] sourcefile1 [ sourcefile2 ... ]
17861 @end example
17862 @end quotation
17864 where
17867 @table @asis
17869 @item @code{sourcefile1} [, @code{sourcefile2} ...]
17871 identify the source files for which a report is to be generated. The
17872 @code{with}ed units will be processed too. You must provide at least one file.
17874 These file names are considered to be regular expressions, so for instance
17875 specifying @code{source*.adb} is the same as giving every file in the current
17876 directory whose name starts with @code{source} and whose extension is
17877 @code{adb}.
17879 You shouldn't specify any directory name, just base names. @code{gnatxref}
17880 and @code{gnatfind} will be able to locate these files by themselves using
17881 the source path. If you specify directories, no result is produced.
17882 @end table
17884 The following switches are available for @code{gnatxref}:
17886 @geindex --version (gnatxref)
17889 @table @asis
17891 @item @code{--version}
17893 Display Copyright and version, then exit disregarding all other options.
17894 @end table
17896 @geindex --help (gnatxref)
17899 @table @asis
17901 @item @code{--help}
17903 If @code{--version} was not used, display usage, then exit disregarding
17904 all other options.
17905 @end table
17907 @geindex -a (gnatxref)
17910 @table @asis
17912 @item @code{-a}
17914 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
17915 the read-only files found in the library search path. Otherwise, these files
17916 will be ignored. This option can be used to protect Gnat sources or your own
17917 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
17918 much faster, and their output much smaller. Read-only here refers to access
17919 or permissions status in the file system for the current user.
17920 @end table
17922 @geindex -aIDIR (gnatxref)
17925 @table @asis
17927 @item @code{-aI@emph{DIR}}
17929 When looking for source files also look in directory DIR. The order in which
17930 source file search is undertaken is the same as for @code{gnatmake}.
17931 @end table
17933 @geindex -aODIR (gnatxref)
17936 @table @asis
17938 @item @code{aO@emph{DIR}}
17940 When -searching for library and object files, look in directory
17941 DIR. The order in which library files are searched is the same as for
17942 @code{gnatmake}.
17943 @end table
17945 @geindex -nostdinc (gnatxref)
17948 @table @asis
17950 @item @code{-nostdinc}
17952 Do not look for sources in the system default directory.
17953 @end table
17955 @geindex -nostdlib (gnatxref)
17958 @table @asis
17960 @item @code{-nostdlib}
17962 Do not look for library files in the system default directory.
17963 @end table
17965 @geindex --ext (gnatxref)
17968 @table @asis
17970 @item @code{--ext=@emph{extension}}
17972 Specify an alternate ali file extension. The default is @code{ali} and other
17973 extensions (e.g. @code{gli} for C/C++ sources) may be specified via this switch.
17974 Note that if this switch overrides the default, only the new extension will
17975 be considered.
17976 @end table
17978 @geindex --RTS (gnatxref)
17981 @table @asis
17983 @item @code{--RTS=@emph{rts-path}}
17985 Specifies the default location of the runtime library. Same meaning as the
17986 equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
17987 @end table
17989 @geindex -d (gnatxref)
17992 @table @asis
17994 @item @code{-d}
17996 If this switch is set @code{gnatxref} will output the parent type
17997 reference for each matching derived types.
17998 @end table
18000 @geindex -f (gnatxref)
18003 @table @asis
18005 @item @code{-f}
18007 If this switch is set, the output file names will be preceded by their
18008 directory (if the file was found in the search path). If this switch is
18009 not set, the directory will not be printed.
18010 @end table
18012 @geindex -g (gnatxref)
18015 @table @asis
18017 @item @code{-g}
18019 If this switch is set, information is output only for library-level
18020 entities, ignoring local entities. The use of this switch may accelerate
18021 @code{gnatfind} and @code{gnatxref}.
18022 @end table
18024 @geindex -IDIR (gnatxref)
18027 @table @asis
18029 @item @code{-I@emph{DIR}}
18031 Equivalent to @code{-aODIR -aIDIR}.
18032 @end table
18034 @geindex -pFILE (gnatxref)
18037 @table @asis
18039 @item @code{-p@emph{FILE}}
18041 Specify a configuration file to use to list the source and object directories.
18043 If a file is specified, then the content of the source directory and object
18044 directory lines are added as if they had been specified respectively
18045 by @code{-aI} and @code{-aO}.
18047 See @ref{154,,Configuration Files for gnatxref and gnatfind} for the syntax
18048 of this configuration file.
18050 @item @code{-u}
18052 Output only unused symbols. This may be really useful if you give your
18053 main compilation unit on the command line, as @code{gnatxref} will then
18054 display every unused entity and 'with'ed package.
18056 @item @code{-v}
18058 Instead of producing the default output, @code{gnatxref} will generate a
18059 @code{tags} file that can be used by vi. For examples how to use this
18060 feature, see @ref{155,,Examples of gnatxref Usage}. The tags file is output
18061 to the standard output, thus you will have to redirect it to a file.
18062 @end table
18064 All these switches may be in any order on the command line, and may even
18065 appear after the file names. They need not be separated by spaces, thus
18066 you can say @code{gnatxref -ag} instead of @code{gnatxref -a -g}.
18068 @node gnatfind Switches,Configuration Files for gnatxref and gnatfind,gnatxref Switches,The Cross-Referencing Tools gnatxref and gnatfind
18069 @anchor{gnat_ugn/gnat_utility_programs id11}@anchor{156}@anchor{gnat_ugn/gnat_utility_programs gnatfind-switches}@anchor{157}
18070 @subsection @code{gnatfind} Switches
18073 The command invocation for @code{gnatfind} is:
18075 @quotation
18077 @example
18078 $ gnatfind [ switches ]  pattern[:sourcefile[:line[:column]]]
18079       [file1 file2 ...]
18080 @end example
18081 @end quotation
18083 with the following iterpretation of the command arguments:
18086 @table @asis
18088 @item @emph{pattern}
18090 An entity will be output only if it matches the regular expression found
18091 in @emph{pattern}, see @ref{158,,Regular Expressions in gnatfind and gnatxref}.
18093 Omitting the pattern is equivalent to specifying @code{*}, which
18094 will match any entity. Note that if you do not provide a pattern, you
18095 have to provide both a sourcefile and a line.
18097 Entity names are given in Latin-1, with uppercase/lowercase equivalence
18098 for matching purposes. At the current time there is no support for
18099 8-bit codes other than Latin-1, or for wide characters in identifiers.
18101 @item @emph{sourcefile}
18103 @code{gnatfind} will look for references, bodies or declarations
18104 of symbols referenced in @code{sourcefile}, at line @code{line}
18105 and column @code{column}. See @ref{159,,Examples of gnatfind Usage}
18106 for syntax examples.
18108 @item @emph{line}
18110 A decimal integer identifying the line number containing
18111 the reference to the entity (or entities) to be located.
18113 @item @emph{column}
18115 A decimal integer identifying the exact location on the
18116 line of the first character of the identifier for the
18117 entity reference. Columns are numbered from 1.
18119 @item @emph{file1 file2 ...}
18121 The search will be restricted to these source files. If none are given, then
18122 the search will be conducted for every library file in the search path.
18123 These files must appear only after the pattern or sourcefile.
18125 These file names are considered to be regular expressions, so for instance
18126 specifying @code{source*.adb} is the same as giving every file in the current
18127 directory whose name starts with @code{source} and whose extension is
18128 @code{adb}.
18130 The location of the spec of the entity will always be displayed, even if it
18131 isn't in one of @code{file1}, @code{file2}, ... The
18132 occurrences of the entity in the separate units of the ones given on the
18133 command line will also be displayed.
18135 Note that if you specify at least one file in this part, @code{gnatfind} may
18136 sometimes not be able to find the body of the subprograms.
18137 @end table
18139 At least one of 'sourcefile' or 'pattern' has to be present on
18140 the command line.
18142 The following switches are available:
18144 @geindex --version (gnatfind)
18147 @table @asis
18149 @item @code{--version}
18151 Display Copyright and version, then exit disregarding all other options.
18152 @end table
18154 @geindex --help (gnatfind)
18157 @table @asis
18159 @item @code{--help}
18161 If @code{--version} was not used, display usage, then exit disregarding
18162 all other options.
18163 @end table
18165 @geindex -a (gnatfind)
18168 @table @asis
18170 @item @code{-a}
18172 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
18173 the read-only files found in the library search path. Otherwise, these files
18174 will be ignored. This option can be used to protect Gnat sources or your own
18175 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
18176 much faster, and their output much smaller. Read-only here refers to access
18177 or permission status in the file system for the current user.
18178 @end table
18180 @geindex -aIDIR (gnatfind)
18183 @table @asis
18185 @item @code{-aI@emph{DIR}}
18187 When looking for source files also look in directory DIR. The order in which
18188 source file search is undertaken is the same as for @code{gnatmake}.
18189 @end table
18191 @geindex -aODIR (gnatfind)
18194 @table @asis
18196 @item @code{-aO@emph{DIR}}
18198 When searching for library and object files, look in directory
18199 DIR. The order in which library files are searched is the same as for
18200 @code{gnatmake}.
18201 @end table
18203 @geindex -nostdinc (gnatfind)
18206 @table @asis
18208 @item @code{-nostdinc}
18210 Do not look for sources in the system default directory.
18211 @end table
18213 @geindex -nostdlib (gnatfind)
18216 @table @asis
18218 @item @code{-nostdlib}
18220 Do not look for library files in the system default directory.
18221 @end table
18223 @geindex --ext (gnatfind)
18226 @table @asis
18228 @item @code{--ext=@emph{extension}}
18230 Specify an alternate ali file extension. The default is @code{ali} and other
18231 extensions may be specified via this switch. Note that if this switch
18232 overrides the default, only the new extension will be considered.
18233 @end table
18235 @geindex --RTS (gnatfind)
18238 @table @asis
18240 @item @code{--RTS=@emph{rts-path}}
18242 Specifies the default location of the runtime library. Same meaning as the
18243 equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
18244 @end table
18246 @geindex -d (gnatfind)
18249 @table @asis
18251 @item @code{-d}
18253 If this switch is set, then @code{gnatfind} will output the parent type
18254 reference for each matching derived types.
18255 @end table
18257 @geindex -e (gnatfind)
18260 @table @asis
18262 @item @code{-e}
18264 By default, @code{gnatfind} accept the simple regular expression set for
18265 @code{pattern}. If this switch is set, then the pattern will be
18266 considered as full Unix-style regular expression.
18267 @end table
18269 @geindex -f (gnatfind)
18272 @table @asis
18274 @item @code{-f}
18276 If this switch is set, the output file names will be preceded by their
18277 directory (if the file was found in the search path). If this switch is
18278 not set, the directory will not be printed.
18279 @end table
18281 @geindex -g (gnatfind)
18284 @table @asis
18286 @item @code{-g}
18288 If this switch is set, information is output only for library-level
18289 entities, ignoring local entities. The use of this switch may accelerate
18290 @code{gnatfind} and @code{gnatxref}.
18291 @end table
18293 @geindex -IDIR (gnatfind)
18296 @table @asis
18298 @item @code{-I@emph{DIR}}
18300 Equivalent to @code{-aODIR -aIDIR}.
18301 @end table
18303 @geindex -pFILE (gnatfind)
18306 @table @asis
18308 @item @code{-p@emph{FILE}}
18310 Specify a configuration file to use to list the source and object directories.
18312 If a file is specified, then the content of the source directory and object
18313 directory lines are added as if they had been specified respectively
18314 by @code{-aI} and @code{-aO}.
18316 See @ref{154,,Configuration Files for gnatxref and gnatfind} for the syntax
18317 of this configuration file.
18318 @end table
18320 @geindex -r (gnatfind)
18323 @table @asis
18325 @item @code{-r}
18327 By default, @code{gnatfind} will output only the information about the
18328 declaration, body or type completion of the entities. If this switch is
18329 set, the @code{gnatfind} will locate every reference to the entities in
18330 the files specified on the command line (or in every file in the search
18331 path if no file is given on the command line).
18332 @end table
18334 @geindex -s (gnatfind)
18337 @table @asis
18339 @item @code{-s}
18341 If this switch is set, then @code{gnatfind} will output the content
18342 of the Ada source file lines were the entity was found.
18343 @end table
18345 @geindex -t (gnatfind)
18348 @table @asis
18350 @item @code{-t}
18352 If this switch is set, then @code{gnatfind} will output the type hierarchy for
18353 the specified type. It act like -d option but recursively from parent
18354 type to parent type. When this switch is set it is not possible to
18355 specify more than one file.
18356 @end table
18358 All these switches may be in any order on the command line, and may even
18359 appear after the file names. They need not be separated by spaces, thus
18360 you can say @code{gnatxref -ag} instead of
18361 @code{gnatxref -a -g}.
18363 As stated previously, @code{gnatfind} will search in every directory in the
18364 search path. You can force it to look only in the current directory if
18365 you specify @code{*} at the end of the command line.
18367 @node Configuration Files for gnatxref and gnatfind,Regular Expressions in gnatfind and gnatxref,gnatfind Switches,The Cross-Referencing Tools gnatxref and gnatfind
18368 @anchor{gnat_ugn/gnat_utility_programs configuration-files-for-gnatxref-and-gnatfind}@anchor{154}@anchor{gnat_ugn/gnat_utility_programs id12}@anchor{15a}
18369 @subsection Configuration Files for @code{gnatxref} and @code{gnatfind}
18372 Configuration files are used by @code{gnatxref} and @code{gnatfind} to specify
18373 the list of source and object directories to consider. They can be
18374 specified via the @code{-p} switch.
18376 The following lines can be included, in any order in the file:
18379 @itemize *
18381 @item 
18383 @table @asis
18385 @item @emph{src_dir=DIR}
18387 [default: @code{"./"}].
18388 Specifies a directory where to look for source files. Multiple @code{src_dir}
18389 lines can be specified and they will be searched in the order they
18390 are specified.
18391 @end table
18393 @item 
18395 @table @asis
18397 @item @emph{obj_dir=DIR}
18399 [default: @code{"./"}].
18400 Specifies a directory where to look for object and library files. Multiple
18401 @code{obj_dir} lines can be specified, and they will be searched in the order
18402 they are specified
18403 @end table
18404 @end itemize
18406 Any other line will be silently ignored.
18408 @node Regular Expressions in gnatfind and gnatxref,Examples of gnatxref Usage,Configuration Files for gnatxref and gnatfind,The Cross-Referencing Tools gnatxref and gnatfind
18409 @anchor{gnat_ugn/gnat_utility_programs id13}@anchor{15b}@anchor{gnat_ugn/gnat_utility_programs regular-expressions-in-gnatfind-and-gnatxref}@anchor{158}
18410 @subsection Regular Expressions in @code{gnatfind} and @code{gnatxref}
18413 As specified in the section about @code{gnatfind}, the pattern can be a
18414 regular expression. Two kinds of regular expressions
18415 are recognized:
18418 @itemize *
18420 @item 
18422 @table @asis
18424 @item @emph{Globbing pattern}
18426 These are the most common regular expression. They are the same as are
18427 generally used in a Unix shell command line, or in a DOS session.
18429 Here is a more formal grammar:
18431 @example
18432 regexp ::= term
18433 term   ::= elmt            -- matches elmt
18434 term   ::= elmt elmt       -- concatenation (elmt then elmt)
18435 term   ::= *               -- any string of 0 or more characters
18436 term   ::= ?               -- matches any character
18437 term   ::= [char @{char@}]   -- matches any character listed
18438 term   ::= [char - char]   -- matches any character in range
18439 @end example
18440 @end table
18442 @item 
18444 @table @asis
18446 @item @emph{Full regular expression}
18448 The second set of regular expressions is much more powerful. This is the
18449 type of regular expressions recognized by utilities such as @code{grep}.
18451 The following is the form of a regular expression, expressed in same BNF
18452 style as is found in the Ada Reference Manual:
18454 @example
18455 regexp ::= term @{| term@}   -- alternation (term or term ...)
18457 term ::= item @{item@}       -- concatenation (item then item)
18459 item ::= elmt              -- match elmt
18460 item ::= elmt *            -- zero or more elmt's
18461 item ::= elmt +            -- one or more elmt's
18462 item ::= elmt ?            -- matches elmt or nothing
18464 elmt ::= nschar            -- matches given character
18465 elmt ::= [nschar @{nschar@}]   -- matches any character listed
18466 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
18467 elmt ::= [char - char]     -- matches chars in given range
18468 elmt ::= \\ char            -- matches given character
18469 elmt ::= .                 -- matches any single character
18470 elmt ::= ( regexp )        -- parens used for grouping
18472 char ::= any character, including special characters
18473 nschar ::= any character except ()[].*+?^
18474 @end example
18476 Here are a few examples:
18478 @quotation
18481 @table @asis
18483 @item @code{abcde|fghi}
18485 will match any of the two strings @code{abcde} and @code{fghi},
18487 @item @code{abc*d}
18489 will match any string like @code{abd}, @code{abcd}, @code{abccd},
18490 @code{abcccd}, and so on,
18492 @item @code{[a-z]+}
18494 will match any string which has only lowercase characters in it (and at
18495 least one character.
18496 @end table
18497 @end quotation
18498 @end table
18499 @end itemize
18501 @node Examples of gnatxref Usage,Examples of gnatfind Usage,Regular Expressions in gnatfind and gnatxref,The Cross-Referencing Tools gnatxref and gnatfind
18502 @anchor{gnat_ugn/gnat_utility_programs examples-of-gnatxref-usage}@anchor{155}@anchor{gnat_ugn/gnat_utility_programs id14}@anchor{15c}
18503 @subsection Examples of @code{gnatxref} Usage
18506 @menu
18507 * General Usage:: 
18508 * Using gnatxref with vi:: 
18510 @end menu
18512 @node General Usage,Using gnatxref with vi,,Examples of gnatxref Usage
18513 @anchor{gnat_ugn/gnat_utility_programs general-usage}@anchor{15d}
18514 @subsubsection General Usage
18517 For the following examples, we will consider the following units:
18519 @quotation
18521 @example
18522 main.ads:
18523 1: with Bar;
18524 2: package Main is
18525 3:     procedure Foo (B : in Integer);
18526 4:     C : Integer;
18527 5: private
18528 6:     D : Integer;
18529 7: end Main;
18531 main.adb:
18532 1: package body Main is
18533 2:     procedure Foo (B : in Integer) is
18534 3:     begin
18535 4:        C := B;
18536 5:        D := B;
18537 6:        Bar.Print (B);
18538 7:        Bar.Print (C);
18539 8:     end Foo;
18540 9: end Main;
18542 bar.ads:
18543 1: package Bar is
18544 2:     procedure Print (B : Integer);
18545 3: end bar;
18546 @end example
18547 @end quotation
18549 The first thing to do is to recompile your application (for instance, in
18550 that case just by doing a @code{gnatmake main}, so that GNAT generates
18551 the cross-referencing information.
18552 You can then issue any of the following commands:
18554 @quotation
18557 @itemize *
18559 @item 
18560 @code{gnatxref main.adb}
18561 @code{gnatxref} generates cross-reference information for main.adb
18562 and every unit 'with'ed by main.adb.
18564 The output would be:
18566 @quotation
18568 @example
18569 B                                                      Type: Integer
18570   Decl: bar.ads           2:22
18571 B                                                      Type: Integer
18572   Decl: main.ads          3:20
18573   Body: main.adb          2:20
18574   Ref:  main.adb          4:13     5:13     6:19
18575 Bar                                                    Type: Unit
18576   Decl: bar.ads           1:9
18577   Ref:  main.adb          6:8      7:8
18578        main.ads           1:6
18579 C                                                      Type: Integer
18580   Decl: main.ads          4:5
18581   Modi: main.adb          4:8
18582   Ref:  main.adb          7:19
18583 D                                                      Type: Integer
18584   Decl: main.ads          6:5
18585   Modi: main.adb          5:8
18586 Foo                                                    Type: Unit
18587   Decl: main.ads          3:15
18588   Body: main.adb          2:15
18589 Main                                                    Type: Unit
18590   Decl: main.ads          2:9
18591   Body: main.adb          1:14
18592 Print                                                   Type: Unit
18593   Decl: bar.ads           2:15
18594   Ref:  main.adb          6:12     7:12
18595 @end example
18596 @end quotation
18598 This shows that the entity @code{Main} is declared in main.ads, line 2, column 9,
18599 its body is in main.adb, line 1, column 14 and is not referenced any where.
18601 The entity @code{Print} is declared in @code{bar.ads}, line 2, column 15 and it
18602 is referenced in @code{main.adb}, line 6 column 12 and line 7 column 12.
18604 @item 
18605 @code{gnatxref package1.adb package2.ads}
18606 @code{gnatxref} will generates cross-reference information for
18607 @code{package1.adb}, @code{package2.ads} and any other package @code{with}ed by any
18608 of these.
18609 @end itemize
18610 @end quotation
18612 @node Using gnatxref with vi,,General Usage,Examples of gnatxref Usage
18613 @anchor{gnat_ugn/gnat_utility_programs using-gnatxref-with-vi}@anchor{15e}
18614 @subsubsection Using @code{gnatxref} with @code{vi}
18617 @code{gnatxref} can generate a tags file output, which can be used
18618 directly from @code{vi}. Note that the standard version of @code{vi}
18619 will not work properly with overloaded symbols. Consider using another
18620 free implementation of @code{vi}, such as @code{vim}.
18622 @quotation
18624 @example
18625 $ gnatxref -v gnatfind.adb > tags
18626 @end example
18627 @end quotation
18629 The following command will generate the tags file for @code{gnatfind} itself
18630 (if the sources are in the search path!):
18632 @quotation
18634 @example
18635 $ gnatxref -v gnatfind.adb > tags
18636 @end example
18637 @end quotation
18639 From @code{vi}, you can then use the command @code{:tag @emph{entity}}
18640 (replacing @code{entity} by whatever you are looking for), and vi will
18641 display a new file with the corresponding declaration of entity.
18643 @node Examples of gnatfind Usage,,Examples of gnatxref Usage,The Cross-Referencing Tools gnatxref and gnatfind
18644 @anchor{gnat_ugn/gnat_utility_programs id15}@anchor{15f}@anchor{gnat_ugn/gnat_utility_programs examples-of-gnatfind-usage}@anchor{159}
18645 @subsection Examples of @code{gnatfind} Usage
18649 @itemize *
18651 @item 
18652 @code{gnatfind -f xyz:main.adb}
18653 Find declarations for all entities xyz referenced at least once in
18654 main.adb. The references are search in every library file in the search
18655 path.
18657 The directories will be printed as well (as the @code{-f}
18658 switch is set)
18660 The output will look like:
18662 @quotation
18664 @example
18665 directory/main.ads:106:14: xyz <= declaration
18666 directory/main.adb:24:10: xyz <= body
18667 directory/foo.ads:45:23: xyz <= declaration
18668 @end example
18669 @end quotation
18671 I.e., one of the entities xyz found in main.adb is declared at
18672 line 12 of main.ads (and its body is in main.adb), and another one is
18673 declared at line 45 of foo.ads
18675 @item 
18676 @code{gnatfind -fs xyz:main.adb}
18677 This is the same command as the previous one, but @code{gnatfind} will
18678 display the content of the Ada source file lines.
18680 The output will look like:
18682 @example
18683 directory/main.ads:106:14: xyz <= declaration
18684    procedure xyz;
18685 directory/main.adb:24:10: xyz <= body
18686    procedure xyz is
18687 directory/foo.ads:45:23: xyz <= declaration
18688    xyz : Integer;
18689 @end example
18691 This can make it easier to find exactly the location your are looking
18692 for.
18694 @item 
18695 @code{gnatfind -r "*x*":main.ads:123 foo.adb}
18696 Find references to all entities containing an x that are
18697 referenced on line 123 of main.ads.
18698 The references will be searched only in main.ads and foo.adb.
18700 @item 
18701 @code{gnatfind main.ads:123}
18702 Find declarations and bodies for all entities that are referenced on
18703 line 123 of main.ads.
18705 This is the same as @code{gnatfind "*":main.adb:123`}
18707 @item 
18708 @code{gnatfind mydir/main.adb:123:45}
18709 Find the declaration for the entity referenced at column 45 in
18710 line 123 of file main.adb in directory mydir. Note that it
18711 is usual to omit the identifier name when the column is given,
18712 since the column position identifies a unique reference.
18714 The column has to be the beginning of the identifier, and should not
18715 point to any character in the middle of the identifier.
18716 @end itemize
18718 @node The Ada to HTML Converter gnathtml,,The Cross-Referencing Tools gnatxref and gnatfind,GNAT Utility Programs
18719 @anchor{gnat_ugn/gnat_utility_programs the-ada-to-html-converter-gnathtml}@anchor{23}@anchor{gnat_ugn/gnat_utility_programs id16}@anchor{160}
18720 @section The Ada to HTML Converter @code{gnathtml}
18723 @geindex gnathtml
18725 @code{gnathtml} is a Perl script that allows Ada source files to be browsed using
18726 standard Web browsers. For installation information, see @ref{161,,Installing gnathtml}.
18728 Ada reserved keywords are highlighted in a bold font and Ada comments in
18729 a blue font. Unless your program was compiled with the gcc @code{-gnatx}
18730 switch to suppress the generation of cross-referencing information, user
18731 defined variables and types will appear in a different color; you will
18732 be able to click on any identifier and go to its declaration.
18734 @menu
18735 * Invoking gnathtml:: 
18736 * Installing gnathtml:: 
18738 @end menu
18740 @node Invoking gnathtml,Installing gnathtml,,The Ada to HTML Converter gnathtml
18741 @anchor{gnat_ugn/gnat_utility_programs invoking-gnathtml}@anchor{162}@anchor{gnat_ugn/gnat_utility_programs id17}@anchor{163}
18742 @subsection Invoking @code{gnathtml}
18745 The command line is as follows:
18747 @quotation
18749 @example
18750 $ perl gnathtml.pl [ switches ] ada-files
18751 @end example
18752 @end quotation
18754 You can specify as many Ada files as you want. @code{gnathtml} will generate
18755 an html file for every ada file, and a global file called @code{index.htm}.
18756 This file is an index of every identifier defined in the files.
18758 The following switches are available:
18760 @geindex -83 (gnathtml)
18763 @table @asis
18765 @item @code{83}
18767 Only the Ada 83 subset of keywords will be highlighted.
18768 @end table
18770 @geindex -cc (gnathtml)
18773 @table @asis
18775 @item @code{cc @emph{color}}
18777 This option allows you to change the color used for comments. The default
18778 value is green. The color argument can be any name accepted by html.
18779 @end table
18781 @geindex -d (gnathtml)
18784 @table @asis
18786 @item @code{d}
18788 If the Ada files depend on some other files (for instance through
18789 @code{with} clauses, the latter files will also be converted to html.
18790 Only the files in the user project will be converted to html, not the files
18791 in the run-time library itself.
18792 @end table
18794 @geindex -D (gnathtml)
18797 @table @asis
18799 @item @code{D}
18801 This command is the same as @code{-d} above, but @code{gnathtml} will
18802 also look for files in the run-time library, and generate html files for them.
18803 @end table
18805 @geindex -ext (gnathtml)
18808 @table @asis
18810 @item @code{ext @emph{extension}}
18812 This option allows you to change the extension of the generated HTML files.
18813 If you do not specify an extension, it will default to @code{htm}.
18814 @end table
18816 @geindex -f (gnathtml)
18819 @table @asis
18821 @item @code{f}
18823 By default, gnathtml will generate html links only for global entities
18824 ('with'ed units, global variables and types,...).  If you specify
18825 @code{-f} on the command line, then links will be generated for local
18826 entities too.
18827 @end table
18829 @geindex -l (gnathtml)
18832 @table @asis
18834 @item @code{l @emph{number}}
18836 If this switch is provided and @code{number} is not 0, then
18837 @code{gnathtml} will number the html files every @code{number} line.
18838 @end table
18840 @geindex -I (gnathtml)
18843 @table @asis
18845 @item @code{I @emph{dir}}
18847 Specify a directory to search for library files (@code{.ALI} files) and
18848 source files. You can provide several -I switches on the command line,
18849 and the directories will be parsed in the order of the command line.
18850 @end table
18852 @geindex -o (gnathtml)
18855 @table @asis
18857 @item @code{o @emph{dir}}
18859 Specify the output directory for html files. By default, gnathtml will
18860 saved the generated html files in a subdirectory named @code{html/}.
18861 @end table
18863 @geindex -p (gnathtml)
18866 @table @asis
18868 @item @code{p @emph{file}}
18870 If you are using Emacs and the most recent Emacs Ada mode, which provides
18871 a full Integrated Development Environment for compiling, checking,
18872 running and debugging applications, you may use @code{.gpr} files
18873 to give the directories where Emacs can find sources and object files.
18875 Using this switch, you can tell gnathtml to use these files.
18876 This allows you to get an html version of your application, even if it
18877 is spread over multiple directories.
18878 @end table
18880 @geindex -sc (gnathtml)
18883 @table @asis
18885 @item @code{sc @emph{color}}
18887 This switch allows you to change the color used for symbol
18888 definitions.
18889 The default value is red. The color argument can be any name accepted by html.
18890 @end table
18892 @geindex -t (gnathtml)
18895 @table @asis
18897 @item @code{t @emph{file}}
18899 This switch provides the name of a file. This file contains a list of
18900 file names to be converted, and the effect is exactly as though they had
18901 appeared explicitly on the command line. This
18902 is the recommended way to work around the command line length limit on some
18903 systems.
18904 @end table
18906 @node Installing gnathtml,,Invoking gnathtml,The Ada to HTML Converter gnathtml
18907 @anchor{gnat_ugn/gnat_utility_programs installing-gnathtml}@anchor{161}@anchor{gnat_ugn/gnat_utility_programs id18}@anchor{164}
18908 @subsection Installing @code{gnathtml}
18911 @code{Perl} needs to be installed on your machine to run this script.
18912 @code{Perl} is freely available for almost every architecture and
18913 operating system via the Internet.
18915 On Unix systems, you  may want to modify  the  first line of  the script
18916 @code{gnathtml},  to explicitly  specify  where Perl
18917 is located. The syntax of this line is:
18919 @quotation
18921 @example
18922 #!full_path_name_to_perl
18923 @end example
18924 @end quotation
18926 Alternatively, you may run the script using the following command line:
18928 @quotation
18930 @example
18931 $ perl gnathtml.pl [ switches ] files
18932 @end example
18933 @end quotation
18935 @c -- +---------------------------------------------------------------------+
18937 @c -- | The following sections are present only in the PRO and GPL editions |
18939 @c -- +---------------------------------------------------------------------+
18949 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
18951 @node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
18952 @anchor{gnat_ugn/gnat_and_program_execution gnat-and-program-execution}@anchor{c}@anchor{gnat_ugn/gnat_and_program_execution doc}@anchor{165}@anchor{gnat_ugn/gnat_and_program_execution id1}@anchor{166}
18953 @chapter GNAT and Program Execution
18956 This chapter covers several topics:
18959 @itemize *
18961 @item 
18962 @ref{167,,Running and Debugging Ada Programs}
18964 @item 
18965 @ref{168,,Code Coverage and Profiling}
18967 @item 
18968 @ref{169,,Improving Performance}
18970 @item 
18971 @ref{16a,,Overflow Check Handling in GNAT}
18973 @item 
18974 @ref{16b,,Performing Dimensionality Analysis in GNAT}
18976 @item 
18977 @ref{16c,,Stack Related Facilities}
18979 @item 
18980 @ref{16d,,Memory Management Issues}
18981 @end itemize
18983 @menu
18984 * Running and Debugging Ada Programs:: 
18985 * Code Coverage and Profiling:: 
18986 * Improving Performance:: 
18987 * Overflow Check Handling in GNAT:: 
18988 * Performing Dimensionality Analysis in GNAT:: 
18989 * Stack Related Facilities:: 
18990 * Memory Management Issues:: 
18992 @end menu
18994 @node Running and Debugging Ada Programs,Code Coverage and Profiling,,GNAT and Program Execution
18995 @anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{167}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{24}
18996 @section Running and Debugging Ada Programs
18999 @geindex Debugging
19001 This section discusses how to debug Ada programs.
19003 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19006 @itemize *
19008 @item 
19009 The illegality may be a violation of the static semantics of Ada. In
19010 that case GNAT diagnoses the constructs in the program that are illegal.
19011 It is then a straightforward matter for the user to modify those parts of
19012 the program.
19014 @item 
19015 The illegality may be a violation of the dynamic semantics of Ada. In
19016 that case the program compiles and executes, but may generate incorrect
19017 results, or may terminate abnormally with some exception.
19019 @item 
19020 When presented with a program that contains convoluted errors, GNAT
19021 itself may terminate abnormally without providing full diagnostics on
19022 the incorrect user program.
19023 @end itemize
19025 @geindex Debugger
19027 @geindex gdb
19029 @menu
19030 * The GNAT Debugger GDB:: 
19031 * Running GDB:: 
19032 * Introduction to GDB Commands:: 
19033 * Using Ada Expressions:: 
19034 * Calling User-Defined Subprograms:: 
19035 * Using the next Command in a Function:: 
19036 * Stopping When Ada Exceptions Are Raised:: 
19037 * Ada Tasks:: 
19038 * Debugging Generic Units:: 
19039 * Remote Debugging with gdbserver:: 
19040 * GNAT Abnormal Termination or Failure to Terminate:: 
19041 * Naming Conventions for GNAT Source Files:: 
19042 * Getting Internal Debugging Information:: 
19043 * Stack Traceback:: 
19044 * Pretty-Printers for the GNAT runtime:: 
19046 @end menu
19048 @node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
19049 @anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{16e}@anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{16f}
19050 @subsection The GNAT Debugger GDB
19053 @code{GDB} is a general purpose, platform-independent debugger that
19054 can be used to debug mixed-language programs compiled with @code{gcc},
19055 and in particular is capable of debugging Ada programs compiled with
19056 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19057 complex Ada data structures.
19059 See @cite{Debugging with GDB},
19060 for full details on the usage of @code{GDB}, including a section on
19061 its usage on programs. This manual should be consulted for full
19062 details. The section that follows is a brief introduction to the
19063 philosophy and use of @code{GDB}.
19065 When GNAT programs are compiled, the compiler optionally writes debugging
19066 information into the generated object file, including information on
19067 line numbers, and on declared types and variables. This information is
19068 separate from the generated code. It makes the object files considerably
19069 larger, but it does not add to the size of the actual executable that
19070 will be loaded into memory, and has no impact on run-time performance. The
19071 generation of debug information is triggered by the use of the
19072 @code{-g} switch in the @code{gcc} or @code{gnatmake} command
19073 used to carry out the compilations. It is important to emphasize that
19074 the use of these options does not change the generated code.
19076 The debugging information is written in standard system formats that
19077 are used by many tools, including debuggers and profilers. The format
19078 of the information is typically designed to describe C types and
19079 semantics, but GNAT implements a translation scheme which allows full
19080 details about Ada types and variables to be encoded into these
19081 standard C formats. Details of this encoding scheme may be found in
19082 the file exp_dbug.ads in the GNAT source distribution. However, the
19083 details of this encoding are, in general, of no interest to a user,
19084 since @code{GDB} automatically performs the necessary decoding.
19086 When a program is bound and linked, the debugging information is
19087 collected from the object files, and stored in the executable image of
19088 the program. Again, this process significantly increases the size of
19089 the generated executable file, but it does not increase the size of
19090 the executable program itself. Furthermore, if this program is run in
19091 the normal manner, it runs exactly as if the debug information were
19092 not present, and takes no more actual memory.
19094 However, if the program is run under control of @code{GDB}, the
19095 debugger is activated.  The image of the program is loaded, at which
19096 point it is ready to run.  If a run command is given, then the program
19097 will run exactly as it would have if @code{GDB} were not present. This
19098 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19099 entirely non-intrusive until a breakpoint is encountered.  If no
19100 breakpoint is ever hit, the program will run exactly as it would if no
19101 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19102 the debugging information and can respond to user commands to inspect
19103 variables, and more generally to report on the state of execution.
19105 @node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
19106 @anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{170}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{171}
19107 @subsection Running GDB
19110 This section describes how to initiate the debugger.
19112 The debugger can be launched from a @code{GPS} menu or
19113 directly from the command line. The description below covers the latter use.
19114 All the commands shown can be used in the @code{GPS} debug console window,
19115 but there are usually more GUI-based ways to achieve the same effect.
19117 The command to run @code{GDB} is
19119 @quotation
19121 @example
19122 $ gdb program
19123 @end example
19124 @end quotation
19126 where @code{program} is the name of the executable file. This
19127 activates the debugger and results in a prompt for debugger commands.
19128 The simplest command is simply @code{run}, which causes the program to run
19129 exactly as if the debugger were not present. The following section
19130 describes some of the additional commands that can be given to @code{GDB}.
19132 @node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
19133 @anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{172}@anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{173}
19134 @subsection Introduction to GDB Commands
19137 @code{GDB} contains a large repertoire of commands.
19138 See @cite{Debugging with GDB} for extensive documentation on the use
19139 of these commands, together with examples of their use. Furthermore,
19140 the command @emph{help} invoked from within GDB activates a simple help
19141 facility which summarizes the available commands and their options.
19142 In this section we summarize a few of the most commonly
19143 used commands to give an idea of what @code{GDB} is about. You should create
19144 a simple program with debugging information and experiment with the use of
19145 these @code{GDB} commands on the program as you read through the
19146 following section.
19149 @itemize *
19151 @item 
19153 @table @asis
19155 @item @code{set args @emph{arguments}}
19157 The @emph{arguments} list above is a list of arguments to be passed to
19158 the program on a subsequent run command, just as though the arguments
19159 had been entered on a normal invocation of the program. The @code{set args}
19160 command is not needed if the program does not require arguments.
19161 @end table
19163 @item 
19165 @table @asis
19167 @item @code{run}
19169 The @code{run} command causes execution of the program to start from
19170 the beginning. If the program is already running, that is to say if
19171 you are currently positioned at a breakpoint, then a prompt will ask
19172 for confirmation that you want to abandon the current execution and
19173 restart.
19174 @end table
19176 @item 
19178 @table @asis
19180 @item @code{breakpoint @emph{location}}
19182 The breakpoint command sets a breakpoint, that is to say a point at which
19183 execution will halt and @code{GDB} will await further
19184 commands. @emph{location} is
19185 either a line number within a file, given in the format @code{file:linenumber},
19186 or it is the name of a subprogram. If you request that a breakpoint be set on
19187 a subprogram that is overloaded, a prompt will ask you to specify on which of
19188 those subprograms you want to breakpoint. You can also
19189 specify that all of them should be breakpointed. If the program is run
19190 and execution encounters the breakpoint, then the program
19191 stops and @code{GDB} signals that the breakpoint was encountered by
19192 printing the line of code before which the program is halted.
19193 @end table
19195 @item 
19197 @table @asis
19199 @item @code{catch exception @emph{name}}
19201 This command causes the program execution to stop whenever exception
19202 @code{name} is raised.  If @code{name} is omitted, then the execution is
19203 suspended when any exception is raised.
19204 @end table
19206 @item 
19208 @table @asis
19210 @item @code{print @emph{expression}}
19212 This will print the value of the given expression. Most simple
19213 Ada expression formats are properly handled by @code{GDB}, so the expression
19214 can contain function calls, variables, operators, and attribute references.
19215 @end table
19217 @item 
19219 @table @asis
19221 @item @code{continue}
19223 Continues execution following a breakpoint, until the next breakpoint or the
19224 termination of the program.
19225 @end table
19227 @item 
19229 @table @asis
19231 @item @code{step}
19233 Executes a single line after a breakpoint. If the next statement
19234 is a subprogram call, execution continues into (the first statement of)
19235 the called subprogram.
19236 @end table
19238 @item 
19240 @table @asis
19242 @item @code{next}
19244 Executes a single line. If this line is a subprogram call, executes and
19245 returns from the call.
19246 @end table
19248 @item 
19250 @table @asis
19252 @item @code{list}
19254 Lists a few lines around the current source location. In practice, it
19255 is usually more convenient to have a separate edit window open with the
19256 relevant source file displayed. Successive applications of this command
19257 print subsequent lines. The command can be given an argument which is a
19258 line number, in which case it displays a few lines around the specified one.
19259 @end table
19261 @item 
19263 @table @asis
19265 @item @code{backtrace}
19267 Displays a backtrace of the call chain. This command is typically
19268 used after a breakpoint has occurred, to examine the sequence of calls that
19269 leads to the current breakpoint. The display includes one line for each
19270 activation record (frame) corresponding to an active subprogram.
19271 @end table
19273 @item 
19275 @table @asis
19277 @item @code{up}
19279 At a breakpoint, @code{GDB} can display the values of variables local
19280 to the current frame. The command @code{up} can be used to
19281 examine the contents of other active frames, by moving the focus up
19282 the stack, that is to say from callee to caller, one frame at a time.
19283 @end table
19285 @item 
19287 @table @asis
19289 @item @code{down}
19291 Moves the focus of @code{GDB} down from the frame currently being
19292 examined to the frame of its callee (the reverse of the previous command),
19293 @end table
19295 @item 
19297 @table @asis
19299 @item @code{frame @emph{n}}
19301 Inspect the frame with the given number. The value 0 denotes the frame
19302 of the current breakpoint, that is to say the top of the call stack.
19303 @end table
19305 @item 
19307 @table @asis
19309 @item @code{kill}
19311 Kills the child process in which the program is running under GDB.
19312 This may be useful for several purposes:
19315 @itemize *
19317 @item 
19318 It allows you to recompile and relink your program, since on many systems
19319 you cannot regenerate an executable file while it is running in a process.
19321 @item 
19322 You can run your program outside the debugger, on systems that do not
19323 permit executing a program outside GDB while breakpoints are set
19324 within GDB.
19326 @item 
19327 It allows you to debug a core dump rather than a running process.
19328 @end itemize
19329 @end table
19330 @end itemize
19332 The above list is a very short introduction to the commands that
19333 @code{GDB} provides. Important additional capabilities, including conditional
19334 breakpoints, the ability to execute command sequences on a breakpoint,
19335 the ability to debug at the machine instruction level and many other
19336 features are described in detail in @cite{Debugging with GDB}.
19337 Note that most commands can be abbreviated
19338 (for example, c for continue, bt for backtrace).
19340 @node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
19341 @anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{174}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{175}
19342 @subsection Using Ada Expressions
19345 @geindex Ada expressions (in gdb)
19347 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19348 extensions. The philosophy behind the design of this subset is
19350 @quotation
19353 @itemize *
19355 @item 
19356 That @code{GDB} should provide basic literals and access to operations for
19357 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19358 leaving more sophisticated computations to subprograms written into the
19359 program (which therefore may be called from @code{GDB}).
19361 @item 
19362 That type safety and strict adherence to Ada language restrictions
19363 are not particularly relevant in a debugging context.
19365 @item 
19366 That brevity is important to the @code{GDB} user.
19367 @end itemize
19368 @end quotation
19370 Thus, for brevity, the debugger acts as if there were
19371 implicit @code{with} and @code{use} clauses in effect for all user-written
19372 packages, thus making it unnecessary to fully qualify most names with
19373 their packages, regardless of context. Where this causes ambiguity,
19374 @code{GDB} asks the user's intent.
19376 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
19378 @node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
19379 @anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{176}@anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{177}
19380 @subsection Calling User-Defined Subprograms
19383 An important capability of @code{GDB} is the ability to call user-defined
19384 subprograms while debugging. This is achieved simply by entering
19385 a subprogram call statement in the form:
19387 @quotation
19389 @example
19390 call subprogram-name (parameters)
19391 @end example
19392 @end quotation
19394 The keyword @code{call} can be omitted in the normal case where the
19395 @code{subprogram-name} does not coincide with any of the predefined
19396 @code{GDB} commands.
19398 The effect is to invoke the given subprogram, passing it the
19399 list of parameters that is supplied. The parameters can be expressions and
19400 can include variables from the program being debugged. The
19401 subprogram must be defined
19402 at the library level within your program, and @code{GDB} will call the
19403 subprogram within the environment of your program execution (which
19404 means that the subprogram is free to access or even modify variables
19405 within your program).
19407 The most important use of this facility is in allowing the inclusion of
19408 debugging routines that are tailored to particular data structures
19409 in your program. Such debugging routines can be written to provide a suitably
19410 high-level description of an abstract type, rather than a low-level dump
19411 of its physical layout. After all, the standard
19412 @code{GDB print} command only knows the physical layout of your
19413 types, not their abstract meaning. Debugging routines can provide information
19414 at the desired semantic level and are thus enormously useful.
19416 For example, when debugging GNAT itself, it is crucial to have access to
19417 the contents of the tree nodes used to represent the program internally.
19418 But tree nodes are represented simply by an integer value (which in turn
19419 is an index into a table of nodes).
19420 Using the @code{print} command on a tree node would simply print this integer
19421 value, which is not very useful. But the PN routine (defined in file
19422 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19423 a useful high level representation of the tree node, which includes the
19424 syntactic category of the node, its position in the source, the integers
19425 that denote descendant nodes and parent node, as well as varied
19426 semantic information. To study this example in more detail, you might want to
19427 look at the body of the PN procedure in the stated file.
19429 Another useful application of this capability is to deal with situations of
19430 complex data which are not handled suitably by GDB. For example, if you specify
19431 Convention Fortran for a multi-dimensional array, GDB does not know that
19432 the ordering of array elements has been switched and will not properly
19433 address the array elements. In such a case, instead of trying to print the
19434 elements directly from GDB, you can write a callable procedure that prints
19435 the elements in the desired format.
19437 @node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
19438 @anchor{gnat_ugn/gnat_and_program_execution using-the-next-command-in-a-function}@anchor{178}@anchor{gnat_ugn/gnat_and_program_execution id8}@anchor{179}
19439 @subsection Using the @emph{next} Command in a Function
19442 When you use the @code{next} command in a function, the current source
19443 location will advance to the next statement as usual. A special case
19444 arises in the case of a @code{return} statement.
19446 Part of the code for a return statement is the 'epilogue' of the function.
19447 This is the code that returns to the caller. There is only one copy of
19448 this epilogue code, and it is typically associated with the last return
19449 statement in the function if there is more than one return. In some
19450 implementations, this epilogue is associated with the first statement
19451 of the function.
19453 The result is that if you use the @code{next} command from a return
19454 statement that is not the last return statement of the function you
19455 may see a strange apparent jump to the last return statement or to
19456 the start of the function. You should simply ignore this odd jump.
19457 The value returned is always that from the first return statement
19458 that was stepped through.
19460 @node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
19461 @anchor{gnat_ugn/gnat_and_program_execution stopping-when-ada-exceptions-are-raised}@anchor{17a}@anchor{gnat_ugn/gnat_and_program_execution id9}@anchor{17b}
19462 @subsection Stopping When Ada Exceptions Are Raised
19465 @geindex Exceptions (in gdb)
19467 You can set catchpoints that stop the program execution when your program
19468 raises selected exceptions.
19471 @itemize *
19473 @item 
19475 @table @asis
19477 @item @code{catch exception}
19479 Set a catchpoint that stops execution whenever (any task in the) program
19480 raises any exception.
19481 @end table
19483 @item 
19485 @table @asis
19487 @item @code{catch exception @emph{name}}
19489 Set a catchpoint that stops execution whenever (any task in the) program
19490 raises the exception @emph{name}.
19491 @end table
19493 @item 
19495 @table @asis
19497 @item @code{catch exception unhandled}
19499 Set a catchpoint that stops executing whenever (any task in the) program
19500 raises an exception for which there is no handler.
19501 @end table
19503 @item 
19505 @table @asis
19507 @item @code{info exceptions}, @code{info exceptions @emph{regexp}}
19509 The @code{info exceptions} command permits the user to examine all defined
19510 exceptions within Ada programs. With a regular expression, @emph{regexp}, as
19511 argument, prints out only those exceptions whose name matches @emph{regexp}.
19512 @end table
19513 @end itemize
19515 @geindex Tasks (in gdb)
19517 @node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
19518 @anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{17c}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{17d}
19519 @subsection Ada Tasks
19522 @code{GDB} allows the following task-related commands:
19525 @itemize *
19527 @item 
19529 @table @asis
19531 @item @code{info tasks}
19533 This command shows a list of current Ada tasks, as in the following example:
19535 @example
19536 (gdb) info tasks
19537   ID       TID P-ID   Thread Pri State                 Name
19538    1   8088000   0   807e000  15 Child Activation Wait main_task
19539    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19540    3   809a800   1   80a4800  15 Child Activation Wait a
19541 *  4   80ae800   3   80b8000  15 Running               c
19542 @end example
19544 In this listing, the asterisk before the first task indicates it to be the
19545 currently running task. The first column lists the task ID that is used
19546 to refer to tasks in the following commands.
19547 @end table
19548 @end itemize
19550 @geindex Breakpoints and tasks
19553 @itemize *
19555 @item 
19556 @code{break`@w{`}*linespec* `@w{`}task} @emph{taskid}, @code{break} @emph{linespec} @code{task} @emph{taskid} @code{if} ...
19558 @quotation
19560 These commands are like the @code{break ... thread ...}.
19561 @emph{linespec} specifies source lines.
19563 Use the qualifier @code{task @emph{taskid}} with a breakpoint command
19564 to specify that you only want @code{GDB} to stop the program when a
19565 particular Ada task reaches this breakpoint. @emph{taskid} is one of the
19566 numeric task identifiers assigned by @code{GDB}, shown in the first
19567 column of the @code{info tasks} display.
19569 If you do not specify @code{task @emph{taskid}} when you set a
19570 breakpoint, the breakpoint applies to @emph{all} tasks of your
19571 program.
19573 You can use the @code{task} qualifier on conditional breakpoints as
19574 well; in this case, place @code{task @emph{taskid}} before the
19575 breakpoint condition (before the @code{if}).
19576 @end quotation
19577 @end itemize
19579 @geindex Task switching (in gdb)
19582 @itemize *
19584 @item 
19585 @code{task @emph{taskno}}
19587 @quotation
19589 This command allows switching to the task referred by @emph{taskno}. In
19590 particular, this allows browsing of the backtrace of the specified
19591 task. It is advisable to switch back to the original task before
19592 continuing execution otherwise the scheduling of the program may be
19593 perturbed.
19594 @end quotation
19595 @end itemize
19597 For more detailed information on the tasking support,
19598 see @cite{Debugging with GDB}.
19600 @geindex Debugging Generic Units
19602 @geindex Generics
19604 @node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
19605 @anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{17e}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{17f}
19606 @subsection Debugging Generic Units
19609 GNAT always uses code expansion for generic instantiation. This means that
19610 each time an instantiation occurs, a complete copy of the original code is
19611 made, with appropriate substitutions of formals by actuals.
19613 It is not possible to refer to the original generic entities in
19614 @code{GDB}, but it is always possible to debug a particular instance of
19615 a generic, by using the appropriate expanded names. For example, if we have
19617 @quotation
19619 @example
19620 procedure g is
19622    generic package k is
19623       procedure kp (v1 : in out integer);
19624    end k;
19626    package body k is
19627       procedure kp (v1 : in out integer) is
19628       begin
19629          v1 := v1 + 1;
19630       end kp;
19631    end k;
19633    package k1 is new k;
19634    package k2 is new k;
19636    var : integer := 1;
19638 begin
19639    k1.kp (var);
19640    k2.kp (var);
19641    k1.kp (var);
19642    k2.kp (var);
19643 end;
19644 @end example
19645 @end quotation
19647 Then to break on a call to procedure kp in the k2 instance, simply
19648 use the command:
19650 @quotation
19652 @example
19653 (gdb) break g.k2.kp
19654 @end example
19655 @end quotation
19657 When the breakpoint occurs, you can step through the code of the
19658 instance in the normal manner and examine the values of local variables, as for
19659 other units.
19661 @geindex Remote Debugging with gdbserver
19663 @node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
19664 @anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{180}@anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{181}
19665 @subsection Remote Debugging with gdbserver
19668 On platforms where gdbserver is supported, it is possible to use this tool
19669 to debug your application remotely.  This can be useful in situations
19670 where the program needs to be run on a target host that is different
19671 from the host used for development, particularly when the target has
19672 a limited amount of resources (either CPU and/or memory).
19674 To do so, start your program using gdbserver on the target machine.
19675 gdbserver then automatically suspends the execution of your program
19676 at its entry point, waiting for a debugger to connect to it.  The
19677 following commands starts an application and tells gdbserver to
19678 wait for a connection with the debugger on localhost port 4444.
19680 @quotation
19682 @example
19683 $ gdbserver localhost:4444 program
19684 Process program created; pid = 5685
19685 Listening on port 4444
19686 @end example
19687 @end quotation
19689 Once gdbserver has started listening, we can tell the debugger to establish
19690 a connection with this gdbserver, and then start the same debugging session
19691 as if the program was being debugged on the same host, directly under
19692 the control of GDB.
19694 @quotation
19696 @example
19697 $ gdb program
19698 (gdb) target remote targethost:4444
19699 Remote debugging using targethost:4444
19700 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19701 (gdb) b foo.adb:3
19702 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19703 (gdb) continue
19704 Continuing.
19706 Breakpoint 1, foo () at foo.adb:4
19707 4       end foo;
19708 @end example
19709 @end quotation
19711 It is also possible to use gdbserver to attach to an already running
19712 program, in which case the execution of that program is simply suspended
19713 until the connection between the debugger and gdbserver is established.
19715 For more information on how to use gdbserver, see the @emph{Using the gdbserver Program}
19716 section in @cite{Debugging with GDB}.
19717 GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
19719 @geindex Abnormal Termination or Failure to Terminate
19721 @node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
19722 @anchor{gnat_ugn/gnat_and_program_execution gnat-abnormal-termination-or-failure-to-terminate}@anchor{182}@anchor{gnat_ugn/gnat_and_program_execution id13}@anchor{183}
19723 @subsection GNAT Abnormal Termination or Failure to Terminate
19726 When presented with programs that contain serious errors in syntax
19727 or semantics,
19728 GNAT may on rare occasions  experience problems in operation, such
19729 as aborting with a
19730 segmentation fault or illegal memory access, raising an internal
19731 exception, terminating abnormally, or failing to terminate at all.
19732 In such cases, you can activate
19733 various features of GNAT that can help you pinpoint the construct in your
19734 program that is the likely source of the problem.
19736 The following strategies are presented in increasing order of
19737 difficulty, corresponding to your experience in using GNAT and your
19738 familiarity with compiler internals.
19741 @itemize *
19743 @item 
19744 Run @code{gcc} with the @code{-gnatf}. This first
19745 switch causes all errors on a given line to be reported. In its absence,
19746 only the first error on a line is displayed.
19748 The @code{-gnatdO} switch causes errors to be displayed as soon as they
19749 are encountered, rather than after compilation is terminated. If GNAT
19750 terminates prematurely or goes into an infinite loop, the last error
19751 message displayed may help to pinpoint the culprit.
19753 @item 
19754 Run @code{gcc} with the @code{-v} (verbose) switch. In this
19755 mode, @code{gcc} produces ongoing information about the progress of the
19756 compilation and provides the name of each procedure as code is
19757 generated. This switch allows you to find which Ada procedure was being
19758 compiled when it encountered a code generation problem.
19759 @end itemize
19761 @geindex -gnatdc switch
19764 @itemize *
19766 @item 
19767 Run @code{gcc} with the @code{-gnatdc} switch. This is a GNAT specific
19768 switch that does for the front-end what @code{-v} does
19769 for the back end. The system prints the name of each unit,
19770 either a compilation unit or nested unit, as it is being analyzed.
19772 @item 
19773 Finally, you can start
19774 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19775 front-end of GNAT, and can be run independently (normally it is just
19776 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
19777 would on a C program (but @ref{16e,,The GNAT Debugger GDB} for caveats). The
19778 @code{where} command is the first line of attack; the variable
19779 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19780 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
19781 which the execution stopped, and @code{input_file name} indicates the name of
19782 the source file.
19783 @end itemize
19785 @node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
19786 @anchor{gnat_ugn/gnat_and_program_execution naming-conventions-for-gnat-source-files}@anchor{184}@anchor{gnat_ugn/gnat_and_program_execution id14}@anchor{185}
19787 @subsection Naming Conventions for GNAT Source Files
19790 In order to examine the workings of the GNAT system, the following
19791 brief description of its organization may be helpful:
19794 @itemize *
19796 @item 
19797 Files with prefix @code{sc} contain the lexical scanner.
19799 @item 
19800 All files prefixed with @code{par} are components of the parser. The
19801 numbers correspond to chapters of the Ada Reference Manual. For example,
19802 parsing of select statements can be found in @code{par-ch9.adb}.
19804 @item 
19805 All files prefixed with @code{sem} perform semantic analysis. The
19806 numbers correspond to chapters of the Ada standard. For example, all
19807 issues involving context clauses can be found in @code{sem_ch10.adb}. In
19808 addition, some features of the language require sufficient special processing
19809 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19810 dynamic dispatching, etc.
19812 @item 
19813 All files prefixed with @code{exp} perform normalization and
19814 expansion of the intermediate representation (abstract syntax tree, or AST).
19815 these files use the same numbering scheme as the parser and semantics files.
19816 For example, the construction of record initialization procedures is done in
19817 @code{exp_ch3.adb}.
19819 @item 
19820 The files prefixed with @code{bind} implement the binder, which
19821 verifies the consistency of the compilation, determines an order of
19822 elaboration, and generates the bind file.
19824 @item 
19825 The files @code{atree.ads} and @code{atree.adb} detail the low-level
19826 data structures used by the front-end.
19828 @item 
19829 The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
19830 the abstract syntax tree as produced by the parser.
19832 @item 
19833 The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
19834 all entities, computed during semantic analysis.
19836 @item 
19837 Library management issues are dealt with in files with prefix
19838 @code{lib}.
19840 @geindex Annex A (in Ada Reference Manual)
19842 @item 
19843 Ada files with the prefix @code{a-} are children of @code{Ada}, as
19844 defined in Annex A.
19846 @geindex Annex B (in Ada reference Manual)
19848 @item 
19849 Files with prefix @code{i-} are children of @code{Interfaces}, as
19850 defined in Annex B.
19852 @geindex System (package in Ada Reference Manual)
19854 @item 
19855 Files with prefix @code{s-} are children of @code{System}. This includes
19856 both language-defined children and GNAT run-time routines.
19858 @geindex GNAT (package)
19860 @item 
19861 Files with prefix @code{g-} are children of @code{GNAT}. These are useful
19862 general-purpose packages, fully documented in their specs. All
19863 the other @code{.c} files are modifications of common @code{gcc} files.
19864 @end itemize
19866 @node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
19867 @anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{186}@anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{187}
19868 @subsection Getting Internal Debugging Information
19871 Most compilers have internal debugging switches and modes. GNAT
19872 does also, except GNAT internal debugging switches and modes are not
19873 secret. A summary and full description of all the compiler and binder
19874 debug flags are in the file @code{debug.adb}. You must obtain the
19875 sources of the compiler to see the full detailed effects of these flags.
19877 The switches that print the source of the program (reconstructed from
19878 the internal tree) are of general interest for user programs, as are the
19879 options to print
19880 the full internal tree, and the entity table (the symbol table
19881 information). The reconstructed source provides a readable version of the
19882 program after the front-end has completed analysis and  expansion,
19883 and is useful when studying the performance of specific constructs.
19884 For example, constraint checks are indicated, complex aggregates
19885 are replaced with loops and assignments, and tasking primitives
19886 are replaced with run-time calls.
19888 @geindex traceback
19890 @geindex stack traceback
19892 @geindex stack unwinding
19894 @node Stack Traceback,Pretty-Printers for the GNAT runtime,Getting Internal Debugging Information,Running and Debugging Ada Programs
19895 @anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{188}@anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{189}
19896 @subsection Stack Traceback
19899 Traceback is a mechanism to display the sequence of subprogram calls that
19900 leads to a specified execution point in a program. Often (but not always)
19901 the execution point is an instruction at which an exception has been raised.
19902 This mechanism is also known as @emph{stack unwinding} because it obtains
19903 its information by scanning the run-time stack and recovering the activation
19904 records of all active subprograms. Stack unwinding is one of the most
19905 important tools for program debugging.
19907 The first entry stored in traceback corresponds to the deepest calling level,
19908 that is to say the subprogram currently executing the instruction
19909 from which we want to obtain the traceback.
19911 Note that there is no runtime performance penalty when stack traceback
19912 is enabled, and no exception is raised during program execution.
19914 @geindex traceback
19915 @geindex non-symbolic
19917 @menu
19918 * Non-Symbolic Traceback:: 
19919 * Symbolic Traceback:: 
19921 @end menu
19923 @node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
19924 @anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{18a}@anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{18b}
19925 @subsubsection Non-Symbolic Traceback
19928 Note: this feature is not supported on all platforms. See
19929 @code{GNAT.Traceback} spec in @code{g-traceb.ads}
19930 for a complete list of supported platforms.
19932 @subsubheading Tracebacks From an Unhandled Exception
19935 A runtime non-symbolic traceback is a list of addresses of call instructions.
19936 To enable this feature you must use the @code{-E}
19937 @code{gnatbind} option. With this option a stack traceback is stored as part
19938 of exception information. You can retrieve this information using the
19939 @code{addr2line} tool.
19941 Here is a simple example:
19943 @quotation
19945 @example
19946 procedure STB is
19948    procedure P1 is
19949    begin
19950       raise Constraint_Error;
19951    end P1;
19953    procedure P2 is
19954    begin
19955       P1;
19956    end P2;
19958 begin
19959    P2;
19960 end STB;
19961 @end example
19963 @example
19964 $ gnatmake stb -bargs -E
19965 $ stb
19967 Execution terminated by unhandled exception
19968 Exception name: CONSTRAINT_ERROR
19969 Message: stb.adb:5
19970 Call stack traceback locations:
19971 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19972 @end example
19973 @end quotation
19975 As we see the traceback lists a sequence of addresses for the unhandled
19976 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19977 guess that this exception come from procedure P1. To translate these
19978 addresses into the source lines where the calls appear, the
19979 @code{addr2line} tool, described below, is invaluable. The use of this tool
19980 requires the program to be compiled with debug information.
19982 @quotation
19984 @example
19985 $ gnatmake -g stb -bargs -E
19986 $ stb
19988 Execution terminated by unhandled exception
19989 Exception name: CONSTRAINT_ERROR
19990 Message: stb.adb:5
19991 Call stack traceback locations:
19992 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19994 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19995    0x4011f1 0x77e892a4
19997 00401373 at d:/stb/stb.adb:5
19998 0040138B at d:/stb/stb.adb:10
19999 0040139C at d:/stb/stb.adb:14
20000 00401335 at d:/stb/b~stb.adb:104
20001 004011C4 at /build/.../crt1.c:200
20002 004011F1 at /build/.../crt1.c:222
20003 77E892A4 in ?? at ??:0
20004 @end example
20005 @end quotation
20007 The @code{addr2line} tool has several other useful options:
20009 @quotation
20012 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
20013 @item
20015 @code{--functions}
20017 @tab
20019 to get the function name corresponding to any location
20021 @item
20023 @code{--demangle=gnat}
20025 @tab
20027 to use the gnat decoding mode for the function names.
20028 Note that for binutils version 2.9.x the option is
20029 simply @code{--demangle}.
20031 @end multitable
20034 @example
20035 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
20036    0x40139c 0x401335 0x4011c4 0x4011f1
20038 00401373 in stb.p1 at d:/stb/stb.adb:5
20039 0040138B in stb.p2 at d:/stb/stb.adb:10
20040 0040139C in stb at d:/stb/stb.adb:14
20041 00401335 in main at d:/stb/b~stb.adb:104
20042 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
20043 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
20044 @end example
20045 @end quotation
20047 From this traceback we can see that the exception was raised in
20048 @code{stb.adb} at line 5, which was reached from a procedure call in
20049 @code{stb.adb} at line 10, and so on. The @code{b~std.adb} is the binder file,
20050 which contains the call to the main program.
20051 @ref{11c,,Running gnatbind}. The remaining entries are assorted runtime routines,
20052 and the output will vary from platform to platform.
20054 It is also possible to use @code{GDB} with these traceback addresses to debug
20055 the program. For example, we can break at a given code location, as reported
20056 in the stack traceback:
20058 @quotation
20060 @example
20061 $ gdb -nw stb
20062 @end example
20063 @end quotation
20065 Furthermore, this feature is not implemented inside Windows DLL. Only
20066 the non-symbolic traceback is reported in this case.
20068 @quotation
20070 @example
20071 (gdb) break *0x401373
20072 Breakpoint 1 at 0x401373: file stb.adb, line 5.
20073 @end example
20074 @end quotation
20076 It is important to note that the stack traceback addresses
20077 do not change when debug information is included. This is particularly useful
20078 because it makes it possible to release software without debug information (to
20079 minimize object size), get a field report that includes a stack traceback
20080 whenever an internal bug occurs, and then be able to retrieve the sequence
20081 of calls with the same program compiled with debug information.
20083 @subsubheading Tracebacks From Exception Occurrences
20086 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
20087 The stack traceback is attached to the exception information string, and can
20088 be retrieved in an exception handler within the Ada program, by means of the
20089 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
20091 @quotation
20093 @example
20094 with Ada.Text_IO;
20095 with Ada.Exceptions;
20097 procedure STB is
20099    use Ada;
20100    use Ada.Exceptions;
20102    procedure P1 is
20103       K : Positive := 1;
20104    begin
20105       K := K - 1;
20106    exception
20107       when E : others =>
20108          Text_IO.Put_Line (Exception_Information (E));
20109    end P1;
20111    procedure P2 is
20112    begin
20113       P1;
20114    end P2;
20116 begin
20117    P2;
20118 end STB;
20119 @end example
20120 @end quotation
20122 This program will output:
20124 @quotation
20126 @example
20127 $ stb
20129 Exception name: CONSTRAINT_ERROR
20130 Message: stb.adb:12
20131 Call stack traceback locations:
20132 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20133 @end example
20134 @end quotation
20136 @subsubheading Tracebacks From Anywhere in a Program
20139 It is also possible to retrieve a stack traceback from anywhere in a
20140 program. For this you need to
20141 use the @code{GNAT.Traceback} API. This package includes a procedure called
20142 @code{Call_Chain} that computes a complete stack traceback, as well as useful
20143 display procedures described below. It is not necessary to use the
20144 @code{-E} @code{gnatbind} option in this case, because the stack traceback mechanism
20145 is invoked explicitly.
20147 In the following example we compute a traceback at a specific location in
20148 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20149 convert addresses to strings:
20151 @quotation
20153 @example
20154 with Ada.Text_IO;
20155 with GNAT.Traceback;
20156 with GNAT.Debug_Utilities;
20158 procedure STB is
20160    use Ada;
20161    use GNAT;
20162    use GNAT.Traceback;
20164    procedure P1 is
20165       TB  : Tracebacks_Array (1 .. 10);
20166       --  We are asking for a maximum of 10 stack frames.
20167       Len : Natural;
20168       --  Len will receive the actual number of stack frames returned.
20169    begin
20170       Call_Chain (TB, Len);
20172       Text_IO.Put ("In STB.P1 : ");
20174       for K in 1 .. Len loop
20175          Text_IO.Put (Debug_Utilities.Image (TB (K)));
20176          Text_IO.Put (' ');
20177       end loop;
20179       Text_IO.New_Line;
20180    end P1;
20182    procedure P2 is
20183    begin
20184       P1;
20185    end P2;
20187 begin
20188    P2;
20189 end STB;
20190 @end example
20192 @example
20193 $ gnatmake -g stb
20194 $ stb
20196 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20197 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20198 @end example
20199 @end quotation
20201 You can then get further information by invoking the @code{addr2line}
20202 tool as described earlier (note that the hexadecimal addresses
20203 need to be specified in C format, with a leading '0x').
20205 @geindex traceback
20206 @geindex symbolic
20208 @node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
20209 @anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{18c}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{18d}
20210 @subsubsection Symbolic Traceback
20213 A symbolic traceback is a stack traceback in which procedure names are
20214 associated with each code location.
20216 Note that this feature is not supported on all platforms. See
20217 @code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
20218 list of currently supported platforms.
20220 Note that the symbolic traceback requires that the program be compiled
20221 with debug information. If it is not compiled with debug information
20222 only the non-symbolic information will be valid.
20224 @subsubheading Tracebacks From Exception Occurrences
20227 Here is an example:
20229 @quotation
20231 @example
20232 with Ada.Text_IO;
20233 with GNAT.Traceback.Symbolic;
20235 procedure STB is
20237    procedure P1 is
20238    begin
20239       raise Constraint_Error;
20240    end P1;
20242    procedure P2 is
20243    begin
20244       P1;
20245    end P2;
20247    procedure P3 is
20248    begin
20249       P2;
20250    end P3;
20252 begin
20253    P3;
20254 exception
20255    when E : others =>
20256       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20257 end STB;
20258 @end example
20260 @example
20261 $ gnatmake -g .\stb -bargs -E
20262 $ stb
20264 0040149F in stb.p1 at stb.adb:8
20265 004014B7 in stb.p2 at stb.adb:13
20266 004014CF in stb.p3 at stb.adb:18
20267 004015DD in ada.stb at stb.adb:22
20268 00401461 in main at b~stb.adb:168
20269 004011C4 in __mingw_CRTStartup at crt1.c:200
20270 004011F1 in mainCRTStartup at crt1.c:222
20271 77E892A4 in ?? at ??:0
20272 @end example
20273 @end quotation
20275 In the above example the @code{.\} syntax in the @code{gnatmake} command
20276 is currently required by @code{addr2line} for files that are in
20277 the current working directory.
20278 Moreover, the exact sequence of linker options may vary from platform
20279 to platform.
20280 The above @code{-largs} section is for Windows platforms. By contrast,
20281 under Unix there is no need for the @code{-largs} section.
20282 Differences across platforms are due to details of linker implementation.
20284 @subsubheading Tracebacks From Anywhere in a Program
20287 It is possible to get a symbolic stack traceback
20288 from anywhere in a program, just as for non-symbolic tracebacks.
20289 The first step is to obtain a non-symbolic
20290 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20291 information. Here is an example:
20293 @quotation
20295 @example
20296 with Ada.Text_IO;
20297 with GNAT.Traceback;
20298 with GNAT.Traceback.Symbolic;
20300 procedure STB is
20302    use Ada;
20303    use GNAT.Traceback;
20304    use GNAT.Traceback.Symbolic;
20306    procedure P1 is
20307       TB  : Tracebacks_Array (1 .. 10);
20308       --  We are asking for a maximum of 10 stack frames.
20309       Len : Natural;
20310       --  Len will receive the actual number of stack frames returned.
20311    begin
20312       Call_Chain (TB, Len);
20313       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20314    end P1;
20316    procedure P2 is
20317    begin
20318       P1;
20319    end P2;
20321 begin
20322    P2;
20323 end STB;
20324 @end example
20325 @end quotation
20327 @subsubheading Automatic Symbolic Tracebacks
20330 Symbolic tracebacks may also be enabled by using the -Es switch to gnatbind (as
20331 in @code{gprbuild -g ... -bargs -Es}).
20332 This will cause the Exception_Information to contain a symbolic traceback,
20333 which will also be printed if an unhandled exception terminates the
20334 program.
20336 @node Pretty-Printers for the GNAT runtime,,Stack Traceback,Running and Debugging Ada Programs
20337 @anchor{gnat_ugn/gnat_and_program_execution id19}@anchor{18e}@anchor{gnat_ugn/gnat_and_program_execution pretty-printers-for-the-gnat-runtime}@anchor{18f}
20338 @subsection Pretty-Printers for the GNAT runtime
20341 As discussed in @cite{Calling User-Defined Subprograms}, GDB's
20342 @code{print} command only knows about the physical layout of program data
20343 structures and therefore normally displays only low-level dumps, which
20344 are often hard to understand.
20346 An example of this is when trying to display the contents of an Ada
20347 standard container, such as @code{Ada.Containers.Ordered_Maps.Map}:
20349 @quotation
20351 @example
20352 with Ada.Containers.Ordered_Maps;
20354 procedure PP is
20355    package Int_To_Nat is
20356       new Ada.Containers.Ordered_Maps (Integer, Natural);
20358    Map : Int_To_Nat.Map;
20359 begin
20360    Map.Insert (1, 10);
20361    Map.Insert (2, 20);
20362    Map.Insert (3, 30);
20364    Map.Clear; --  BREAK HERE
20365 end PP;
20366 @end example
20367 @end quotation
20369 When this program is built with debugging information and run under
20370 GDB up to the @code{Map.Clear} statement, trying to print @code{Map} will
20371 yield information that is only relevant to the developers of our standard
20372 containers:
20374 @quotation
20376 @example
20377 (gdb) print map
20378 $1 = (
20379   tree => (
20380     first => 0x64e010,
20381     last => 0x64e070,
20382     root => 0x64e040,
20383     length => 3,
20384     tc => (
20385       busy => 0,
20386       lock => 0
20387     )
20388   )
20390 @end example
20391 @end quotation
20393 Fortunately, GDB has a feature called pretty-printers@footnote{http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Introduction},
20394 which allows customizing how GDB displays data structures. The GDB
20395 shipped with GNAT embeds such pretty-printers for the most common
20396 containers in the standard library.  To enable them, either run the
20397 following command manually under GDB or add it to your @code{.gdbinit} file:
20399 @quotation
20401 @example
20402 python import gnatdbg; gnatdbg.setup()
20403 @end example
20404 @end quotation
20406 Once this is done, GDB's @code{print} command will automatically use
20407 these pretty-printers when appropriate. Using the previous example:
20409 @quotation
20411 @example
20412 (gdb) print map
20413 $1 = pp.int_to_nat.map of length 3 = @{
20414   [1] = 10,
20415   [2] = 20,
20416   [3] = 30
20418 @end example
20419 @end quotation
20421 Pretty-printers are invoked each time GDB tries to display a value,
20422 including when displaying the arguments of a called subprogram (in
20423 GDB's @code{backtrace} command) or when printing the value returned by a
20424 function (in GDB's @code{finish} command).
20426 To display a value without involving pretty-printers, @code{print} can be
20427 invoked with its @code{/r} option:
20429 @quotation
20431 @example
20432 (gdb) print/r map
20433 $1 = (
20434   tree => (...
20435 @end example
20436 @end quotation
20438 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}
20439 for more information.
20441 @geindex Code Coverage
20443 @geindex Profiling
20445 @node Code Coverage and Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
20446 @anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{168}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-and-profiling}@anchor{25}
20447 @section Code Coverage and Profiling
20450 This section describes how to use the @code{gcov} coverage testing tool and
20451 the @code{gprof} profiler tool on Ada programs.
20453 @geindex gcov
20455 @menu
20456 * Code Coverage of Ada Programs with gcov:: 
20457 * Profiling an Ada Program with gprof:: 
20459 @end menu
20461 @node Code Coverage of Ada Programs with gcov,Profiling an Ada Program with gprof,,Code Coverage and Profiling
20462 @anchor{gnat_ugn/gnat_and_program_execution id21}@anchor{190}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-of-ada-programs-with-gcov}@anchor{191}
20463 @subsection Code Coverage of Ada Programs with gcov
20466 @code{gcov} is a test coverage program: it analyzes the execution of a given
20467 program on selected tests, to help you determine the portions of the program
20468 that are still untested.
20470 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
20471 User's Guide. You can refer to this documentation for a more complete
20472 description.
20474 This chapter provides a quick startup guide, and
20475 details some GNAT-specific features.
20477 @menu
20478 * Quick startup guide:: 
20479 * GNAT specifics:: 
20481 @end menu
20483 @node Quick startup guide,GNAT specifics,,Code Coverage of Ada Programs with gcov
20484 @anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{192}@anchor{gnat_ugn/gnat_and_program_execution quick-startup-guide}@anchor{193}
20485 @subsubsection Quick startup guide
20488 In order to perform coverage analysis of a program using @code{gcov}, several
20489 steps are needed:
20492 @enumerate 
20494 @item 
20495 Instrument the code during the compilation process,
20497 @item 
20498 Execute the instrumented program, and
20500 @item 
20501 Invoke the @code{gcov} tool to generate the coverage results.
20502 @end enumerate
20504 @geindex -fprofile-arcs (gcc)
20506 @geindex -ftest-coverage (gcc
20508 @geindex -fprofile-arcs (gnatbind)
20510 The code instrumentation needed by gcov is created at the object level.
20511 The source code is not modified in any way, because the instrumentation code is
20512 inserted by gcc during the compilation process. To compile your code with code
20513 coverage activated, you need to recompile your whole project using the
20514 switches
20515 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20516 @code{-fprofile-arcs}.
20518 @quotation
20520 @example
20521 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \\
20522    -largs -fprofile-arcs
20523 @end example
20524 @end quotation
20526 This compilation process will create @code{.gcno} files together with
20527 the usual object files.
20529 Once the program is compiled with coverage instrumentation, you can
20530 run it as many times as needed -- on portions of a test suite for
20531 example. The first execution will produce @code{.gcda} files at the
20532 same location as the @code{.gcno} files.  Subsequent executions
20533 will update those files, so that a cumulative result of the covered
20534 portions of the program is generated.
20536 Finally, you need to call the @code{gcov} tool. The different options of
20537 @code{gcov} are described in the GCC User's Guide, section @emph{Invoking gcov}.
20539 This will create annotated source files with a @code{.gcov} extension:
20540 @code{my_main.adb} file will be analyzed in @code{my_main.adb.gcov}.
20542 @node GNAT specifics,,Quick startup guide,Code Coverage of Ada Programs with gcov
20543 @anchor{gnat_ugn/gnat_and_program_execution gnat-specifics}@anchor{194}@anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{195}
20544 @subsubsection GNAT specifics
20547 Because of Ada semantics, portions of the source code may be shared among
20548 several object files. This is the case for example when generics are
20549 involved, when inlining is active  or when declarations generate  initialisation
20550 calls. In order to take
20551 into account this shared code, you need to call @code{gcov} on all
20552 source files of the tested program at once.
20554 The list of source files might exceed the system's maximum command line
20555 length. In order to bypass this limitation, a new mechanism has been
20556 implemented in @code{gcov}: you can now list all your project's files into a
20557 text file, and provide this file to gcov as a parameter,  preceded by a @code{@@}
20558 (e.g. @code{gcov @@mysrclist.txt}).
20560 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20561 not supported as there can be unresolved symbols during the final link.
20563 @geindex gprof
20565 @geindex Profiling
20567 @node Profiling an Ada Program with gprof,,Code Coverage of Ada Programs with gcov,Code Coverage and Profiling
20568 @anchor{gnat_ugn/gnat_and_program_execution profiling-an-ada-program-with-gprof}@anchor{196}@anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{197}
20569 @subsection Profiling an Ada Program with gprof
20572 This section is not meant to be an exhaustive documentation of @code{gprof}.
20573 Full documentation for it can be found in the @cite{GNU Profiler User's Guide}
20574 documentation that is part of this GNAT distribution.
20576 Profiling a program helps determine the parts of a program that are executed
20577 most often, and are therefore the most time-consuming.
20579 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
20580 better handle Ada programs and multitasking.
20581 It is currently supported on the following platforms
20584 @itemize *
20586 @item 
20587 linux x86/x86_64
20589 @item 
20590 solaris sparc/sparc64/x86
20592 @item 
20593 windows x86
20594 @end itemize
20596 In order to profile a program using @code{gprof}, several steps are needed:
20599 @enumerate 
20601 @item 
20602 Instrument the code, which requires a full recompilation of the project with the
20603 proper switches.
20605 @item 
20606 Execute the program under the analysis conditions, i.e. with the desired
20607 input.
20609 @item 
20610 Analyze the results using the @code{gprof} tool.
20611 @end enumerate
20613 The following sections detail the different steps, and indicate how
20614 to interpret the results.
20616 @menu
20617 * Compilation for profiling:: 
20618 * Program execution:: 
20619 * Running gprof:: 
20620 * Interpretation of profiling results:: 
20622 @end menu
20624 @node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
20625 @anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{198}@anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{199}
20626 @subsubsection Compilation for profiling
20629 @geindex -pg (gcc)
20630 @geindex for profiling
20632 @geindex -pg (gnatlink)
20633 @geindex for profiling
20635 In order to profile a program the first step is to tell the compiler
20636 to generate the necessary profiling information. The compiler switch to be used
20637 is @code{-pg}, which must be added to other compilation switches. This
20638 switch needs to be specified both during compilation and link stages, and can
20639 be specified once when using gnatmake:
20641 @quotation
20643 @example
20644 $ gnatmake -f -pg -P my_project
20645 @end example
20646 @end quotation
20648 Note that only the objects that were compiled with the @code{-pg} switch will
20649 be profiled; if you need to profile your whole project, use the @code{-f}
20650 gnatmake switch to force full recompilation.
20652 @node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
20653 @anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{19a}@anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{19b}
20654 @subsubsection Program execution
20657 Once the program has been compiled for profiling, you can run it as usual.
20659 The only constraint imposed by profiling is that the program must terminate
20660 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20661 properly analyzed.
20663 Once the program completes execution, a data file called @code{gmon.out} is
20664 generated in the directory where the program was launched from. If this file
20665 already exists, it will be overwritten.
20667 @node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
20668 @anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{19c}@anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{19d}
20669 @subsubsection Running gprof
20672 The @code{gprof} tool is called as follow:
20674 @quotation
20676 @example
20677 $ gprof my_prog gmon.out
20678 @end example
20679 @end quotation
20681 or simply:
20683 @quotation
20685 @example
20686 $  gprof my_prog
20687 @end example
20688 @end quotation
20690 The complete form of the gprof command line is the following:
20692 @quotation
20694 @example
20695 $ gprof [switches] [executable [data-file]]
20696 @end example
20697 @end quotation
20699 @code{gprof} supports numerous switches. The order of these
20700 switch does not matter. The full list of options can be found in
20701 the GNU Profiler User's Guide documentation that comes with this documentation.
20703 The following is the subset of those switches that is most relevant:
20705 @geindex --demangle (gprof)
20708 @table @asis
20710 @item @code{--demangle[=@emph{style}]}, @code{--no-demangle}
20712 These options control whether symbol names should be demangled when
20713 printing output.  The default is to demangle C++ symbols.  The
20714 @code{--no-demangle} option may be used to turn off demangling. Different
20715 compilers have different mangling styles.  The optional demangling style
20716 argument can be used to choose an appropriate demangling style for your
20717 compiler, in particular Ada symbols generated by GNAT can be demangled using
20718 @code{--demangle=gnat}.
20719 @end table
20721 @geindex -e (gprof)
20724 @table @asis
20726 @item @code{-e @emph{function_name}}
20728 The @code{-e @emph{function}} option tells @code{gprof} not to print
20729 information about the function @code{function_name} (and its
20730 children...) in the call graph.  The function will still be listed
20731 as a child of any functions that call it, but its index number will be
20732 shown as @code{[not printed]}.  More than one @code{-e} option may be
20733 given; only one @code{function_name} may be indicated with each @code{-e}
20734 option.
20735 @end table
20737 @geindex -E (gprof)
20740 @table @asis
20742 @item @code{-E @emph{function_name}}
20744 The @code{-E @emph{function}} option works like the @code{-e} option, but
20745 execution time spent in the function (and children who were not called from
20746 anywhere else), will not be used to compute the percentages-of-time for
20747 the call graph.  More than one @code{-E} option may be given; only one
20748 @code{function_name} may be indicated with each @code{-E`} option.
20749 @end table
20751 @geindex -f (gprof)
20754 @table @asis
20756 @item @code{-f @emph{function_name}}
20758 The @code{-f @emph{function}} option causes @code{gprof} to limit the
20759 call graph to the function @code{function_name} and its children (and
20760 their children...).  More than one @code{-f} option may be given;
20761 only one @code{function_name} may be indicated with each @code{-f}
20762 option.
20763 @end table
20765 @geindex -F (gprof)
20768 @table @asis
20770 @item @code{-F @emph{function_name}}
20772 The @code{-F @emph{function}} option works like the @code{-f} option, but
20773 only time spent in the function and its children (and their
20774 children...) will be used to determine total-time and
20775 percentages-of-time for the call graph.  More than one @code{-F} option
20776 may be given; only one @code{function_name} may be indicated with each
20777 @code{-F} option.  The @code{-F} option overrides the @code{-E} option.
20778 @end table
20780 @node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
20781 @anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{19e}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{19f}
20782 @subsubsection Interpretation of profiling results
20785 The results of the profiling analysis are represented by two arrays: the
20786 'flat profile' and the 'call graph'. Full documentation of those outputs
20787 can be found in the GNU Profiler User's Guide.
20789 The flat profile shows the time spent in each function of the program, and how
20790 many time it has been called. This allows you to locate easily the most
20791 time-consuming functions.
20793 The call graph shows, for each subprogram, the subprograms that call it,
20794 and the subprograms that it calls. It also provides an estimate of the time
20795 spent in each of those callers/called subprograms.
20797 @node Improving Performance,Overflow Check Handling in GNAT,Code Coverage and Profiling,GNAT and Program Execution
20798 @anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{169}@anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{26}
20799 @section Improving Performance
20802 @geindex Improving performance
20804 This section presents several topics related to program performance.
20805 It first describes some of the tradeoffs that need to be considered
20806 and some of the techniques for making your program run faster.
20809 It then documents the unused subprogram/data elimination feature,
20810 which can reduce the size of program executables.
20812 @menu
20813 * Performance Considerations:: 
20814 * Text_IO Suggestions:: 
20815 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
20817 @end menu
20819 @node Performance Considerations,Text_IO Suggestions,,Improving Performance
20820 @anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{1a0}@anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{1a1}
20821 @subsection Performance Considerations
20824 The GNAT system provides a number of options that allow a trade-off
20825 between
20828 @itemize *
20830 @item 
20831 performance of the generated code
20833 @item 
20834 speed of compilation
20836 @item 
20837 minimization of dependences and recompilation
20839 @item 
20840 the degree of run-time checking.
20841 @end itemize
20843 The defaults (if no options are selected) aim at improving the speed
20844 of compilation and minimizing dependences, at the expense of performance
20845 of the generated code:
20848 @itemize *
20850 @item 
20851 no optimization
20853 @item 
20854 no inlining of subprogram calls
20856 @item 
20857 all run-time checks enabled except overflow and elaboration checks
20858 @end itemize
20860 These options are suitable for most program development purposes. This
20861 section describes how you can modify these choices, and also provides
20862 some guidelines on debugging optimized code.
20864 @menu
20865 * Controlling Run-Time Checks:: 
20866 * Use of Restrictions:: 
20867 * Optimization Levels:: 
20868 * Debugging Optimized Code:: 
20869 * Inlining of Subprograms:: 
20870 * Floating_Point_Operations:: 
20871 * Vectorization of loops:: 
20872 * Other Optimization Switches:: 
20873 * Optimization and Strict Aliasing:: 
20874 * Aliased Variables and Optimization:: 
20875 * Atomic Variables and Optimization:: 
20876 * Passive Task Optimization:: 
20878 @end menu
20880 @node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
20881 @anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{1a2}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{1a3}
20882 @subsubsection Controlling Run-Time Checks
20885 By default, GNAT generates all run-time checks, except stack overflow
20886 checks, and checks for access before elaboration on subprogram
20887 calls. The latter are not required in default mode, because all
20888 necessary checking is done at compile time.
20890 @geindex -gnatp (gcc)
20892 @geindex -gnato (gcc)
20894 The gnat switch, @code{-gnatp} allows this default to be modified. See
20895 @ref{f9,,Run-Time Checks}.
20897 Our experience is that the default is suitable for most development
20898 purposes.
20900 Elaboration checks are off by default, and also not needed by default, since
20901 GNAT uses a static elaboration analysis approach that avoids the need for
20902 run-time checking. This manual contains a full chapter discussing the issue
20903 of elaboration checks, and if the default is not satisfactory for your use,
20904 you should read this chapter.
20906 For validity checks, the minimal checks required by the Ada Reference
20907 Manual (for case statements and assignments to array elements) are on
20908 by default. These can be suppressed by use of the @code{-gnatVn} switch.
20909 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
20910 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
20911 it may be reasonable to routinely use @code{-gnatVn}. Validity checks
20912 are also suppressed entirely if @code{-gnatp} is used.
20914 @geindex Overflow checks
20916 @geindex Checks
20917 @geindex overflow
20919 @geindex Suppress
20921 @geindex Unsuppress
20923 @geindex pragma Suppress
20925 @geindex pragma Unsuppress
20927 Note that the setting of the switches controls the default setting of
20928 the checks. They may be modified using either @code{pragma Suppress} (to
20929 remove checks) or @code{pragma Unsuppress} (to add back suppressed
20930 checks) in the program source.
20932 @node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
20933 @anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{1a4}@anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{1a5}
20934 @subsubsection Use of Restrictions
20937 The use of pragma Restrictions allows you to control which features are
20938 permitted in your program. Apart from the obvious point that if you avoid
20939 relatively expensive features like finalization (enforceable by the use
20940 of pragma Restrictions (No_Finalization), the use of this pragma does not
20941 affect the generated code in most cases.
20943 One notable exception to this rule is that the possibility of task abort
20944 results in some distributed overhead, particularly if finalization or
20945 exception handlers are used. The reason is that certain sections of code
20946 have to be marked as non-abortable.
20948 If you use neither the @code{abort} statement, nor asynchronous transfer
20949 of control (@code{select ... then abort}), then this distributed overhead
20950 is removed, which may have a general positive effect in improving
20951 overall performance.  Especially code involving frequent use of tasking
20952 constructs and controlled types will show much improved performance.
20953 The relevant restrictions pragmas are
20955 @quotation
20957 @example
20958 pragma Restrictions (No_Abort_Statements);
20959 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
20960 @end example
20961 @end quotation
20963 It is recommended that these restriction pragmas be used if possible. Note
20964 that this also means that you can write code without worrying about the
20965 possibility of an immediate abort at any point.
20967 @node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
20968 @anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{1a6}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{fc}
20969 @subsubsection Optimization Levels
20972 @geindex -O (gcc)
20974 Without any optimization option,
20975 the compiler's goal is to reduce the cost of
20976 compilation and to make debugging produce the expected results.
20977 Statements are independent: if you stop the program with a breakpoint between
20978 statements, you can then assign a new value to any variable or change
20979 the program counter to any other statement in the subprogram and get exactly
20980 the results you would expect from the source code.
20982 Turning on optimization makes the compiler attempt to improve the
20983 performance and/or code size at the expense of compilation time and
20984 possibly the ability to debug the program.
20986 If you use multiple
20987 -O options, with or without level numbers,
20988 the last such option is the one that is effective.
20990 The default is optimization off. This results in the fastest compile
20991 times, but GNAT makes absolutely no attempt to optimize, and the
20992 generated programs are considerably larger and slower than when
20993 optimization is enabled. You can use the
20994 @code{-O} switch (the permitted forms are @code{-O0}, @code{-O1}
20995 @code{-O2}, @code{-O3}, and @code{-Os})
20996 to @code{gcc} to control the optimization level:
20999 @itemize *
21001 @item 
21003 @table @asis
21005 @item @code{-O0}
21007 No optimization (the default);
21008 generates unoptimized code but has
21009 the fastest compilation time.
21011 Note that many other compilers do substantial optimization even
21012 if 'no optimization' is specified. With gcc, it is very unusual
21013 to use @code{-O0} for production if execution time is of any concern,
21014 since @code{-O0} means (almost) no optimization. This difference
21015 between gcc and other compilers should be kept in mind when
21016 doing performance comparisons.
21017 @end table
21019 @item 
21021 @table @asis
21023 @item @code{-O1}
21025 Moderate optimization;
21026 optimizes reasonably well but does not
21027 degrade compilation time significantly.
21028 @end table
21030 @item 
21032 @table @asis
21034 @item @code{-O2}
21036 Full optimization;
21037 generates highly optimized code and has
21038 the slowest compilation time.
21039 @end table
21041 @item 
21043 @table @asis
21045 @item @code{-O3}
21047 Full optimization as in @code{-O2};
21048 also uses more aggressive automatic inlining of subprograms within a unit
21049 (@ref{10f,,Inlining of Subprograms}) and attempts to vectorize loops.
21050 @end table
21052 @item 
21054 @table @asis
21056 @item @code{-Os}
21058 Optimize space usage (code and data) of resulting program.
21059 @end table
21060 @end itemize
21062 Higher optimization levels perform more global transformations on the
21063 program and apply more expensive analysis algorithms in order to generate
21064 faster and more compact code. The price in compilation time, and the
21065 resulting improvement in execution time,
21066 both depend on the particular application and the hardware environment.
21067 You should experiment to find the best level for your application.
21069 Since the precise set of optimizations done at each level will vary from
21070 release to release (and sometime from target to target), it is best to think
21071 of the optimization settings in general terms.
21072 See the @emph{Options That Control Optimization} section in
21073 @cite{Using the GNU Compiler Collection (GCC)}
21074 for details about
21075 the @code{-O} settings and a number of @code{-f} options that
21076 individually enable or disable specific optimizations.
21078 Unlike some other compilation systems, @code{gcc} has
21079 been tested extensively at all optimization levels. There are some bugs
21080 which appear only with optimization turned on, but there have also been
21081 bugs which show up only in @emph{unoptimized} code. Selecting a lower
21082 level of optimization does not improve the reliability of the code
21083 generator, which in practice is highly reliable at all optimization
21084 levels.
21086 Note regarding the use of @code{-O3}: The use of this optimization level
21087 ought not to be automatically preferred over that of level @code{-O2},
21088 since it often results in larger executables which may run more slowly.
21089 See further discussion of this point in @ref{10f,,Inlining of Subprograms}.
21091 @node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
21092 @anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{1a7}@anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{1a8}
21093 @subsubsection Debugging Optimized Code
21096 @geindex Debugging optimized code
21098 @geindex Optimization and debugging
21100 Although it is possible to do a reasonable amount of debugging at
21101 nonzero optimization levels,
21102 the higher the level the more likely that
21103 source-level constructs will have been eliminated by optimization.
21104 For example, if a loop is strength-reduced, the loop
21105 control variable may be completely eliminated and thus cannot be
21106 displayed in the debugger.
21107 This can only happen at @code{-O2} or @code{-O3}.
21108 Explicit temporary variables that you code might be eliminated at
21109 level @code{-O1} or higher.
21111 @geindex -g (gcc)
21113 The use of the @code{-g} switch,
21114 which is needed for source-level debugging,
21115 affects the size of the program executable on disk,
21116 and indeed the debugging information can be quite large.
21117 However, it has no effect on the generated code (and thus does not
21118 degrade performance)
21120 Since the compiler generates debugging tables for a compilation unit before
21121 it performs optimizations, the optimizing transformations may invalidate some
21122 of the debugging data.  You therefore need to anticipate certain
21123 anomalous situations that may arise while debugging optimized code.
21124 These are the most common cases:
21127 @itemize *
21129 @item 
21130 @emph{The 'hopping Program Counter':}  Repeated @code{step} or @code{next}
21131 commands show
21132 the PC bouncing back and forth in the code.  This may result from any of
21133 the following optimizations:
21136 @itemize -
21138 @item 
21139 @emph{Common subexpression elimination:} using a single instance of code for a
21140 quantity that the source computes several times.  As a result you
21141 may not be able to stop on what looks like a statement.
21143 @item 
21144 @emph{Invariant code motion:} moving an expression that does not change within a
21145 loop, to the beginning of the loop.
21147 @item 
21148 @emph{Instruction scheduling:} moving instructions so as to
21149 overlap loads and stores (typically) with other code, or in
21150 general to move computations of values closer to their uses. Often
21151 this causes you to pass an assignment statement without the assignment
21152 happening and then later bounce back to the statement when the
21153 value is actually needed.  Placing a breakpoint on a line of code
21154 and then stepping over it may, therefore, not always cause all the
21155 expected side-effects.
21156 @end itemize
21158 @item 
21159 @emph{The 'big leap':} More commonly known as @emph{cross-jumping}, in which
21160 two identical pieces of code are merged and the program counter suddenly
21161 jumps to a statement that is not supposed to be executed, simply because
21162 it (and the code following) translates to the same thing as the code
21163 that @emph{was} supposed to be executed.  This effect is typically seen in
21164 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
21165 a @code{break} in a C @code{switch} statement.
21167 @item 
21168 @emph{The 'roving variable':} The symptom is an unexpected value in a variable.
21169 There are various reasons for this effect:
21172 @itemize -
21174 @item 
21175 In a subprogram prologue, a parameter may not yet have been moved to its
21176 'home'.
21178 @item 
21179 A variable may be dead, and its register re-used.  This is
21180 probably the most common cause.
21182 @item 
21183 As mentioned above, the assignment of a value to a variable may
21184 have been moved.
21186 @item 
21187 A variable may be eliminated entirely by value propagation or
21188 other means.  In this case, GCC may incorrectly generate debugging
21189 information for the variable
21190 @end itemize
21192 In general, when an unexpected value appears for a local variable or parameter
21193 you should first ascertain if that value was actually computed by
21194 your program, as opposed to being incorrectly reported by the debugger.
21195 Record fields or
21196 array elements in an object designated by an access value
21197 are generally less of a problem, once you have ascertained that the access
21198 value is sensible.
21199 Typically, this means checking variables in the preceding code and in the
21200 calling subprogram to verify that the value observed is explainable from other
21201 values (one must apply the procedure recursively to those
21202 other values); or re-running the code and stopping a little earlier
21203 (perhaps before the call) and stepping to better see how the variable obtained
21204 the value in question; or continuing to step @emph{from} the point of the
21205 strange value to see if code motion had simply moved the variable's
21206 assignments later.
21207 @end itemize
21209 In light of such anomalies, a recommended technique is to use @code{-O0}
21210 early in the software development cycle, when extensive debugging capabilities
21211 are most needed, and then move to @code{-O1} and later @code{-O2} as
21212 the debugger becomes less critical.
21213 Whether to use the @code{-g} switch in the release version is
21214 a release management issue.
21215 Note that if you use @code{-g} you can then use the @code{strip} program
21216 on the resulting executable,
21217 which removes both debugging information and global symbols.
21219 @node Inlining of Subprograms,Floating_Point_Operations,Debugging Optimized Code,Performance Considerations
21220 @anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{1a9}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{10f}
21221 @subsubsection Inlining of Subprograms
21224 A call to a subprogram in the current unit is inlined if all the
21225 following conditions are met:
21228 @itemize *
21230 @item 
21231 The optimization level is at least @code{-O1}.
21233 @item 
21234 The called subprogram is suitable for inlining: It must be small enough
21235 and not contain something that @code{gcc} cannot support in inlined
21236 subprograms.
21238 @geindex pragma Inline
21240 @geindex Inline
21242 @item 
21243 Any one of the following applies: @code{pragma Inline} is applied to the
21244 subprogram; the subprogram is local to the unit and called once from
21245 within it; the subprogram is small and optimization level @code{-O2} is
21246 specified; optimization level @code{-O3} is specified.
21247 @end itemize
21249 Calls to subprograms in @emph{with}ed units are normally not inlined.
21250 To achieve actual inlining (that is, replacement of the call by the code
21251 in the body of the subprogram), the following conditions must all be true:
21254 @itemize *
21256 @item 
21257 The optimization level is at least @code{-O1}.
21259 @item 
21260 The called subprogram is suitable for inlining: It must be small enough
21261 and not contain something that @code{gcc} cannot support in inlined
21262 subprograms.
21264 @item 
21265 There is a @code{pragma Inline} for the subprogram.
21267 @item 
21268 The @code{-gnatn} switch is used on the command line.
21269 @end itemize
21271 Even if all these conditions are met, it may not be possible for
21272 the compiler to inline the call, due to the length of the body,
21273 or features in the body that make it impossible for the compiler
21274 to do the inlining.
21276 Note that specifying the @code{-gnatn} switch causes additional
21277 compilation dependencies. Consider the following:
21279 @quotation
21281 @example
21282 package R is
21283    procedure Q;
21284    pragma Inline (Q);
21285 end R;
21286 package body R is
21287    ...
21288 end R;
21290 with R;
21291 procedure Main is
21292 begin
21293    ...
21294    R.Q;
21295 end Main;
21296 @end example
21297 @end quotation
21299 With the default behavior (no @code{-gnatn} switch specified), the
21300 compilation of the @code{Main} procedure depends only on its own source,
21301 @code{main.adb}, and the spec of the package in file @code{r.ads}. This
21302 means that editing the body of @code{R} does not require recompiling
21303 @code{Main}.
21305 On the other hand, the call @code{R.Q} is not inlined under these
21306 circumstances. If the @code{-gnatn} switch is present when @code{Main}
21307 is compiled, the call will be inlined if the body of @code{Q} is small
21308 enough, but now @code{Main} depends on the body of @code{R} in
21309 @code{r.adb} as well as on the spec. This means that if this body is edited,
21310 the main program must be recompiled. Note that this extra dependency
21311 occurs whether or not the call is in fact inlined by @code{gcc}.
21313 The use of front end inlining with @code{-gnatN} generates similar
21314 additional dependencies.
21316 @geindex -fno-inline (gcc)
21318 Note: The @code{-fno-inline} switch overrides all other conditions and ensures that
21319 no inlining occurs, unless requested with pragma Inline_Always for @code{gcc}
21320 back-ends. The extra dependences resulting from @code{-gnatn} will still be active,
21321 even if this switch is used to suppress the resulting inlining actions.
21323 @geindex -fno-inline-functions (gcc)
21325 Note: The @code{-fno-inline-functions} switch can be used to prevent
21326 automatic inlining of subprograms if @code{-O3} is used.
21328 @geindex -fno-inline-small-functions (gcc)
21330 Note: The @code{-fno-inline-small-functions} switch can be used to prevent
21331 automatic inlining of small subprograms if @code{-O2} is used.
21333 @geindex -fno-inline-functions-called-once (gcc)
21335 Note: The @code{-fno-inline-functions-called-once} switch
21336 can be used to prevent inlining of subprograms local to the unit
21337 and called once from within it if @code{-O1} is used.
21339 Note regarding the use of @code{-O3}: @code{-gnatn} is made up of two
21340 sub-switches @code{-gnatn1} and @code{-gnatn2} that can be directly
21341 specified in lieu of it, @code{-gnatn} being translated into one of them
21342 based on the optimization level. With @code{-O2} or below, @code{-gnatn}
21343 is equivalent to @code{-gnatn1} which activates pragma @code{Inline} with
21344 moderate inlining across modules. With @code{-O3}, @code{-gnatn} is
21345 equivalent to @code{-gnatn2} which activates pragma @code{Inline} with
21346 full inlining across modules. If you have used pragma @code{Inline} in
21347 appropriate cases, then it is usually much better to use @code{-O2}
21348 and @code{-gnatn} and avoid the use of @code{-O3} which has the additional
21349 effect of inlining subprograms you did not think should be inlined. We have
21350 found that the use of @code{-O3} may slow down the compilation and increase
21351 the code size by performing excessive inlining, leading to increased
21352 instruction cache pressure from the increased code size and thus minor
21353 performance improvements. So the bottom line here is that you should not
21354 automatically assume that @code{-O3} is better than @code{-O2}, and
21355 indeed you should use @code{-O3} only if tests show that it actually
21356 improves performance for your program.
21358 @node Floating_Point_Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
21359 @anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{1aa}@anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{1ab}
21360 @subsubsection Floating_Point_Operations
21363 @geindex Floating-Point Operations
21365 On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
21366 64-bit standard IEEE floating-point representations, and operations will
21367 use standard IEEE arithmetic as provided by the processor. On most, but
21368 not all, architectures, the attribute Machine_Overflows is False for these
21369 types, meaning that the semantics of overflow is implementation-defined.
21370 In the case of GNAT, these semantics correspond to the normal IEEE
21371 treatment of infinities and NaN (not a number) values. For example,
21372 1.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
21373 avoiding explicit overflow checks, the performance is greatly improved
21374 on many targets. However, if required, floating-point overflow can be
21375 enabled by the use of the pragma Check_Float_Overflow.
21377 Another consideration that applies specifically to x86 32-bit
21378 architectures is which form of floating-point arithmetic is used.
21379 By default the operations use the old style x86 floating-point,
21380 which implements an 80-bit extended precision form (on these
21381 architectures the type Long_Long_Float corresponds to that form).
21382 In addition, generation of efficient code in this mode means that
21383 the extended precision form will be used for intermediate results.
21384 This may be helpful in improving the final precision of a complex
21385 expression. However it means that the results obtained on the x86
21386 will be different from those on other architectures, and for some
21387 algorithms, the extra intermediate precision can be detrimental.
21389 In addition to this old-style floating-point, all modern x86 chips
21390 implement an alternative floating-point operation model referred
21391 to as SSE2. In this model there is no extended form, and furthermore
21392 execution performance is significantly enhanced. To force GNAT to use
21393 this more modern form, use both of the switches:
21395 @quotation
21397 -msse2 -mfpmath=sse
21398 @end quotation
21400 A unit compiled with these switches will automatically use the more
21401 efficient SSE2 instruction set for Float and Long_Float operations.
21402 Note that the ABI has the same form for both floating-point models,
21403 so it is permissible to mix units compiled with and without these
21404 switches.
21406 @node Vectorization of loops,Other Optimization Switches,Floating_Point_Operations,Performance Considerations
21407 @anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{1ac}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{1ad}
21408 @subsubsection Vectorization of loops
21411 @geindex Optimization Switches
21413 You can take advantage of the auto-vectorizer present in the @code{gcc}
21414 back end to vectorize loops with GNAT.  The corresponding command line switch
21415 is @code{-ftree-vectorize} but, as it is enabled by default at @code{-O3}
21416 and other aggressive optimizations helpful for vectorization also are enabled
21417 by default at this level, using @code{-O3} directly is recommended.
21419 You also need to make sure that the target architecture features a supported
21420 SIMD instruction set.  For example, for the x86 architecture, you should at
21421 least specify @code{-msse2} to get significant vectorization (but you don't
21422 need to specify it for x86-64 as it is part of the base 64-bit architecture).
21423 Similarly, for the PowerPC architecture, you should specify @code{-maltivec}.
21425 The preferred loop form for vectorization is the @code{for} iteration scheme.
21426 Loops with a @code{while} iteration scheme can also be vectorized if they are
21427 very simple, but the vectorizer will quickly give up otherwise.  With either
21428 iteration scheme, the flow of control must be straight, in particular no
21429 @code{exit} statement may appear in the loop body.  The loop may however
21430 contain a single nested loop, if it can be vectorized when considered alone:
21432 @quotation
21434 @example
21435 A : array (1..4, 1..4) of Long_Float;
21436 S : array (1..4) of Long_Float;
21438 procedure Sum is
21439 begin
21440    for I in A'Range(1) loop
21441       for J in A'Range(2) loop
21442          S (I) := S (I) + A (I, J);
21443       end loop;
21444    end loop;
21445 end Sum;
21446 @end example
21447 @end quotation
21449 The vectorizable operations depend on the targeted SIMD instruction set, but
21450 the adding and some of the multiplying operators are generally supported, as
21451 well as the logical operators for modular types. Note that compiling
21452 with @code{-gnatp} might well reveal cases where some checks do thwart
21453 vectorization.
21455 Type conversions may also prevent vectorization if they involve semantics that
21456 are not directly supported by the code generator or the SIMD instruction set.
21457 A typical example is direct conversion from floating-point to integer types.
21458 The solution in this case is to use the following idiom:
21460 @quotation
21462 @example
21463 Integer (S'Truncation (F))
21464 @end example
21465 @end quotation
21467 if @code{S} is the subtype of floating-point object @code{F}.
21469 In most cases, the vectorizable loops are loops that iterate over arrays.
21470 All kinds of array types are supported, i.e. constrained array types with
21471 static bounds:
21473 @quotation
21475 @example
21476 type Array_Type is array (1 .. 4) of Long_Float;
21477 @end example
21478 @end quotation
21480 constrained array types with dynamic bounds:
21482 @quotation
21484 @example
21485 type Array_Type is array (1 .. Q.N) of Long_Float;
21487 type Array_Type is array (Q.K .. 4) of Long_Float;
21489 type Array_Type is array (Q.K .. Q.N) of Long_Float;
21490 @end example
21491 @end quotation
21493 or unconstrained array types:
21495 @quotation
21497 @example
21498 type Array_Type is array (Positive range <>) of Long_Float;
21499 @end example
21500 @end quotation
21502 The quality of the generated code decreases when the dynamic aspect of the
21503 array type increases, the worst code being generated for unconstrained array
21504 types.  This is so because, the less information the compiler has about the
21505 bounds of the array, the more fallback code it needs to generate in order to
21506 fix things up at run time.
21508 It is possible to specify that a given loop should be subject to vectorization
21509 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
21511 @quotation
21513 @example
21514 pragma Loop_Optimize (Vector);
21515 @end example
21516 @end quotation
21518 placed immediately within the loop will convey the appropriate hint to the
21519 compiler for this loop.
21521 It is also possible to help the compiler generate better vectorized code
21522 for a given loop by asserting that there are no loop-carried dependencies
21523 in the loop.  Consider for example the procedure:
21525 @quotation
21527 @example
21528 type Arr is array (1 .. 4) of Long_Float;
21530 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
21531 begin
21532   for I in Arr'Range loop
21533     R(I) := X(I) + Y(I);
21534   end loop;
21535 end;
21536 @end example
21537 @end quotation
21539 By default, the compiler cannot unconditionally vectorize the loop because
21540 assigning to a component of the array designated by R in one iteration could
21541 change the value read from the components of the array designated by X or Y
21542 in a later iteration.  As a result, the compiler will generate two versions
21543 of the loop in the object code, one vectorized and the other not vectorized,
21544 as well as a test to select the appropriate version at run time.  This can
21545 be overcome by another hint:
21547 @quotation
21549 @example
21550 pragma Loop_Optimize (Ivdep);
21551 @end example
21552 @end quotation
21554 placed immediately within the loop will tell the compiler that it can safely
21555 omit the non-vectorized version of the loop as well as the run-time test.
21557 @node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
21558 @anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{1ae}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{1af}
21559 @subsubsection Other Optimization Switches
21562 @geindex Optimization Switches
21564 Since GNAT uses the @code{gcc} back end, all the specialized
21565 @code{gcc} optimization switches are potentially usable. These switches
21566 have not been extensively tested with GNAT but can generally be expected
21567 to work. Examples of switches in this category are @code{-funroll-loops}
21568 and the various target-specific @code{-m} options (in particular, it has
21569 been observed that @code{-march=xxx} can significantly improve performance
21570 on appropriate machines). For full details of these switches, see
21571 the @emph{Submodel Options} section in the @emph{Hardware Models and Configurations}
21572 chapter of @cite{Using the GNU Compiler Collection (GCC)}.
21574 @node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
21575 @anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{f3}@anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{1b0}
21576 @subsubsection Optimization and Strict Aliasing
21579 @geindex Aliasing
21581 @geindex Strict Aliasing
21583 @geindex No_Strict_Aliasing
21585 The strong typing capabilities of Ada allow an optimizer to generate
21586 efficient code in situations where other languages would be forced to
21587 make worst case assumptions preventing such optimizations. Consider
21588 the following example:
21590 @quotation
21592 @example
21593 procedure R is
21594    type Int1 is new Integer;
21595    type Int2 is new Integer;
21596    type Int1A is access Int1;
21597    type Int2A is access Int2;
21598    Int1V : Int1A;
21599    Int2V : Int2A;
21600    ...
21602 begin
21603    ...
21604    for J in Data'Range loop
21605       if Data (J) = Int1V.all then
21606          Int2V.all := Int2V.all + 1;
21607       end if;
21608    end loop;
21609    ...
21610 end R;
21611 @end example
21612 @end quotation
21614 In this example, since the variable @code{Int1V} can only access objects
21615 of type @code{Int1}, and @code{Int2V} can only access objects of type
21616 @code{Int2}, there is no possibility that the assignment to
21617 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
21618 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
21619 for all iterations of the loop and avoid the extra memory reference
21620 required to dereference it each time through the loop.
21622 This kind of optimization, called strict aliasing analysis, is
21623 triggered by specifying an optimization level of @code{-O2} or
21624 higher or @code{-Os} and allows GNAT to generate more efficient code
21625 when access values are involved.
21627 However, although this optimization is always correct in terms of
21628 the formal semantics of the Ada Reference Manual, difficulties can
21629 arise if features like @code{Unchecked_Conversion} are used to break
21630 the typing system. Consider the following complete program example:
21632 @quotation
21634 @example
21635 package p1 is
21636    type int1 is new integer;
21637    type int2 is new integer;
21638    type a1 is access int1;
21639    type a2 is access int2;
21640 end p1;
21642 with p1; use p1;
21643 package p2 is
21644    function to_a2 (Input : a1) return a2;
21645 end p2;
21647 with Unchecked_Conversion;
21648 package body p2 is
21649    function to_a2 (Input : a1) return a2 is
21650       function to_a2u is
21651         new Unchecked_Conversion (a1, a2);
21652    begin
21653       return to_a2u (Input);
21654    end to_a2;
21655 end p2;
21657 with p2; use p2;
21658 with p1; use p1;
21659 with Text_IO; use Text_IO;
21660 procedure m is
21661    v1 : a1 := new int1;
21662    v2 : a2 := to_a2 (v1);
21663 begin
21664    v1.all := 1;
21665    v2.all := 0;
21666    put_line (int1'image (v1.all));
21667 end;
21668 @end example
21669 @end quotation
21671 This program prints out 0 in @code{-O0} or @code{-O1}
21672 mode, but it prints out 1 in @code{-O2} mode. That's
21673 because in strict aliasing mode, the compiler can and
21674 does assume that the assignment to @code{v2.all} could not
21675 affect the value of @code{v1.all}, since different types
21676 are involved.
21678 This behavior is not a case of non-conformance with the standard, since
21679 the Ada RM specifies that an unchecked conversion where the resulting
21680 bit pattern is not a correct value of the target type can result in an
21681 abnormal value and attempting to reference an abnormal value makes the
21682 execution of a program erroneous.  That's the case here since the result
21683 does not point to an object of type @code{int2}.  This means that the
21684 effect is entirely unpredictable.
21686 However, although that explanation may satisfy a language
21687 lawyer, in practice an applications programmer expects an
21688 unchecked conversion involving pointers to create true
21689 aliases and the behavior of printing 1 seems plain wrong.
21690 In this case, the strict aliasing optimization is unwelcome.
21692 Indeed the compiler recognizes this possibility, and the
21693 unchecked conversion generates a warning:
21695 @quotation
21697 @example
21698 p2.adb:5:07: warning: possible aliasing problem with type "a2"
21699 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
21700 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
21701 @end example
21702 @end quotation
21704 Unfortunately the problem is recognized when compiling the body of
21705 package @code{p2}, but the actual "bad" code is generated while
21706 compiling the body of @code{m} and this latter compilation does not see
21707 the suspicious @code{Unchecked_Conversion}.
21709 As implied by the warning message, there are approaches you can use to
21710 avoid the unwanted strict aliasing optimization in a case like this.
21712 One possibility is to simply avoid the use of @code{-O2}, but
21713 that is a bit drastic, since it throws away a number of useful
21714 optimizations that do not involve strict aliasing assumptions.
21716 A less drastic approach is to compile the program using the
21717 option @code{-fno-strict-aliasing}. Actually it is only the
21718 unit containing the dereferencing of the suspicious pointer
21719 that needs to be compiled. So in this case, if we compile
21720 unit @code{m} with this switch, then we get the expected
21721 value of zero printed. Analyzing which units might need
21722 the switch can be painful, so a more reasonable approach
21723 is to compile the entire program with options @code{-O2}
21724 and @code{-fno-strict-aliasing}. If the performance is
21725 satisfactory with this combination of options, then the
21726 advantage is that the entire issue of possible "wrong"
21727 optimization due to strict aliasing is avoided.
21729 To avoid the use of compiler switches, the configuration
21730 pragma @code{No_Strict_Aliasing} with no parameters may be
21731 used to specify that for all access types, the strict
21732 aliasing optimization should be suppressed.
21734 However, these approaches are still overkill, in that they causes
21735 all manipulations of all access values to be deoptimized. A more
21736 refined approach is to concentrate attention on the specific
21737 access type identified as problematic.
21739 First, if a careful analysis of uses of the pointer shows
21740 that there are no possible problematic references, then
21741 the warning can be suppressed by bracketing the
21742 instantiation of @code{Unchecked_Conversion} to turn
21743 the warning off:
21745 @quotation
21747 @example
21748 pragma Warnings (Off);
21749 function to_a2u is
21750   new Unchecked_Conversion (a1, a2);
21751 pragma Warnings (On);
21752 @end example
21753 @end quotation
21755 Of course that approach is not appropriate for this particular
21756 example, since indeed there is a problematic reference. In this
21757 case we can take one of two other approaches.
21759 The first possibility is to move the instantiation of unchecked
21760 conversion to the unit in which the type is declared. In
21761 this example, we would move the instantiation of
21762 @code{Unchecked_Conversion} from the body of package
21763 @code{p2} to the spec of package @code{p1}. Now the
21764 warning disappears. That's because any use of the
21765 access type knows there is a suspicious unchecked
21766 conversion, and the strict aliasing optimization
21767 is automatically suppressed for the type.
21769 If it is not practical to move the unchecked conversion to the same unit
21770 in which the destination access type is declared (perhaps because the
21771 source type is not visible in that unit), you may use pragma
21772 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
21773 same declarative sequence as the declaration of the access type:
21775 @quotation
21777 @example
21778 type a2 is access int2;
21779 pragma No_Strict_Aliasing (a2);
21780 @end example
21781 @end quotation
21783 Here again, the compiler now knows that the strict aliasing optimization
21784 should be suppressed for any reference to type @code{a2} and the
21785 expected behavior is obtained.
21787 Finally, note that although the compiler can generate warnings for
21788 simple cases of unchecked conversions, there are tricker and more
21789 indirect ways of creating type incorrect aliases which the compiler
21790 cannot detect. Examples are the use of address overlays and unchecked
21791 conversions involving composite types containing access types as
21792 components. In such cases, no warnings are generated, but there can
21793 still be aliasing problems. One safe coding practice is to forbid the
21794 use of address clauses for type overlaying, and to allow unchecked
21795 conversion only for primitive types. This is not really a significant
21796 restriction since any possible desired effect can be achieved by
21797 unchecked conversion of access values.
21799 The aliasing analysis done in strict aliasing mode can certainly
21800 have significant benefits. We have seen cases of large scale
21801 application code where the time is increased by up to 5% by turning
21802 this optimization off. If you have code that includes significant
21803 usage of unchecked conversion, you might want to just stick with
21804 @code{-O1} and avoid the entire issue. If you get adequate
21805 performance at this level of optimization level, that's probably
21806 the safest approach. If tests show that you really need higher
21807 levels of optimization, then you can experiment with @code{-O2}
21808 and @code{-O2 -fno-strict-aliasing} to see how much effect this
21809 has on size and speed of the code. If you really need to use
21810 @code{-O2} with strict aliasing in effect, then you should
21811 review any uses of unchecked conversion of access types,
21812 particularly if you are getting the warnings described above.
21814 @node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
21815 @anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{1b1}@anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{1b2}
21816 @subsubsection Aliased Variables and Optimization
21819 @geindex Aliasing
21821 There are scenarios in which programs may
21822 use low level techniques to modify variables
21823 that otherwise might be considered to be unassigned. For example,
21824 a variable can be passed to a procedure by reference, which takes
21825 the address of the parameter and uses the address to modify the
21826 variable's value, even though it is passed as an IN parameter.
21827 Consider the following example:
21829 @quotation
21831 @example
21832 procedure P is
21833    Max_Length : constant Natural := 16;
21834    type Char_Ptr is access all Character;
21836    procedure Get_String(Buffer: Char_Ptr; Size : Integer);
21837    pragma Import (C, Get_String, "get_string");
21839    Name : aliased String (1 .. Max_Length) := (others => ' ');
21840    Temp : Char_Ptr;
21842    function Addr (S : String) return Char_Ptr is
21843       function To_Char_Ptr is
21844         new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
21845    begin
21846       return To_Char_Ptr (S (S'First)'Address);
21847    end;
21849 begin
21850    Temp := Addr (Name);
21851    Get_String (Temp, Max_Length);
21852 end;
21853 @end example
21854 @end quotation
21856 where Get_String is a C function that uses the address in Temp to
21857 modify the variable @code{Name}. This code is dubious, and arguably
21858 erroneous, and the compiler would be entitled to assume that
21859 @code{Name} is never modified, and generate code accordingly.
21861 However, in practice, this would cause some existing code that
21862 seems to work with no optimization to start failing at high
21863 levels of optimzization.
21865 What the compiler does for such cases is to assume that marking
21866 a variable as aliased indicates that some "funny business" may
21867 be going on. The optimizer recognizes the aliased keyword and
21868 inhibits optimizations that assume the value cannot be assigned.
21869 This means that the above example will in fact "work" reliably,
21870 that is, it will produce the expected results.
21872 @node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
21873 @anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{1b3}@anchor{gnat_ugn/gnat_and_program_execution id41}@anchor{1b4}
21874 @subsubsection Atomic Variables and Optimization
21877 @geindex Atomic
21879 There are two considerations with regard to performance when
21880 atomic variables are used.
21882 First, the RM only guarantees that access to atomic variables
21883 be atomic, it has nothing to say about how this is achieved,
21884 though there is a strong implication that this should not be
21885 achieved by explicit locking code. Indeed GNAT will never
21886 generate any locking code for atomic variable access (it will
21887 simply reject any attempt to make a variable or type atomic
21888 if the atomic access cannot be achieved without such locking code).
21890 That being said, it is important to understand that you cannot
21891 assume that the entire variable will always be accessed. Consider
21892 this example:
21894 @quotation
21896 @example
21897 type R is record
21898    A,B,C,D : Character;
21899 end record;
21900 for R'Size use 32;
21901 for R'Alignment use 4;
21903 RV : R;
21904 pragma Atomic (RV);
21905 X : Character;
21907 X := RV.B;
21908 @end example
21909 @end quotation
21911 You cannot assume that the reference to @code{RV.B}
21912 will read the entire 32-bit
21913 variable with a single load instruction. It is perfectly legitimate if
21914 the hardware allows it to do a byte read of just the B field. This read
21915 is still atomic, which is all the RM requires. GNAT can and does take
21916 advantage of this, depending on the architecture and optimization level.
21917 Any assumption to the contrary is non-portable and risky. Even if you
21918 examine the assembly language and see a full 32-bit load, this might
21919 change in a future version of the compiler.
21921 If your application requires that all accesses to @code{RV} in this
21922 example be full 32-bit loads, you need to make a copy for the access
21923 as in:
21925 @quotation
21927 @example
21928 declare
21929    RV_Copy : constant R := RV;
21930 begin
21931    X := RV_Copy.B;
21932 end;
21933 @end example
21934 @end quotation
21936 Now the reference to RV must read the whole variable.
21937 Actually one can imagine some compiler which figures
21938 out that the whole copy is not required (because only
21939 the B field is actually accessed), but GNAT
21940 certainly won't do that, and we don't know of any
21941 compiler that would not handle this right, and the
21942 above code will in practice work portably across
21943 all architectures (that permit the Atomic declaration).
21945 The second issue with atomic variables has to do with
21946 the possible requirement of generating synchronization
21947 code. For more details on this, consult the sections on
21948 the pragmas Enable/Disable_Atomic_Synchronization in the
21949 GNAT Reference Manual. If performance is critical, and
21950 such synchronization code is not required, it may be
21951 useful to disable it.
21953 @node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
21954 @anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{1b5}@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{1b6}
21955 @subsubsection Passive Task Optimization
21958 @geindex Passive Task
21960 A passive task is one which is sufficiently simple that
21961 in theory a compiler could recognize it an implement it
21962 efficiently without creating a new thread. The original design
21963 of Ada 83 had in mind this kind of passive task optimization, but
21964 only a few Ada 83 compilers attempted it. The problem was that
21965 it was difficult to determine the exact conditions under which
21966 the optimization was possible. The result is a very fragile
21967 optimization where a very minor change in the program can
21968 suddenly silently make a task non-optimizable.
21970 With the revisiting of this issue in Ada 95, there was general
21971 agreement that this approach was fundamentally flawed, and the
21972 notion of protected types was introduced. When using protected
21973 types, the restrictions are well defined, and you KNOW that the
21974 operations will be optimized, and furthermore this optimized
21975 performance is fully portable.
21977 Although it would theoretically be possible for GNAT to attempt to
21978 do this optimization, but it really doesn't make sense in the
21979 context of Ada 95, and none of the Ada 95 compilers implement
21980 this optimization as far as we know. In particular GNAT never
21981 attempts to perform this optimization.
21983 In any new Ada 95 code that is written, you should always
21984 use protected types in place of tasks that might be able to
21985 be optimized in this manner.
21986 Of course this does not help if you have legacy Ada 83 code
21987 that depends on this optimization, but it is unusual to encounter
21988 a case where the performance gains from this optimization
21989 are significant.
21991 Your program should work correctly without this optimization. If
21992 you have performance problems, then the most practical
21993 approach is to figure out exactly where these performance problems
21994 arise, and update those particular tasks to be protected types. Note
21995 that typically clients of the tasks who call entries, will not have
21996 to be modified, only the task definition itself.
21998 @node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
21999 @anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{1b7}@anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{1b8}
22000 @subsection @code{Text_IO} Suggestions
22003 @geindex Text_IO and performance
22005 The @code{Ada.Text_IO} package has fairly high overheads due in part to
22006 the requirement of maintaining page and line counts. If performance
22007 is critical, a recommendation is to use @code{Stream_IO} instead of
22008 @code{Text_IO} for volume output, since this package has less overhead.
22010 If @code{Text_IO} must be used, note that by default output to the standard
22011 output and standard error files is unbuffered (this provides better
22012 behavior when output statements are used for debugging, or if the
22013 progress of a program is observed by tracking the output, e.g. by
22014 using the Unix @emph{tail -f} command to watch redirected output.
22016 If you are generating large volumes of output with @code{Text_IO} and
22017 performance is an important factor, use a designated file instead
22018 of the standard output file, or change the standard output file to
22019 be buffered using @code{Interfaces.C_Streams.setvbuf}.
22021 @node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
22022 @anchor{gnat_ugn/gnat_and_program_execution id44}@anchor{1b9}@anchor{gnat_ugn/gnat_and_program_execution reducing-size-of-executables-with-unused-subprogram-data-elimination}@anchor{1ba}
22023 @subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
22026 @geindex Uunused subprogram/data elimination
22028 This section describes how you can eliminate unused subprograms and data from
22029 your executable just by setting options at compilation time.
22031 @menu
22032 * About unused subprogram/data elimination:: 
22033 * Compilation options:: 
22034 * Example of unused subprogram/data elimination:: 
22036 @end menu
22038 @node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
22039 @anchor{gnat_ugn/gnat_and_program_execution id45}@anchor{1bb}@anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{1bc}
22040 @subsubsection About unused subprogram/data elimination
22043 By default, an executable contains all code and data of its composing objects
22044 (directly linked or coming from statically linked libraries), even data or code
22045 never used by this executable.
22047 This feature will allow you to eliminate such unused code from your
22048 executable, making it smaller (in disk and in memory).
22050 This functionality is available on all Linux platforms except for the IA-64
22051 architecture and on all cross platforms using the ELF binary file format.
22052 In both cases GNU binutils version 2.16 or later are required to enable it.
22054 @node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
22055 @anchor{gnat_ugn/gnat_and_program_execution id46}@anchor{1bd}@anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{1be}
22056 @subsubsection Compilation options
22059 The operation of eliminating the unused code and data from the final executable
22060 is directly performed by the linker.
22062 @geindex -ffunction-sections (gcc)
22064 @geindex -fdata-sections (gcc)
22066 In order to do this, it has to work with objects compiled with the
22067 following options:
22068 @code{-ffunction-sections} @code{-fdata-sections}.
22070 These options are usable with C and Ada files.
22071 They will place respectively each
22072 function or data in a separate section in the resulting object file.
22074 Once the objects and static libraries are created with these options, the
22075 linker can perform the dead code elimination. You can do this by setting
22076 the @code{-Wl,--gc-sections} option to gcc command or in the
22077 @code{-largs} section of @code{gnatmake}. This will perform a
22078 garbage collection of code and data never referenced.
22080 If the linker performs a partial link (@code{-r} linker option), then you
22081 will need to provide the entry point using the @code{-e} / @code{--entry}
22082 linker option.
22084 Note that objects compiled without the @code{-ffunction-sections} and
22085 @code{-fdata-sections} options can still be linked with the executable.
22086 However, no dead code elimination will be performed on those objects (they will
22087 be linked as is).
22089 The GNAT static library is now compiled with -ffunction-sections and
22090 -fdata-sections on some platforms. This allows you to eliminate the unused code
22091 and data of the GNAT library from your executable.
22093 @node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
22094 @anchor{gnat_ugn/gnat_and_program_execution id47}@anchor{1bf}@anchor{gnat_ugn/gnat_and_program_execution example-of-unused-subprogram-data-elimination}@anchor{1c0}
22095 @subsubsection Example of unused subprogram/data elimination
22098 Here is a simple example:
22100 @quotation
22102 @example
22103 with Aux;
22105 procedure Test is
22106 begin
22107    Aux.Used (10);
22108 end Test;
22110 package Aux is
22111    Used_Data   : Integer;
22112    Unused_Data : Integer;
22114    procedure Used   (Data : Integer);
22115    procedure Unused (Data : Integer);
22116 end Aux;
22118 package body Aux is
22119    procedure Used (Data : Integer) is
22120    begin
22121       Used_Data := Data;
22122    end Used;
22124    procedure Unused (Data : Integer) is
22125    begin
22126       Unused_Data := Data;
22127    end Unused;
22128 end Aux;
22129 @end example
22130 @end quotation
22132 @code{Unused} and @code{Unused_Data} are never referenced in this code
22133 excerpt, and hence they may be safely removed from the final executable.
22135 @quotation
22137 @example
22138 $ gnatmake test
22140 $ nm test | grep used
22141 020015f0 T aux__unused
22142 02005d88 B aux__unused_data
22143 020015cc T aux__used
22144 02005d84 B aux__used_data
22146 $ gnatmake test -cargs -fdata-sections -ffunction-sections \\
22147      -largs -Wl,--gc-sections
22149 $ nm test | grep used
22150 02005350 T aux__used
22151 0201ffe0 B aux__used_data
22152 @end example
22153 @end quotation
22155 It can be observed that the procedure @code{Unused} and the object
22156 @code{Unused_Data} are removed by the linker when using the
22157 appropriate options.
22159 @geindex Overflow checks
22161 @geindex Checks (overflow)
22164 @node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
22165 @anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{16a}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{27}
22166 @section Overflow Check Handling in GNAT
22169 This section explains how to control the handling of overflow checks.
22171 @menu
22172 * Background:: 
22173 * Management of Overflows in GNAT:: 
22174 * Specifying the Desired Mode:: 
22175 * Default Settings:: 
22176 * Implementation Notes:: 
22178 @end menu
22180 @node Background,Management of Overflows in GNAT,,Overflow Check Handling in GNAT
22181 @anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{1c1}@anchor{gnat_ugn/gnat_and_program_execution background}@anchor{1c2}
22182 @subsection Background
22185 Overflow checks are checks that the compiler may make to ensure
22186 that intermediate results are not out of range. For example:
22188 @quotation
22190 @example
22191 A : Integer;
22193 A := A + 1;
22194 @end example
22195 @end quotation
22197 If @code{A} has the value @code{Integer'Last}, then the addition may cause
22198 overflow since the result is out of range of the type @code{Integer}.
22199 In this case @code{Constraint_Error} will be raised if checks are
22200 enabled.
22202 A trickier situation arises in examples like the following:
22204 @quotation
22206 @example
22207 A, C : Integer;
22209 A := (A + 1) + C;
22210 @end example
22211 @end quotation
22213 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
22214 Now the final result of the expression on the right hand side is
22215 @code{Integer'Last} which is in range, but the question arises whether the
22216 intermediate addition of @code{(A + 1)} raises an overflow error.
22218 The (perhaps surprising) answer is that the Ada language
22219 definition does not answer this question. Instead it leaves
22220 it up to the implementation to do one of two things if overflow
22221 checks are enabled.
22224 @itemize *
22226 @item 
22227 raise an exception (@code{Constraint_Error}), or
22229 @item 
22230 yield the correct mathematical result which is then used in
22231 subsequent operations.
22232 @end itemize
22234 If the compiler chooses the first approach, then the assignment of this
22235 example will indeed raise @code{Constraint_Error} if overflow checking is
22236 enabled, or result in erroneous execution if overflow checks are suppressed.
22238 But if the compiler
22239 chooses the second approach, then it can perform both additions yielding
22240 the correct mathematical result, which is in range, so no exception
22241 will be raised, and the right result is obtained, regardless of whether
22242 overflow checks are suppressed.
22244 Note that in the first example an
22245 exception will be raised in either case, since if the compiler
22246 gives the correct mathematical result for the addition, it will
22247 be out of range of the target type of the assignment, and thus
22248 fails the range check.
22250 This lack of specified behavior in the handling of overflow for
22251 intermediate results is a source of non-portability, and can thus
22252 be problematic when programs are ported. Most typically this arises
22253 in a situation where the original compiler did not raise an exception,
22254 and then the application is moved to a compiler where the check is
22255 performed on the intermediate result and an unexpected exception is
22256 raised.
22258 Furthermore, when using Ada 2012's preconditions and other
22259 assertion forms, another issue arises. Consider:
22261 @quotation
22263 @example
22264 procedure P (A, B : Integer) with
22265   Pre => A + B <= Integer'Last;
22266 @end example
22267 @end quotation
22269 One often wants to regard arithmetic in a context like this from
22270 a mathematical point of view. So for example, if the two actual parameters
22271 for a call to @code{P} are both @code{Integer'Last}, then
22272 the precondition should be regarded as False. If we are executing
22273 in a mode with run-time checks enabled for preconditions, then we would
22274 like this precondition to fail, rather than raising an exception
22275 because of the intermediate overflow.
22277 However, the language definition leaves the specification of
22278 whether the above condition fails (raising @code{Assert_Error}) or
22279 causes an intermediate overflow (raising @code{Constraint_Error})
22280 up to the implementation.
22282 The situation is worse in a case such as the following:
22284 @quotation
22286 @example
22287 procedure Q (A, B, C : Integer) with
22288   Pre => A + B + C <= Integer'Last;
22289 @end example
22290 @end quotation
22292 Consider the call
22294 @quotation
22296 @example
22297 Q (A => Integer'Last, B => 1, C => -1);
22298 @end example
22299 @end quotation
22301 From a mathematical point of view the precondition
22302 is True, but at run time we may (but are not guaranteed to) get an
22303 exception raised because of the intermediate overflow (and we really
22304 would prefer this precondition to be considered True at run time).
22306 @node Management of Overflows in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
22307 @anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{1c3}@anchor{gnat_ugn/gnat_and_program_execution management-of-overflows-in-gnat}@anchor{1c4}
22308 @subsection Management of Overflows in GNAT
22311 To deal with the portability issue, and with the problem of
22312 mathematical versus run-time interpretation of the expressions in
22313 assertions, GNAT provides comprehensive control over the handling
22314 of intermediate overflow. GNAT can operate in three modes, and
22315 furthemore, permits separate selection of operating modes for
22316 the expressions within assertions (here the term 'assertions'
22317 is used in the technical sense, which includes preconditions and so forth)
22318 and for expressions appearing outside assertions.
22320 The three modes are:
22323 @itemize *
22325 @item 
22326 @emph{Use base type for intermediate operations} (@code{STRICT})
22328 In this mode, all intermediate results for predefined arithmetic
22329 operators are computed using the base type, and the result must
22330 be in range of the base type. If this is not the
22331 case then either an exception is raised (if overflow checks are
22332 enabled) or the execution is erroneous (if overflow checks are suppressed).
22333 This is the normal default mode.
22335 @item 
22336 @emph{Most intermediate overflows avoided} (@code{MINIMIZED})
22338 In this mode, the compiler attempts to avoid intermediate overflows by
22339 using a larger integer type, typically @code{Long_Long_Integer},
22340 as the type in which arithmetic is
22341 performed for predefined arithmetic operators. This may be slightly more
22342 expensive at
22343 run time (compared to suppressing intermediate overflow checks), though
22344 the cost is negligible on modern 64-bit machines. For the examples given
22345 earlier, no intermediate overflows would have resulted in exceptions,
22346 since the intermediate results are all in the range of
22347 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
22348 of GNAT). In addition, if checks are enabled, this reduces the number of
22349 checks that must be made, so this choice may actually result in an
22350 improvement in space and time behavior.
22352 However, there are cases where @code{Long_Long_Integer} is not large
22353 enough, consider the following example:
22355 @quotation
22357 @example
22358 procedure R (A, B, C, D : Integer) with
22359   Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
22360 @end example
22361 @end quotation
22363 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
22364 Now the intermediate results are
22365 out of the range of @code{Long_Long_Integer} even though the final result
22366 is in range and the precondition is True (from a mathematical point
22367 of view). In such a case, operating in this mode, an overflow occurs
22368 for the intermediate computation (which is why this mode
22369 says @emph{most} intermediate overflows are avoided). In this case,
22370 an exception is raised if overflow checks are enabled, and the
22371 execution is erroneous if overflow checks are suppressed.
22373 @item 
22374 @emph{All intermediate overflows avoided} (@code{ELIMINATED})
22376 In this mode, the compiler  avoids all intermediate overflows
22377 by using arbitrary precision arithmetic as required. In this
22378 mode, the above example with @code{A**2 * B**2} would
22379 not cause intermediate overflow, because the intermediate result
22380 would be evaluated using sufficient precision, and the result
22381 of evaluating the precondition would be True.
22383 This mode has the advantage of avoiding any intermediate
22384 overflows, but at the expense of significant run-time overhead,
22385 including the use of a library (included automatically in this
22386 mode) for multiple-precision arithmetic.
22388 This mode provides cleaner semantics for assertions, since now
22389 the run-time behavior emulates true arithmetic behavior for the
22390 predefined arithmetic operators, meaning that there is never a
22391 conflict between the mathematical view of the assertion, and its
22392 run-time behavior.
22394 Note that in this mode, the behavior is unaffected by whether or
22395 not overflow checks are suppressed, since overflow does not occur.
22396 It is possible for gigantic intermediate expressions to raise
22397 @code{Storage_Error} as a result of attempting to compute the
22398 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
22399 but overflow is impossible.
22400 @end itemize
22402 Note that these modes apply only to the evaluation of predefined
22403 arithmetic, membership, and comparison operators for signed integer
22404 arithmetic.
22406 For fixed-point arithmetic, checks can be suppressed. But if checks
22407 are enabled
22408 then fixed-point values are always checked for overflow against the
22409 base type for intermediate expressions (that is such checks always
22410 operate in the equivalent of @code{STRICT} mode).
22412 For floating-point, on nearly all architectures, @code{Machine_Overflows}
22413 is False, and IEEE infinities are generated, so overflow exceptions
22414 are never raised. If you want to avoid infinities, and check that
22415 final results of expressions are in range, then you can declare a
22416 constrained floating-point type, and range checks will be carried
22417 out in the normal manner (with infinite values always failing all
22418 range checks).
22420 @node Specifying the Desired Mode,Default Settings,Management of Overflows in GNAT,Overflow Check Handling in GNAT
22421 @anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{f8}@anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{1c5}
22422 @subsection Specifying the Desired Mode
22425 @geindex pragma Overflow_Mode
22427 The desired mode of for handling intermediate overflow can be specified using
22428 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
22429 The pragma has the form
22431 @quotation
22433 @example
22434 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
22435 @end example
22436 @end quotation
22438 where @code{MODE} is one of
22441 @itemize *
22443 @item 
22444 @code{STRICT}:  intermediate overflows checked (using base type)
22446 @item 
22447 @code{MINIMIZED}: minimize intermediate overflows
22449 @item 
22450 @code{ELIMINATED}: eliminate intermediate overflows
22451 @end itemize
22453 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
22454 @code{minimized} all have the same effect.
22456 If only the @code{General} parameter is present, then the given @code{MODE} applies
22457 to expressions both within and outside assertions. If both arguments
22458 are present, then @code{General} applies to expressions outside assertions,
22459 and @code{Assertions} applies to expressions within assertions. For example:
22461 @quotation
22463 @example
22464 pragma Overflow_Mode
22465   (General => Minimized, Assertions => Eliminated);
22466 @end example
22467 @end quotation
22469 specifies that general expressions outside assertions be evaluated
22470 in 'minimize intermediate overflows' mode, and expressions within
22471 assertions be evaluated in 'eliminate intermediate overflows' mode.
22472 This is often a reasonable choice, avoiding excessive overhead
22473 outside assertions, but assuring a high degree of portability
22474 when importing code from another compiler, while incurring
22475 the extra overhead for assertion expressions to ensure that
22476 the behavior at run time matches the expected mathematical
22477 behavior.
22479 The @code{Overflow_Mode} pragma has the same scoping and placement
22480 rules as pragma @code{Suppress}, so it can occur either as a
22481 configuration pragma, specifying a default for the whole
22482 program, or in a declarative scope, where it applies to the
22483 remaining declarations and statements in that scope.
22485 Note that pragma @code{Overflow_Mode} does not affect whether
22486 overflow checks are enabled or suppressed. It only controls the
22487 method used to compute intermediate values. To control whether
22488 overflow checking is enabled or suppressed, use pragma @code{Suppress}
22489 or @code{Unsuppress} in the usual manner.
22491 @geindex -gnato? (gcc)
22493 @geindex -gnato?? (gcc)
22495 Additionally, a compiler switch @code{-gnato?} or @code{-gnato??}
22496 can be used to control the checking mode default (which can be subsequently
22497 overridden using pragmas).
22499 Here @code{?} is one of the digits @code{1} through @code{3}:
22501 @quotation
22504 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
22505 @item
22507 @code{1}
22509 @tab
22511 use base type for intermediate operations (@code{STRICT})
22513 @item
22515 @code{2}
22517 @tab
22519 minimize intermediate overflows (@code{MINIMIZED})
22521 @item
22523 @code{3}
22525 @tab
22527 eliminate intermediate overflows (@code{ELIMINATED})
22529 @end multitable
22531 @end quotation
22533 As with the pragma, if only one digit appears then it applies to all
22534 cases; if two digits are given, then the first applies outside
22535 assertions, and the second within assertions. Thus the equivalent
22536 of the example pragma above would be
22537 @code{-gnato23}.
22539 If no digits follow the @code{-gnato}, then it is equivalent to
22540 @code{-gnato11},
22541 causing all intermediate operations to be computed using the base
22542 type (@code{STRICT} mode).
22544 @node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
22545 @anchor{gnat_ugn/gnat_and_program_execution id59}@anchor{1c6}@anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{1c7}
22546 @subsection Default Settings
22549 The default mode for overflow checks is
22551 @quotation
22553 @example
22554 General => Strict
22555 @end example
22556 @end quotation
22558 which causes all computations both inside and outside assertions to use
22559 the base type.
22561 This retains compatibility with previous versions of
22562 GNAT which suppressed overflow checks by default and always
22563 used the base type for computation of intermediate results.
22565 @c Sphinx allows no emphasis within :index: role. As a workaround we
22566 @c point the index to "switch" and use emphasis for "-gnato".
22568 The 
22569 @geindex -gnato (gcc)
22570 switch @code{-gnato} (with no digits following)
22571 is equivalent to
22573 @quotation
22575 @example
22576 General => Strict
22577 @end example
22578 @end quotation
22580 which causes overflow checking of all intermediate overflows
22581 both inside and outside assertions against the base type.
22583 The pragma @code{Suppress (Overflow_Check)} disables overflow
22584 checking, but it has no effect on the method used for computing
22585 intermediate results.
22587 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
22588 checking, but it has no effect on the method used for computing
22589 intermediate results.
22591 @node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
22592 @anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{1c8}@anchor{gnat_ugn/gnat_and_program_execution id60}@anchor{1c9}
22593 @subsection Implementation Notes
22596 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
22597 reasonably efficient, and can be generally used. It also helps
22598 to ensure compatibility with code imported from some other
22599 compiler to GNAT.
22601 Setting all intermediate overflows checking (@code{CHECKED} mode)
22602 makes sense if you want to
22603 make sure that your code is compatible with any other possible
22604 Ada implementation. This may be useful in ensuring portability
22605 for code that is to be exported to some other compiler than GNAT.
22607 The Ada standard allows the reassociation of expressions at
22608 the same precedence level if no parentheses are present. For
22609 example, @code{A+B+C} parses as though it were @code{(A+B)+C}, but
22610 the compiler can reintepret this as @code{A+(B+C)}, possibly
22611 introducing or eliminating an overflow exception. The GNAT
22612 compiler never takes advantage of this freedom, and the
22613 expression @code{A+B+C} will be evaluated as @code{(A+B)+C}.
22614 If you need the other order, you can write the parentheses
22615 explicitly @code{A+(B+C)} and GNAT will respect this order.
22617 The use of @code{ELIMINATED} mode will cause the compiler to
22618 automatically include an appropriate arbitrary precision
22619 integer arithmetic package. The compiler will make calls
22620 to this package, though only in cases where it cannot be
22621 sure that @code{Long_Long_Integer} is sufficient to guard against
22622 intermediate overflows. This package does not use dynamic
22623 alllocation, but it does use the secondary stack, so an
22624 appropriate secondary stack package must be present (this
22625 is always true for standard full Ada, but may require
22626 specific steps for restricted run times such as ZFP).
22628 Although @code{ELIMINATED} mode causes expressions to use arbitrary
22629 precision arithmetic, avoiding overflow, the final result
22630 must be in an appropriate range. This is true even if the
22631 final result is of type @code{[Long_[Long_]]Integer'Base}, which
22632 still has the same bounds as its associated constrained
22633 type at run-time.
22635 Currently, the @code{ELIMINATED} mode is only available on target
22636 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
22637 platforms).
22639 @node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
22640 @anchor{gnat_ugn/gnat_and_program_execution id61}@anchor{16b}@anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{28}
22641 @section Performing Dimensionality Analysis in GNAT
22644 @geindex Dimensionality analysis
22646 The GNAT compiler supports dimensionality checking. The user can
22647 specify physical units for objects, and the compiler will verify that uses
22648 of these objects are compatible with their dimensions, in a fashion that is
22649 familiar to engineering practice. The dimensions of algebraic expressions
22650 (including powers with static exponents) are computed from their constituents.
22652 @geindex Dimension_System aspect
22654 @geindex Dimension aspect
22656 This feature depends on Ada 2012 aspect specifications, and is available from
22657 version 7.0.1 of GNAT onwards.
22658 The GNAT-specific aspect @code{Dimension_System}
22659 allows you to define a system of units; the aspect @code{Dimension}
22660 then allows the user to declare dimensioned quantities within a given system.
22661 (These aspects are described in the @emph{Implementation Defined Aspects}
22662 chapter of the @emph{GNAT Reference Manual}).
22664 The major advantage of this model is that it does not require the declaration of
22665 multiple operators for all possible combinations of types: it is only necessary
22666 to use the proper subtypes in object declarations.
22668 @geindex System.Dim.Mks package (GNAT library)
22670 @geindex MKS_Type type
22672 The simplest way to impose dimensionality checking on a computation is to make
22673 use of the package @code{System.Dim.Mks},
22674 which is part of the GNAT library. This
22675 package defines a floating-point type @code{MKS_Type},
22676 for which a sequence of
22677 dimension names are specified, together with their conventional abbreviations.
22678 The following should be read together with the full specification of the
22679 package, in file @code{s-dimmks.ads}.
22681 @quotation
22683 @geindex s-dimmks.ads file
22685 @example
22686 type Mks_Type is new Long_Long_Float
22687   with
22688    Dimension_System => (
22689      (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
22690      (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
22691      (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
22692      (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
22693      (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
22694      (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
22695      (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
22696 @end example
22697 @end quotation
22699 The package then defines a series of subtypes that correspond to these
22700 conventional units. For example:
22702 @quotation
22704 @example
22705 subtype Length is Mks_Type
22706   with
22707    Dimension => (Symbol => 'm', Meter  => 1, others => 0);
22708 @end example
22709 @end quotation
22711 and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
22712 @code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
22713 @code{Luminous_Intensity} (the standard set of units of the SI system).
22715 The package also defines conventional names for values of each unit, for
22716 example:
22718 @quotation
22720 @example
22721 m   : constant Length           := 1.0;
22722 kg  : constant Mass             := 1.0;
22723 s   : constant Time             := 1.0;
22724 A   : constant Electric_Current := 1.0;
22725 @end example
22726 @end quotation
22728 as well as useful multiples of these units:
22730 @quotation
22732 @example
22733  cm  : constant Length := 1.0E-02;
22734  g   : constant Mass   := 1.0E-03;
22735  min : constant Time   := 60.0;
22736  day : constant Time   := 60.0 * 24.0 * min;
22738 @end example
22739 @end quotation
22741 Using this package, you can then define a derived unit by
22742 providing the aspect that
22743 specifies its dimensions within the MKS system, as well as the string to
22744 be used for output of a value of that unit:
22746 @quotation
22748 @example
22749 subtype Acceleration is Mks_Type
22750   with Dimension => ("m/sec^2",
22751                      Meter => 1,
22752                      Second => -2,
22753                      others => 0);
22754 @end example
22755 @end quotation
22757 Here is a complete example of use:
22759 @quotation
22761 @example
22762 with System.Dim.MKS; use System.Dim.Mks;
22763 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
22764 with Text_IO; use Text_IO;
22765 procedure Free_Fall is
22766   subtype Acceleration is Mks_Type
22767     with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
22768   G : constant acceleration := 9.81 * m / (s ** 2);
22769   T : Time := 10.0*s;
22770   Distance : Length;
22772 begin
22773   Put ("Gravitational constant: ");
22774   Put (G, Aft => 2, Exp => 0); Put_Line ("");
22775   Distance := 0.5 * G * T ** 2;
22776   Put ("distance travelled in 10 seconds of free fall ");
22777   Put (Distance, Aft => 2, Exp => 0);
22778   Put_Line ("");
22779 end Free_Fall;
22780 @end example
22781 @end quotation
22783 Execution of this program yields:
22785 @quotation
22787 @example
22788 Gravitational constant:  9.81 m/sec^2
22789 distance travelled in 10 seconds of free fall 490.50 m
22790 @end example
22791 @end quotation
22793 However, incorrect assignments such as:
22795 @quotation
22797 @example
22798 Distance := 5.0;
22799 Distance := 5.0 * kg;
22800 @end example
22801 @end quotation
22803 are rejected with the following diagnoses:
22805 @quotation
22807 @example
22808 Distance := 5.0;
22809    >>> dimensions mismatch in assignment
22810    >>> left-hand side has dimension [L]
22811    >>> right-hand side is dimensionless
22813 Distance := 5.0 * kg:
22814    >>> dimensions mismatch in assignment
22815    >>> left-hand side has dimension [L]
22816    >>> right-hand side has dimension [M]
22817 @end example
22818 @end quotation
22820 The dimensions of an expression are properly displayed, even if there is
22821 no explicit subtype for it. If we add to the program:
22823 @quotation
22825 @example
22826 Put ("Final velocity: ");
22827 Put (G * T, Aft =>2, Exp =>0);
22828 Put_Line ("");
22829 @end example
22830 @end quotation
22832 then the output includes:
22834 @quotation
22836 @example
22837 Final velocity: 98.10 m.s**(-1)
22838 @end example
22840 @geindex Dimensionable type
22842 @geindex Dimensioned subtype
22843 @end quotation
22845 The type @code{Mks_Type} is said to be a @emph{dimensionable type} since it has a
22846 @code{Dimension_System} aspect, and the subtypes @code{Length}, @code{Mass}, etc.,
22847 are said to be @emph{dimensioned subtypes} since each one has a @code{Dimension}
22848 aspect.
22850 @quotation
22852 @geindex Dimension Vector (for a dimensioned subtype)
22854 @geindex Dimension aspect
22856 @geindex Dimension_System aspect
22857 @end quotation
22859 The @code{Dimension} aspect of a dimensioned subtype @code{S} defines a mapping
22860 from the base type's Unit_Names to integer (or, more generally, rational)
22861 values. This mapping is the @emph{dimension vector} (also referred to as the
22862 @emph{dimensionality}) for that subtype, denoted by @code{DV(S)}, and thus for each
22863 object of that subtype. Intuitively, the value specified for each
22864 @code{Unit_Name} is the exponent associated with that unit; a zero value
22865 means that the unit is not used. For example:
22867 @quotation
22869 @example
22870 declare
22871    Acc : Acceleration;
22872    ...
22873 begin
22874    ...
22875 end;
22876 @end example
22877 @end quotation
22879 Here @code{DV(Acc)} = @code{DV(Acceleration)} =
22880 @code{(Meter=>1, Kilogram=>0, Second=>-2, Ampere=>0, Kelvin=>0, Mole=>0, Candela=>0)}.
22881 Symbolically, we can express this as @code{Meter / Second**2}.
22883 The dimension vector of an arithmetic expression is synthesized from the
22884 dimension vectors of its components, with compile-time dimensionality checks
22885 that help prevent mismatches such as using an @code{Acceleration} where a
22886 @code{Length} is required.
22888 The dimension vector of the result of an arithmetic expression @emph{expr}, or
22889 @code{DV(@emph{expr})}, is defined as follows, assuming conventional
22890 mathematical definitions for the vector operations that are used:
22893 @itemize *
22895 @item 
22896 If @emph{expr} is of the type @emph{universal_real}, or is not of a dimensioned subtype,
22897 then @emph{expr} is dimensionless; @code{DV(@emph{expr})} is the empty vector.
22899 @item 
22900 @code{DV(@emph{op expr})}, where @emph{op} is a unary operator, is @code{DV(@emph{expr})}
22902 @item 
22903 @code{DV(@emph{expr1 op expr2})} where @emph{op} is "+" or "-" is @code{DV(@emph{expr1})}
22904 provided that @code{DV(@emph{expr1})} = @code{DV(@emph{expr2})}.
22905 If this condition is not met then the construct is illegal.
22907 @item 
22908 @code{DV(@emph{expr1} * @emph{expr2})} is @code{DV(@emph{expr1})} + @code{DV(@emph{expr2})},
22909 and @code{DV(@emph{expr1} / @emph{expr2})} = @code{DV(@emph{expr1})} - @code{DV(@emph{expr2})}.
22910 In this context if one of the @emph{expr}s is dimensionless then its empty
22911 dimension vector is treated as @code{(others => 0)}.
22913 @item 
22914 @code{DV(@emph{expr} ** @emph{power})} is @emph{power} * @code{DV(@emph{expr})},
22915 provided that @emph{power} is a static rational value. If this condition is not
22916 met then the construct is illegal.
22917 @end itemize
22919 Note that, by the above rules, it is illegal to use binary "+" or "-" to
22920 combine a dimensioned and dimensionless value.  Thus an expression such as
22921 @code{acc-10.0} is illegal, where @code{acc} is an object of subtype
22922 @code{Acceleration}.
22924 The dimensionality checks for relationals use the same rules as
22925 for "+" and "-", except when comparing to a literal; thus
22927 @quotation
22929 @example
22930 acc > len
22931 @end example
22932 @end quotation
22934 is equivalent to
22936 @quotation
22938 @example
22939 acc-len > 0.0
22940 @end example
22941 @end quotation
22943 and is thus illegal, but
22945 @quotation
22947 @example
22948 acc > 10.0
22949 @end example
22950 @end quotation
22952 is accepted with a warning. Analogously a conditional expression requires the
22953 same dimension vector for each branch (with no exception for literals).
22955 The dimension vector of a type conversion @code{T(@emph{expr})} is defined
22956 as follows, based on the nature of @code{T}:
22959 @itemize *
22961 @item 
22962 If @code{T} is a dimensioned subtype then @code{DV(T(@emph{expr}))} is @code{DV(T)}
22963 provided that either @emph{expr} is dimensionless or
22964 @code{DV(T)} = @code{DV(@emph{expr})}. The conversion is illegal
22965 if @emph{expr} is dimensioned and @code{DV(@emph{expr})} /= @code{DV(T)}.
22966 Note that vector equality does not require that the corresponding
22967 Unit_Names be the same.
22969 As a consequence of the above rule, it is possible to convert between
22970 different dimension systems that follow the same international system
22971 of units, with the seven physical components given in the standard order
22972 (length, mass, time, etc.). Thus a length in meters can be converted to
22973 a length in inches (with a suitable conversion factor) but cannot be
22974 converted, for example, to a mass in pounds.
22976 @item 
22977 If @code{T} is the base type for @emph{expr} (and the dimensionless root type of
22978 the dimension system), then @code{DV(T(@emph{expr}))} is @code{DV(expr)}.
22979 Thus, if @emph{expr} is of a dimensioned subtype of @code{T}, the conversion may
22980 be regarded as a "view conversion" that preserves dimensionality.
22982 This rule makes it possible to write generic code that can be instantiated
22983 with compatible dimensioned subtypes.  The generic unit will contain
22984 conversions that will consequently be present in instantiations, but
22985 conversions to the base type will preserve dimensionality and make it
22986 possible to write generic code that is correct with respect to
22987 dimensionality.
22989 @item 
22990 Otherwise (i.e., @code{T} is neither a dimensioned subtype nor a dimensionable
22991 base type), @code{DV(T(@emph{expr}))} is the empty vector. Thus a dimensioned
22992 value can be explicitly converted to a non-dimensioned subtype, which
22993 of course then escapes dimensionality analysis.
22994 @end itemize
22996 The dimension vector for a type qualification @code{T'(@emph{expr})} is the same
22997 as for the type conversion @code{T(@emph{expr})}.
22999 An assignment statement
23001 @quotation
23003 @example
23004 Source := Target;
23005 @end example
23006 @end quotation
23008 requires @code{DV(Source)} = @code{DV(Target)}, and analogously for parameter
23009 passing (the dimension vector for the actual parameter must be equal to the
23010 dimension vector for the formal parameter).
23012 @node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
23013 @anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{29}@anchor{gnat_ugn/gnat_and_program_execution id62}@anchor{16c}
23014 @section Stack Related Facilities
23017 This section describes some useful tools associated with stack
23018 checking and analysis. In
23019 particular, it deals with dynamic and static stack usage measurements.
23021 @menu
23022 * Stack Overflow Checking:: 
23023 * Static Stack Usage Analysis:: 
23024 * Dynamic Stack Usage Analysis:: 
23026 @end menu
23028 @node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
23029 @anchor{gnat_ugn/gnat_and_program_execution id63}@anchor{1ca}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{f4}
23030 @subsection Stack Overflow Checking
23033 @geindex Stack Overflow Checking
23035 @geindex -fstack-check (gcc)
23037 For most operating systems, @code{gcc} does not perform stack overflow
23038 checking by default. This means that if the main environment task or
23039 some other task exceeds the available stack space, then unpredictable
23040 behavior will occur. Most native systems offer some level of protection by
23041 adding a guard page at the end of each task stack. This mechanism is usually
23042 not enough for dealing properly with stack overflow situations because
23043 a large local variable could "jump" above the guard page.
23044 Furthermore, when the
23045 guard page is hit, there may not be any space left on the stack for executing
23046 the exception propagation code. Enabling stack checking avoids
23047 such situations.
23049 To activate stack checking, compile all units with the @code{gcc} option
23050 @code{-fstack-check}. For example:
23052 @quotation
23054 @example
23055 $ gcc -c -fstack-check package1.adb
23056 @end example
23057 @end quotation
23059 Units compiled with this option will generate extra instructions to check
23060 that any use of the stack (for procedure calls or for declaring local
23061 variables in declare blocks) does not exceed the available stack space.
23062 If the space is exceeded, then a @code{Storage_Error} exception is raised.
23064 For declared tasks, the default stack size is defined by the GNAT runtime,
23065 whose size may be modified at bind time through the @code{-d} bind switch
23066 (@ref{11f,,Switches for gnatbind}). Task specific stack sizes may be set using the
23067 @code{Storage_Size} pragma.
23069 For the environment task, the stack size is determined by the operating system.
23070 Consequently, to modify the size of the environment task please refer to your
23071 operating system documentation.
23073 @node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
23074 @anchor{gnat_ugn/gnat_and_program_execution id64}@anchor{1cb}@anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{f5}
23075 @subsection Static Stack Usage Analysis
23078 @geindex Static Stack Usage Analysis
23080 @geindex -fstack-usage
23082 A unit compiled with @code{-fstack-usage} will generate an extra file
23083 that specifies
23084 the maximum amount of stack used, on a per-function basis.
23085 The file has the same
23086 basename as the target object file with a @code{.su} extension.
23087 Each line of this file is made up of three fields:
23090 @itemize *
23092 @item 
23093 The name of the function.
23095 @item 
23096 A number of bytes.
23098 @item 
23099 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
23100 @end itemize
23102 The second field corresponds to the size of the known part of the function
23103 frame.
23105 The qualifier @code{static} means that the function frame size
23106 is purely static.
23107 It usually means that all local variables have a static size.
23108 In this case, the second field is a reliable measure of the function stack
23109 utilization.
23111 The qualifier @code{dynamic} means that the function frame size is not static.
23112 It happens mainly when some local variables have a dynamic size. When this
23113 qualifier appears alone, the second field is not a reliable measure
23114 of the function stack analysis. When it is qualified with  @code{bounded}, it
23115 means that the second field is a reliable maximum of the function stack
23116 utilization.
23118 A unit compiled with @code{-Wstack-usage} will issue a warning for each
23119 subprogram whose stack usage might be larger than the specified amount of
23120 bytes.  The wording is in keeping with the qualifier documented above.
23122 @node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
23123 @anchor{gnat_ugn/gnat_and_program_execution id65}@anchor{1cc}@anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{121}
23124 @subsection Dynamic Stack Usage Analysis
23127 It is possible to measure the maximum amount of stack used by a task, by
23128 adding a switch to @code{gnatbind}, as:
23130 @quotation
23132 @example
23133 $ gnatbind -u0 file
23134 @end example
23135 @end quotation
23137 With this option, at each task termination, its stack usage is  output on
23138 @code{stderr}.
23139 It is not always convenient to output the stack usage when the program
23140 is still running. Hence, it is possible to delay this output until program
23141 termination. for a given number of tasks specified as the argument of the
23142 @code{-u} option. For instance:
23144 @quotation
23146 @example
23147 $ gnatbind -u100 file
23148 @end example
23149 @end quotation
23151 will buffer the stack usage information of the first 100 tasks to terminate and
23152 output this info at program termination. Results are displayed in four
23153 columns:
23155 @quotation
23157 @example
23158 Index | Task Name | Stack Size | Stack Usage
23159 @end example
23160 @end quotation
23162 where:
23165 @itemize *
23167 @item 
23168 @emph{Index} is a number associated with each task.
23170 @item 
23171 @emph{Task Name} is the name of the task analyzed.
23173 @item 
23174 @emph{Stack Size} is the maximum size for the stack.
23176 @item 
23177 @emph{Stack Usage} is the measure done by the stack analyzer.
23178 In order to prevent overflow, the stack
23179 is not entirely analyzed, and it's not possible to know exactly how
23180 much has actually been used.
23181 @end itemize
23183 By default the environment task stack, the stack that contains the main unit,
23184 is not processed. To enable processing of the environment task stack, the
23185 environment variable GNAT_STACK_LIMIT needs to be set to the maximum size of
23186 the environment task stack. This amount is given in kilobytes. For example:
23188 @quotation
23190 @example
23191 $ set GNAT_STACK_LIMIT 1600
23192 @end example
23193 @end quotation
23195 would specify to the analyzer that the environment task stack has a limit
23196 of 1.6 megabytes. Any stack usage beyond this will be ignored by the analysis.
23198 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
23199 stack-usage reports at run time. See its body for the details.
23201 @node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
23202 @anchor{gnat_ugn/gnat_and_program_execution id66}@anchor{16d}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{2a}
23203 @section Memory Management Issues
23206 This section describes some useful memory pools provided in the GNAT library
23207 and in particular the GNAT Debug Pool facility, which can be used to detect
23208 incorrect uses of access values (including 'dangling references').
23211 @menu
23212 * Some Useful Memory Pools:: 
23213 * The GNAT Debug Pool Facility:: 
23215 @end menu
23217 @node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
23218 @anchor{gnat_ugn/gnat_and_program_execution id67}@anchor{1cd}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{1ce}
23219 @subsection Some Useful Memory Pools
23222 @geindex Memory Pool
23224 @geindex storage
23225 @geindex pool
23227 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
23228 storage pool. Allocations use the standard system call @code{malloc} while
23229 deallocations use the standard system call @code{free}. No reclamation is
23230 performed when the pool goes out of scope. For performance reasons, the
23231 standard default Ada allocators/deallocators do not use any explicit storage
23232 pools but if they did, they could use this storage pool without any change in
23233 behavior. That is why this storage pool is used  when the user
23234 manages to make the default implicit allocator explicit as in this example:
23236 @quotation
23238 @example
23239 type T1 is access Something;
23240  -- no Storage pool is defined for T2
23242 type T2 is access Something_Else;
23243 for T2'Storage_Pool use T1'Storage_Pool;
23244 -- the above is equivalent to
23245 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
23246 @end example
23247 @end quotation
23249 The @code{System.Pool_Local} package offers the @code{Unbounded_Reclaim_Pool} storage
23250 pool. The allocation strategy is similar to @code{Pool_Local}
23251 except that the all
23252 storage allocated with this pool is reclaimed when the pool object goes out of
23253 scope. This pool provides a explicit mechanism similar to the implicit one
23254 provided by several Ada 83 compilers for allocations performed through a local
23255 access type and whose purpose was to reclaim memory when exiting the
23256 scope of a given local access. As an example, the following program does not
23257 leak memory even though it does not perform explicit deallocation:
23259 @quotation
23261 @example
23262 with System.Pool_Local;
23263 procedure Pooloc1 is
23264    procedure Internal is
23265       type A is access Integer;
23266       X : System.Pool_Local.Unbounded_Reclaim_Pool;
23267       for A'Storage_Pool use X;
23268       v : A;
23269    begin
23270       for I in  1 .. 50 loop
23271          v := new Integer;
23272       end loop;
23273    end Internal;
23274 begin
23275    for I in  1 .. 100 loop
23276       Internal;
23277    end loop;
23278 end Pooloc1;
23279 @end example
23280 @end quotation
23282 The @code{System.Pool_Size} package implements the @code{Stack_Bounded_Pool} used when
23283 @code{Storage_Size} is specified for an access type.
23284 The whole storage for the pool is
23285 allocated at once, usually on the stack at the point where the access type is
23286 elaborated. It is automatically reclaimed when exiting the scope where the
23287 access type is defined. This package is not intended to be used directly by the
23288 user and it is implicitly used for each such declaration:
23290 @quotation
23292 @example
23293 type T1 is access Something;
23294 for T1'Storage_Size use 10_000;
23295 @end example
23296 @end quotation
23298 @node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
23299 @anchor{gnat_ugn/gnat_and_program_execution id68}@anchor{1cf}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{1d0}
23300 @subsection The GNAT Debug Pool Facility
23303 @geindex Debug Pool
23305 @geindex storage
23306 @geindex pool
23307 @geindex memory corruption
23309 The use of unchecked deallocation and unchecked conversion can easily
23310 lead to incorrect memory references. The problems generated by such
23311 references are usually difficult to tackle because the symptoms can be
23312 very remote from the origin of the problem. In such cases, it is
23313 very helpful to detect the problem as early as possible. This is the
23314 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
23316 In order to use the GNAT specific debugging pool, the user must
23317 associate a debug pool object with each of the access types that may be
23318 related to suspected memory problems. See Ada Reference Manual 13.11.
23320 @quotation
23322 @example
23323 type Ptr is access Some_Type;
23324 Pool : GNAT.Debug_Pools.Debug_Pool;
23325 for Ptr'Storage_Pool use Pool;
23326 @end example
23327 @end quotation
23329 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
23330 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
23331 allow the user to redefine allocation and deallocation strategies. They
23332 also provide a checkpoint for each dereference, through the use of
23333 the primitive operation @code{Dereference} which is implicitly called at
23334 each dereference of an access value.
23336 Once an access type has been associated with a debug pool, operations on
23337 values of the type may raise four distinct exceptions,
23338 which correspond to four potential kinds of memory corruption:
23341 @itemize *
23343 @item 
23344 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
23346 @item 
23347 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
23349 @item 
23350 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
23352 @item 
23353 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
23354 @end itemize
23356 For types associated with a Debug_Pool, dynamic allocation is performed using
23357 the standard GNAT allocation routine. References to all allocated chunks of
23358 memory are kept in an internal dictionary. Several deallocation strategies are
23359 provided, whereupon the user can choose to release the memory to the system,
23360 keep it allocated for further invalid access checks, or fill it with an easily
23361 recognizable pattern for debug sessions. The memory pattern is the old IBM
23362 hexadecimal convention: @code{16#DEADBEEF#}.
23364 See the documentation in the file g-debpoo.ads for more information on the
23365 various strategies.
23367 Upon each dereference, a check is made that the access value denotes a
23368 properly allocated memory location. Here is a complete example of use of
23369 @code{Debug_Pools}, that includes typical instances of  memory corruption:
23371 @quotation
23373 @example
23374 with Gnat.Io; use Gnat.Io;
23375 with Unchecked_Deallocation;
23376 with Unchecked_Conversion;
23377 with GNAT.Debug_Pools;
23378 with System.Storage_Elements;
23379 with Ada.Exceptions; use Ada.Exceptions;
23380 procedure Debug_Pool_Test is
23382    type T is access Integer;
23383    type U is access all T;
23385    P : GNAT.Debug_Pools.Debug_Pool;
23386    for T'Storage_Pool use P;
23388    procedure Free is new Unchecked_Deallocation (Integer, T);
23389    function UC is new Unchecked_Conversion (U, T);
23390    A, B : aliased T;
23392    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
23394 begin
23395    Info (P);
23396    A := new Integer;
23397    B := new Integer;
23398    B := A;
23399    Info (P);
23400    Free (A);
23401    begin
23402       Put_Line (Integer'Image(B.all));
23403    exception
23404       when E : others => Put_Line ("raised: " & Exception_Name (E));
23405    end;
23406    begin
23407       Free (B);
23408    exception
23409       when E : others => Put_Line ("raised: " & Exception_Name (E));
23410    end;
23411    B := UC(A'Access);
23412    begin
23413       Put_Line (Integer'Image(B.all));
23414    exception
23415       when E : others => Put_Line ("raised: " & Exception_Name (E));
23416    end;
23417    begin
23418       Free (B);
23419    exception
23420       when E : others => Put_Line ("raised: " & Exception_Name (E));
23421    end;
23422    Info (P);
23423 end Debug_Pool_Test;
23424 @end example
23425 @end quotation
23427 The debug pool mechanism provides the following precise diagnostics on the
23428 execution of this erroneous program:
23430 @quotation
23432 @example
23433 Debug Pool info:
23434   Total allocated bytes :  0
23435   Total deallocated bytes :  0
23436   Current Water Mark:  0
23437   High Water Mark:  0
23439 Debug Pool info:
23440   Total allocated bytes :  8
23441   Total deallocated bytes :  0
23442   Current Water Mark:  8
23443   High Water Mark:  8
23445 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
23446 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
23447 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
23448 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
23449 Debug Pool info:
23450   Total allocated bytes :  8
23451   Total deallocated bytes :  4
23452   Current Water Mark:  4
23453   High Water Mark:  8
23454 @end example
23455 @end quotation
23458 @c -- Non-breaking space in running text
23459 @c -- E.g. Ada |nbsp| 95
23461 @node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
23462 @anchor{gnat_ugn/platform_specific_information platform-specific-information}@anchor{d}@anchor{gnat_ugn/platform_specific_information doc}@anchor{1d1}@anchor{gnat_ugn/platform_specific_information id1}@anchor{1d2}
23463 @chapter Platform-Specific Information
23466 This appendix contains information relating to the implementation
23467 of run-time libraries on various platforms and also covers
23468 topics related to the GNAT implementation on Windows and Mac OS.
23470 @menu
23471 * Run-Time Libraries:: 
23472 * Specifying a Run-Time Library:: 
23473 * GNU/Linux Topics:: 
23474 * Microsoft Windows Topics:: 
23475 * Mac OS Topics:: 
23477 @end menu
23479 @node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
23480 @anchor{gnat_ugn/platform_specific_information id2}@anchor{1d3}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{2b}
23481 @section Run-Time Libraries
23484 @geindex Tasking and threads libraries
23486 @geindex Threads libraries and tasking
23488 @geindex Run-time libraries (platform-specific information)
23490 The GNAT run-time implementation may vary with respect to both the
23491 underlying threads library and the exception-handling scheme.
23492 For threads support, the default run-time will bind to the thread
23493 package of the underlying operating system.
23495 For exception handling, either or both of two models are supplied:
23497 @quotation
23499 @geindex Zero-Cost Exceptions
23501 @geindex ZCX (Zero-Cost Exceptions)
23502 @end quotation
23505 @itemize *
23507 @item 
23508 @strong{Zero-Cost Exceptions} ("ZCX"),
23509 which uses binder-generated tables that
23510 are interrogated at run time to locate a handler.
23512 @geindex setjmp/longjmp Exception Model
23514 @geindex SJLJ (setjmp/longjmp Exception Model)
23516 @item 
23517 @strong{setjmp / longjmp} ('SJLJ'),
23518 which uses dynamically-set data to establish
23519 the set of handlers
23520 @end itemize
23522 Most programs should experience a substantial speed improvement by
23523 being compiled with a ZCX run-time.
23524 This is especially true for
23525 tasking applications or applications with many exception handlers.@}
23527 This section summarizes which combinations of threads and exception support
23528 are supplied on various GNAT platforms.
23529 It then shows how to select a particular library either
23530 permanently or temporarily,
23531 explains the properties of (and tradeoffs among) the various threads
23532 libraries, and provides some additional
23533 information about several specific platforms.
23535 @menu
23536 * Summary of Run-Time Configurations:: 
23538 @end menu
23540 @node Summary of Run-Time Configurations,,,Run-Time Libraries
23541 @anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{1d4}@anchor{gnat_ugn/platform_specific_information id3}@anchor{1d5}
23542 @subsection Summary of Run-Time Configurations
23546 @multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
23547 @headitem
23549 Platform
23551 @tab
23553 Run-Time
23555 @tab
23557 Tasking
23559 @tab
23561 Exceptions
23563 @item
23565 GNU/Linux
23567 @tab
23569 rts-native
23570 (default)
23572 @tab
23574 pthread library
23576 @tab
23580 @item
23582 rts-sjlj
23584 @tab
23586 pthread library
23588 @tab
23590 SJLJ
23592 @item
23594 Windows
23596 @tab
23598 rts-native
23599 (default)
23601 @tab
23603 native Win32 threads
23605 @tab
23609 @item
23611 rts-sjlj
23613 @tab
23615 native Win32 threads
23617 @tab
23619 SJLJ
23621 @item
23623 Mac OS
23625 @tab
23627 rts-native
23629 @tab
23631 pthread library
23633 @tab
23637 @end multitable
23640 @node Specifying a Run-Time Library,GNU/Linux Topics,Run-Time Libraries,Platform-Specific Information
23641 @anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{1d6}@anchor{gnat_ugn/platform_specific_information id4}@anchor{1d7}
23642 @section Specifying a Run-Time Library
23645 The @code{adainclude} subdirectory containing the sources of the GNAT
23646 run-time library, and the @code{adalib} subdirectory containing the
23647 @code{ALI} files and the static and/or shared GNAT library, are located
23648 in the gcc target-dependent area:
23650 @quotation
23652 @example
23653 target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
23654 @end example
23655 @end quotation
23657 As indicated above, on some platforms several run-time libraries are supplied.
23658 These libraries are installed in the target dependent area and
23659 contain a complete source and binary subdirectory. The detailed description
23660 below explains the differences between the different libraries in terms of
23661 their thread support.
23663 The default run-time library (when GNAT is installed) is @emph{rts-native}.
23664 This default run-time is selected by the means of soft links.
23665 For example on x86-linux:
23667 @c --
23668 @c --  $(target-dir)
23669 @c --      |
23670 @c --      +--- adainclude----------+
23671 @c --      |                        |
23672 @c --      +--- adalib-----------+  |
23673 @c --      |                     |  |
23674 @c --      +--- rts-native       |  |
23675 @c --      |    |                |  |
23676 @c --      |    +--- adainclude <---+
23677 @c --      |    |                |
23678 @c --      |    +--- adalib <----+
23679 @c --      |
23680 @c --      +--- rts-sjlj
23681 @c --           |
23682 @c --           +--- adainclude
23683 @c --           |
23684 @c --           +--- adalib
23687 @example
23688                $(target-dir)
23689               __/ /      \ \___
23690       _______/   /        \    \_________________
23691      /          /          \                     \
23692     /          /            \                     \
23693 ADAINCLUDE  ADALIB      rts-native             rts-sjlj
23694    :          :            /    \                 /   \
23695    :          :           /      \               /     \
23696    :          :          /        \             /       \
23697    :          :         /          \           /         \
23698    +-------------> adainclude     adalib   adainclude   adalib
23699               :                     ^
23700               :                     :
23701               +---------------------+
23703               Run-Time Library Directory Structure
23704    (Upper-case names and dotted/dashed arrows represent soft links)
23705 @end example
23707 If the @emph{rts-sjlj} library is to be selected on a permanent basis,
23708 these soft links can be modified with the following commands:
23710 @quotation
23712 @example
23713 $ cd $target
23714 $ rm -f adainclude adalib
23715 $ ln -s rts-sjlj/adainclude adainclude
23716 $ ln -s rts-sjlj/adalib adalib
23717 @end example
23718 @end quotation
23720 Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
23721 @code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
23722 @code{$target/ada_object_path}.
23724 @geindex --RTS option
23726 Selecting another run-time library temporarily can be
23727 achieved by using the @code{--RTS} switch, e.g., @code{--RTS=sjlj}
23728 @anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy}@anchor{1d8}
23729 @geindex SCHED_FIFO scheduling policy
23731 @geindex SCHED_RR scheduling policy
23733 @geindex SCHED_OTHER scheduling policy
23735 @menu
23736 * Choosing the Scheduling Policy:: 
23738 @end menu
23740 @node Choosing the Scheduling Policy,,,Specifying a Run-Time Library
23741 @anchor{gnat_ugn/platform_specific_information id5}@anchor{1d9}
23742 @subsection Choosing the Scheduling Policy
23745 When using a POSIX threads implementation, you have a choice of several
23746 scheduling policies: @code{SCHED_FIFO}, @code{SCHED_RR} and @code{SCHED_OTHER}.
23748 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
23749 or @code{SCHED_RR} requires special (e.g., root) privileges.
23751 @geindex pragma Time_Slice
23753 @geindex -T0 option
23755 @geindex pragma Task_Dispatching_Policy
23757 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
23758 @code{SCHED_FIFO},
23759 you can use one of the following:
23762 @itemize *
23764 @item 
23765 @code{pragma Time_Slice (0.0)}
23767 @item 
23768 the corresponding binder option @code{-T0}
23770 @item 
23771 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23772 @end itemize
23774 To specify @code{SCHED_RR},
23775 you should use @code{pragma Time_Slice} with a
23776 value greater than 0.0, or else use the corresponding @code{-T}
23777 binder option.
23779 To make sure a program is running as root, you can put something like
23780 this in a library package body in your application:
23782 @quotation
23784 @example
23785 function geteuid return Integer;
23786 pragma Import (C, geteuid, "geteuid");
23787 Ignore : constant Boolean :=
23788   (if geteuid = 0 then True else raise Program_Error with "must be root");
23789 @end example
23790 @end quotation
23792 It gets the effective user id, and if it's not 0 (i.e. root), it raises
23793 Program_Error.
23795 @geindex Linux
23797 @geindex GNU/Linux
23799 @node GNU/Linux Topics,Microsoft Windows Topics,Specifying a Run-Time Library,Platform-Specific Information
23800 @anchor{gnat_ugn/platform_specific_information id6}@anchor{1da}@anchor{gnat_ugn/platform_specific_information gnu-linux-topics}@anchor{1db}
23801 @section GNU/Linux Topics
23804 This section describes topics that are specific to GNU/Linux platforms.
23806 @menu
23807 * Required Packages on GNU/Linux:: 
23809 @end menu
23811 @node Required Packages on GNU/Linux,,,GNU/Linux Topics
23812 @anchor{gnat_ugn/platform_specific_information id7}@anchor{1dc}@anchor{gnat_ugn/platform_specific_information required-packages-on-gnu-linux}@anchor{1dd}
23813 @subsection Required Packages on GNU/Linux
23816 GNAT requires the C library developer's package to be installed.
23817 The name of of that package depends on your GNU/Linux distribution:
23820 @itemize *
23822 @item 
23823 RedHat, SUSE: @code{glibc-devel};
23825 @item 
23826 Debian, Ubuntu: @code{libc6-dev} (normally installed by default).
23827 @end itemize
23829 If using the 32-bit version of GNAT on a 64-bit version of GNU/Linux,
23830 you'll need the 32-bit version of the glibc and glibc-devel packages:
23833 @itemize *
23835 @item 
23836 RedHat, SUSE: @code{glibc.i686}, @code{glibc-devel.i686}
23838 @item 
23839 Debian, Ubuntu: @code{libc6:i386}, @code{libc6-dev:i386}
23840 @end itemize
23842 Other GNU/Linux distributions might be choosing a different name
23843 for that package.
23845 @geindex Windows
23847 @node Microsoft Windows Topics,Mac OS Topics,GNU/Linux Topics,Platform-Specific Information
23848 @anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{2c}@anchor{gnat_ugn/platform_specific_information id8}@anchor{1de}
23849 @section Microsoft Windows Topics
23852 This section describes topics that are specific to the Microsoft Windows
23853 platforms.
23859 @menu
23860 * Using GNAT on Windows:: 
23861 * Using a network installation of GNAT:: 
23862 * CONSOLE and WINDOWS subsystems:: 
23863 * Temporary Files:: 
23864 * Disabling Command Line Argument Expansion:: 
23865 * Mixed-Language Programming on Windows:: 
23866 * Windows Specific Add-Ons:: 
23868 @end menu
23870 @node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
23871 @anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{1df}@anchor{gnat_ugn/platform_specific_information id9}@anchor{1e0}
23872 @subsection Using GNAT on Windows
23875 One of the strengths of the GNAT technology is that its tool set
23876 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
23877 @code{gdb} debugger, etc.) is used in the same way regardless of the
23878 platform.
23880 On Windows this tool set is complemented by a number of Microsoft-specific
23881 tools that have been provided to facilitate interoperability with Windows
23882 when this is required. With these tools:
23885 @itemize *
23887 @item 
23888 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
23889 subsystems.
23891 @item 
23892 You can use any Dynamically Linked Library (DLL) in your Ada code (both
23893 relocatable and non-relocatable DLLs are supported).
23895 @item 
23896 You can build Ada DLLs for use in other applications. These applications
23897 can be written in a language other than Ada (e.g., C, C++, etc). Again both
23898 relocatable and non-relocatable Ada DLLs are supported.
23900 @item 
23901 You can include Windows resources in your Ada application.
23903 @item 
23904 You can use or create COM/DCOM objects.
23905 @end itemize
23907 Immediately below are listed all known general GNAT-for-Windows restrictions.
23908 Other restrictions about specific features like Windows Resources and DLLs
23909 are listed in separate sections below.
23912 @itemize *
23914 @item 
23915 It is not possible to use @code{GetLastError} and @code{SetLastError}
23916 when tasking, protected records, or exceptions are used. In these
23917 cases, in order to implement Ada semantics, the GNAT run-time system
23918 calls certain Win32 routines that set the last error variable to 0 upon
23919 success. It should be possible to use @code{GetLastError} and
23920 @code{SetLastError} when tasking, protected record, and exception
23921 features are not used, but it is not guaranteed to work.
23923 @item 
23924 It is not possible to link against Microsoft C++ libraries except for
23925 import libraries. Interfacing must be done by the mean of DLLs.
23927 @item 
23928 It is possible to link against Microsoft C libraries. Yet the preferred
23929 solution is to use C/C++ compiler that comes with GNAT, since it
23930 doesn't require having two different development environments and makes the
23931 inter-language debugging experience smoother.
23933 @item 
23934 When the compilation environment is located on FAT32 drives, users may
23935 experience recompilations of the source files that have not changed if
23936 Daylight Saving Time (DST) state has changed since the last time files
23937 were compiled. NTFS drives do not have this problem.
23939 @item 
23940 No components of the GNAT toolset use any entries in the Windows
23941 registry. The only entries that can be created are file associations and
23942 PATH settings, provided the user has chosen to create them at installation
23943 time, as well as some minimal book-keeping information needed to correctly
23944 uninstall or integrate different GNAT products.
23945 @end itemize
23947 @node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
23948 @anchor{gnat_ugn/platform_specific_information id10}@anchor{1e1}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{1e2}
23949 @subsection Using a network installation of GNAT
23952 Make sure the system on which GNAT is installed is accessible from the
23953 current machine, i.e., the install location is shared over the network.
23954 Shared resources are accessed on Windows by means of UNC paths, which
23955 have the format @code{\\\\server\\sharename\\path}
23957 In order to use such a network installation, simply add the UNC path of the
23958 @code{bin} directory of your GNAT installation in front of your PATH. For
23959 example, if GNAT is installed in @code{\GNAT} directory of a share location
23960 called @code{c-drive} on a machine @code{LOKI}, the following command will
23961 make it available:
23963 @quotation
23965 @example
23966 $ path \\loki\c-drive\gnat\bin;%path%`
23967 @end example
23968 @end quotation
23970 Be aware that every compilation using the network installation results in the
23971 transfer of large amounts of data across the network and will likely cause
23972 serious performance penalty.
23974 @node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
23975 @anchor{gnat_ugn/platform_specific_information id11}@anchor{1e3}@anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{1e4}
23976 @subsection CONSOLE and WINDOWS subsystems
23979 @geindex CONSOLE Subsystem
23981 @geindex WINDOWS Subsystem
23983 @geindex -mwindows
23985 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
23986 (which is the default subsystem) will always create a console when
23987 launching the application. This is not something desirable when the
23988 application has a Windows GUI. To get rid of this console the
23989 application must be using the @code{WINDOWS} subsystem. To do so
23990 the @code{-mwindows} linker option must be specified.
23992 @quotation
23994 @example
23995 $ gnatmake winprog -largs -mwindows
23996 @end example
23997 @end quotation
23999 @node Temporary Files,Disabling Command Line Argument Expansion,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
24000 @anchor{gnat_ugn/platform_specific_information id12}@anchor{1e5}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{1e6}
24001 @subsection Temporary Files
24004 @geindex Temporary files
24006 It is possible to control where temporary files gets created by setting
24007 the 
24008 @geindex TMP
24009 @geindex environment variable; TMP
24010 @code{TMP} environment variable. The file will be created:
24013 @itemize *
24015 @item 
24016 Under the directory pointed to by the 
24017 @geindex TMP
24018 @geindex environment variable; TMP
24019 @code{TMP} environment variable if
24020 this directory exists.
24022 @item 
24023 Under @code{c:\temp}, if the 
24024 @geindex TMP
24025 @geindex environment variable; TMP
24026 @code{TMP} environment variable is not
24027 set (or not pointing to a directory) and if this directory exists.
24029 @item 
24030 Under the current working directory otherwise.
24031 @end itemize
24033 This allows you to determine exactly where the temporary
24034 file will be created. This is particularly useful in networked
24035 environments where you may not have write access to some
24036 directories.
24038 @node Disabling Command Line Argument Expansion,Mixed-Language Programming on Windows,Temporary Files,Microsoft Windows Topics
24039 @anchor{gnat_ugn/platform_specific_information disabling-command-line-argument-expansion}@anchor{1e7}
24040 @subsection Disabling Command Line Argument Expansion
24043 @geindex Command Line Argument Expansion
24045 By default, an executable compiled for the Windows platform will do
24046 the following postprocessing on the arguments passed on the command
24047 line:
24050 @itemize *
24052 @item 
24053 If the argument contains the characters @code{*} and/or @code{?}, then
24054 file expansion will be attempted. For example, if the current directory
24055 contains @code{a.txt} and @code{b.txt}, then when calling:
24057 @example
24058 $ my_ada_program *.txt
24059 @end example
24061 The following arguments will effectively be passed to the main program
24062 (for example when using @code{Ada.Command_Line.Argument}):
24064 @example
24065 Ada.Command_Line.Argument (1) -> "a.txt"
24066 Ada.Command_Line.Argument (2) -> "b.txt"
24067 @end example
24069 @item 
24070 Filename expansion can be disabled for a given argument by using single
24071 quotes. Thus, calling:
24073 @example
24074 $ my_ada_program '*.txt'
24075 @end example
24077 will result in:
24079 @example
24080 Ada.Command_Line.Argument (1) -> "*.txt"
24081 @end example
24082 @end itemize
24084 Note that if the program is launched from a shell such as Cygwin Bash
24085 then quote removal might be performed by the shell.
24087 In some contexts it might be useful to disable this feature (for example if
24088 the program performs its own argument expansion). In order to do this, a C
24089 symbol needs to be defined and set to @code{0}. You can do this by
24090 adding the following code fragment in one of your Ada units:
24092 @example
24093 Do_Argv_Expansion : Integer := 0;
24094 pragma Export (C, Do_Argv_Expansion, "__gnat_do_argv_expansion");
24095 @end example
24097 The results of previous examples will be respectively:
24099 @example
24100 Ada.Command_Line.Argument (1) -> "*.txt"
24101 @end example
24103 and:
24105 @example
24106 Ada.Command_Line.Argument (1) -> "'*.txt'"
24107 @end example
24109 @node Mixed-Language Programming on Windows,Windows Specific Add-Ons,Disabling Command Line Argument Expansion,Microsoft Windows Topics
24110 @anchor{gnat_ugn/platform_specific_information id13}@anchor{1e8}@anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{1e9}
24111 @subsection Mixed-Language Programming on Windows
24114 Developing pure Ada applications on Windows is no different than on
24115 other GNAT-supported platforms. However, when developing or porting an
24116 application that contains a mix of Ada and C/C++, the choice of your
24117 Windows C/C++ development environment conditions your overall
24118 interoperability strategy.
24120 If you use @code{gcc} or Microsoft C to compile the non-Ada part of
24121 your application, there are no Windows-specific restrictions that
24122 affect the overall interoperability with your Ada code. If you do want
24123 to use the Microsoft tools for your C++ code, you have two choices:
24126 @itemize *
24128 @item 
24129 Encapsulate your C++ code in a DLL to be linked with your Ada
24130 application. In this case, use the Microsoft or whatever environment to
24131 build the DLL and use GNAT to build your executable
24132 (@ref{1ea,,Using DLLs with GNAT}).
24134 @item 
24135 Or you can encapsulate your Ada code in a DLL to be linked with the
24136 other part of your application. In this case, use GNAT to build the DLL
24137 (@ref{1eb,,Building DLLs with GNAT Project files}) and use the Microsoft
24138 or whatever environment to build your executable.
24139 @end itemize
24141 In addition to the description about C main in
24142 @ref{44,,Mixed Language Programming} section, if the C main uses a
24143 stand-alone library it is required on x86-windows to
24144 setup the SEH context. For this the C main must looks like this:
24146 @quotation
24148 @example
24149 /* main.c */
24150 extern void adainit (void);
24151 extern void adafinal (void);
24152 extern void __gnat_initialize(void*);
24153 extern void call_to_ada (void);
24155 int main (int argc, char *argv[])
24157   int SEH [2];
24159   /* Initialize the SEH context */
24160   __gnat_initialize (&SEH);
24162   adainit();
24164   /* Then call Ada services in the stand-alone library */
24166   call_to_ada();
24168   adafinal();
24170 @end example
24171 @end quotation
24173 Note that this is not needed on x86_64-windows where the Windows
24174 native SEH support is used.
24176 @menu
24177 * Windows Calling Conventions:: 
24178 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
24179 * Using DLLs with GNAT:: 
24180 * Building DLLs with GNAT Project files:: 
24181 * Building DLLs with GNAT:: 
24182 * Building DLLs with gnatdll:: 
24183 * Ada DLLs and Finalization:: 
24184 * Creating a Spec for Ada DLLs:: 
24185 * GNAT and Windows Resources:: 
24186 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
24187 * Debugging a DLL:: 
24188 * Setting Stack Size from gnatlink:: 
24189 * Setting Heap Size from gnatlink:: 
24191 @end menu
24193 @node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
24194 @anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{1ec}@anchor{gnat_ugn/platform_specific_information id14}@anchor{1ed}
24195 @subsubsection Windows Calling Conventions
24198 @geindex Stdcall
24200 @geindex APIENTRY
24202 This section pertain only to Win32. On Win64 there is a single native
24203 calling convention. All convention specifiers are ignored on this
24204 platform.
24206 When a subprogram @code{F} (caller) calls a subprogram @code{G}
24207 (callee), there are several ways to push @code{G}'s parameters on the
24208 stack and there are several possible scenarios to clean up the stack
24209 upon @code{G}'s return. A calling convention is an agreed upon software
24210 protocol whereby the responsibilities between the caller (@code{F}) and
24211 the callee (@code{G}) are clearly defined. Several calling conventions
24212 are available for Windows:
24215 @itemize *
24217 @item 
24218 @code{C} (Microsoft defined)
24220 @item 
24221 @code{Stdcall} (Microsoft defined)
24223 @item 
24224 @code{Win32} (GNAT specific)
24226 @item 
24227 @code{DLL} (GNAT specific)
24228 @end itemize
24230 @menu
24231 * C Calling Convention:: 
24232 * Stdcall Calling Convention:: 
24233 * Win32 Calling Convention:: 
24234 * DLL Calling Convention:: 
24236 @end menu
24238 @node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
24239 @anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{1ee}@anchor{gnat_ugn/platform_specific_information id15}@anchor{1ef}
24240 @subsubsection @code{C} Calling Convention
24243 This is the default calling convention used when interfacing to C/C++
24244 routines compiled with either @code{gcc} or Microsoft Visual C++.
24246 In the @code{C} calling convention subprogram parameters are pushed on the
24247 stack by the caller from right to left. The caller itself is in charge of
24248 cleaning up the stack after the call. In addition, the name of a routine
24249 with @code{C} calling convention is mangled by adding a leading underscore.
24251 The name to use on the Ada side when importing (or exporting) a routine
24252 with @code{C} calling convention is the name of the routine. For
24253 instance the C function:
24255 @quotation
24257 @example
24258 int get_val (long);
24259 @end example
24260 @end quotation
24262 should be imported from Ada as follows:
24264 @quotation
24266 @example
24267 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24268 pragma Import (C, Get_Val, External_Name => "get_val");
24269 @end example
24270 @end quotation
24272 Note that in this particular case the @code{External_Name} parameter could
24273 have been omitted since, when missing, this parameter is taken to be the
24274 name of the Ada entity in lower case. When the @code{Link_Name} parameter
24275 is missing, as in the above example, this parameter is set to be the
24276 @code{External_Name} with a leading underscore.
24278 When importing a variable defined in C, you should always use the @code{C}
24279 calling convention unless the object containing the variable is part of a
24280 DLL (in which case you should use the @code{Stdcall} calling
24281 convention, @ref{1f0,,Stdcall Calling Convention}).
24283 @node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
24284 @anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{1f0}@anchor{gnat_ugn/platform_specific_information id16}@anchor{1f1}
24285 @subsubsection @code{Stdcall} Calling Convention
24288 This convention, which was the calling convention used for Pascal
24289 programs, is used by Microsoft for all the routines in the Win32 API for
24290 efficiency reasons. It must be used to import any routine for which this
24291 convention was specified.
24293 In the @code{Stdcall} calling convention subprogram parameters are pushed
24294 on the stack by the caller from right to left. The callee (and not the
24295 caller) is in charge of cleaning the stack on routine exit. In addition,
24296 the name of a routine with @code{Stdcall} calling convention is mangled by
24297 adding a leading underscore (as for the @code{C} calling convention) and a
24298 trailing @code{@@@emph{nn}}, where @code{nn} is the overall size (in
24299 bytes) of the parameters passed to the routine.
24301 The name to use on the Ada side when importing a C routine with a
24302 @code{Stdcall} calling convention is the name of the C routine. The leading
24303 underscore and trailing @code{@@@emph{nn}} are added automatically by
24304 the compiler. For instance the Win32 function:
24306 @quotation
24308 @example
24309 APIENTRY int get_val (long);
24310 @end example
24311 @end quotation
24313 should be imported from Ada as follows:
24315 @quotation
24317 @example
24318 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24319 pragma Import (Stdcall, Get_Val);
24320 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
24321 @end example
24322 @end quotation
24324 As for the @code{C} calling convention, when the @code{External_Name}
24325 parameter is missing, it is taken to be the name of the Ada entity in lower
24326 case. If instead of writing the above import pragma you write:
24328 @quotation
24330 @example
24331 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24332 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
24333 @end example
24334 @end quotation
24336 then the imported routine is @code{_retrieve_val@@4}. However, if instead
24337 of specifying the @code{External_Name} parameter you specify the
24338 @code{Link_Name} as in the following example:
24340 @quotation
24342 @example
24343 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24344 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
24345 @end example
24346 @end quotation
24348 then the imported routine is @code{retrieve_val}, that is, there is no
24349 decoration at all. No leading underscore and no Stdcall suffix
24350 @code{@@@emph{nn}}.
24352 This is especially important as in some special cases a DLL's entry
24353 point name lacks a trailing @code{@@@emph{nn}} while the exported
24354 name generated for a call has it.
24356 It is also possible to import variables defined in a DLL by using an
24357 import pragma for a variable. As an example, if a DLL contains a
24358 variable defined as:
24360 @quotation
24362 @example
24363 int my_var;
24364 @end example
24365 @end quotation
24367 then, to access this variable from Ada you should write:
24369 @quotation
24371 @example
24372 My_Var : Interfaces.C.int;
24373 pragma Import (Stdcall, My_Var);
24374 @end example
24375 @end quotation
24377 Note that to ease building cross-platform bindings this convention
24378 will be handled as a @code{C} calling convention on non-Windows platforms.
24380 @node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
24381 @anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{1f2}@anchor{gnat_ugn/platform_specific_information id17}@anchor{1f3}
24382 @subsubsection @code{Win32} Calling Convention
24385 This convention, which is GNAT-specific is fully equivalent to the
24386 @code{Stdcall} calling convention described above.
24388 @node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
24389 @anchor{gnat_ugn/platform_specific_information id18}@anchor{1f4}@anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{1f5}
24390 @subsubsection @code{DLL} Calling Convention
24393 This convention, which is GNAT-specific is fully equivalent to the
24394 @code{Stdcall} calling convention described above.
24396 @node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
24397 @anchor{gnat_ugn/platform_specific_information id19}@anchor{1f6}@anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{1f7}
24398 @subsubsection Introduction to Dynamic Link Libraries (DLLs)
24401 @geindex DLL
24403 A Dynamically Linked Library (DLL) is a library that can be shared by
24404 several applications running under Windows. A DLL can contain any number of
24405 routines and variables.
24407 One advantage of DLLs is that you can change and enhance them without
24408 forcing all the applications that depend on them to be relinked or
24409 recompiled. However, you should be aware than all calls to DLL routines are
24410 slower since, as you will understand below, such calls are indirect.
24412 To illustrate the remainder of this section, suppose that an application
24413 wants to use the services of a DLL @code{API.dll}. To use the services
24414 provided by @code{API.dll} you must statically link against the DLL or
24415 an import library which contains a jump table with an entry for each
24416 routine and variable exported by the DLL. In the Microsoft world this
24417 import library is called @code{API.lib}. When using GNAT this import
24418 library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
24419 @code{libAPI.a} or @code{libapi.a} (names are case insensitive).
24421 After you have linked your application with the DLL or the import library
24422 and you run your application, here is what happens:
24425 @itemize *
24427 @item 
24428 Your application is loaded into memory.
24430 @item 
24431 The DLL @code{API.dll} is mapped into the address space of your
24432 application. This means that:
24435 @itemize -
24437 @item 
24438 The DLL will use the stack of the calling thread.
24440 @item 
24441 The DLL will use the virtual address space of the calling process.
24443 @item 
24444 The DLL will allocate memory from the virtual address space of the calling
24445 process.
24447 @item 
24448 Handles (pointers) can be safely exchanged between routines in the DLL
24449 routines and routines in the application using the DLL.
24450 @end itemize
24452 @item 
24453 The entries in the jump table (from the import library @code{libAPI.dll.a}
24454 or @code{API.lib} or automatically created when linking against a DLL)
24455 which is part of your application are initialized with the addresses
24456 of the routines and variables in @code{API.dll}.
24458 @item 
24459 If present in @code{API.dll}, routines @code{DllMain} or
24460 @code{DllMainCRTStartup} are invoked. These routines typically contain
24461 the initialization code needed for the well-being of the routines and
24462 variables exported by the DLL.
24463 @end itemize
24465 There is an additional point which is worth mentioning. In the Windows
24466 world there are two kind of DLLs: relocatable and non-relocatable
24467 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
24468 in the target application address space. If the addresses of two
24469 non-relocatable DLLs overlap and these happen to be used by the same
24470 application, a conflict will occur and the application will run
24471 incorrectly. Hence, when possible, it is always preferable to use and
24472 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
24473 supported by GNAT. Note that the @code{-s} linker option (see GNU Linker
24474 User's Guide) removes the debugging symbols from the DLL but the DLL can
24475 still be relocated.
24477 As a side note, an interesting difference between Microsoft DLLs and
24478 Unix shared libraries, is the fact that on most Unix systems all public
24479 routines are exported by default in a Unix shared library, while under
24480 Windows it is possible (but not required) to list exported routines in
24481 a definition file (see @ref{1f8,,The Definition File}).
24483 @node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
24484 @anchor{gnat_ugn/platform_specific_information id20}@anchor{1f9}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{1ea}
24485 @subsubsection Using DLLs with GNAT
24488 To use the services of a DLL, say @code{API.dll}, in your Ada application
24489 you must have:
24492 @itemize *
24494 @item 
24495 The Ada spec for the routines and/or variables you want to access in
24496 @code{API.dll}. If not available this Ada spec must be built from the C/C++
24497 header files provided with the DLL.
24499 @item 
24500 The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
24501 mentioned an import library is a statically linked library containing the
24502 import table which will be filled at load time to point to the actual
24503 @code{API.dll} routines. Sometimes you don't have an import library for the
24504 DLL you want to use. The following sections will explain how to build
24505 one. Note that this is optional.
24507 @item 
24508 The actual DLL, @code{API.dll}.
24509 @end itemize
24511 Once you have all the above, to compile an Ada application that uses the
24512 services of @code{API.dll} and whose main subprogram is @code{My_Ada_App},
24513 you simply issue the command
24515 @quotation
24517 @example
24518 $ gnatmake my_ada_app -largs -lAPI
24519 @end example
24520 @end quotation
24522 The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
24523 tells the GNAT linker to look for an import library. The linker will
24524 look for a library name in this specific order:
24527 @itemize *
24529 @item 
24530 @code{libAPI.dll.a}
24532 @item 
24533 @code{API.dll.a}
24535 @item 
24536 @code{libAPI.a}
24538 @item 
24539 @code{API.lib}
24541 @item 
24542 @code{libAPI.dll}
24544 @item 
24545 @code{API.dll}
24546 @end itemize
24548 The first three are the GNU style import libraries. The third is the
24549 Microsoft style import libraries. The last two are the actual DLL names.
24551 Note that if the Ada package spec for @code{API.dll} contains the
24552 following pragma
24554 @quotation
24556 @example
24557 pragma Linker_Options ("-lAPI");
24558 @end example
24559 @end quotation
24561 you do not have to add @code{-largs -lAPI} at the end of the
24562 @code{gnatmake} command.
24564 If any one of the items above is missing you will have to create it
24565 yourself. The following sections explain how to do so using as an
24566 example a fictitious DLL called @code{API.dll}.
24568 @menu
24569 * Creating an Ada Spec for the DLL Services:: 
24570 * Creating an Import Library:: 
24572 @end menu
24574 @node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
24575 @anchor{gnat_ugn/platform_specific_information id21}@anchor{1fa}@anchor{gnat_ugn/platform_specific_information creating-an-ada-spec-for-the-dll-services}@anchor{1fb}
24576 @subsubsection Creating an Ada Spec for the DLL Services
24579 A DLL typically comes with a C/C++ header file which provides the
24580 definitions of the routines and variables exported by the DLL. The Ada
24581 equivalent of this header file is a package spec that contains definitions
24582 for the imported entities. If the DLL you intend to use does not come with
24583 an Ada spec you have to generate one such spec yourself. For example if
24584 the header file of @code{API.dll} is a file @code{api.h} containing the
24585 following two definitions:
24587 @quotation
24589 @example
24590 int some_var;
24591 int get (char *);
24592 @end example
24593 @end quotation
24595 then the equivalent Ada spec could be:
24597 @quotation
24599 @example
24600 with Interfaces.C.Strings;
24601 package API is
24602    use Interfaces;
24604    Some_Var : C.int;
24605    function Get (Str : C.Strings.Chars_Ptr) return C.int;
24607 private
24608    pragma Import (C, Get);
24609    pragma Import (DLL, Some_Var);
24610 end API;
24611 @end example
24612 @end quotation
24614 @node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
24615 @anchor{gnat_ugn/platform_specific_information id22}@anchor{1fc}@anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{1fd}
24616 @subsubsection Creating an Import Library
24619 @geindex Import library
24621 If a Microsoft-style import library @code{API.lib} or a GNAT-style
24622 import library @code{libAPI.dll.a} or @code{libAPI.a} is available
24623 with @code{API.dll} you can skip this section. You can also skip this
24624 section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
24625 as in this case it is possible to link directly against the
24626 DLL. Otherwise read on.
24628 @geindex Definition file
24629 @anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{1f8}
24630 @subsubheading The Definition File
24633 As previously mentioned, and unlike Unix systems, the list of symbols
24634 that are exported from a DLL must be provided explicitly in Windows.
24635 The main goal of a definition file is precisely that: list the symbols
24636 exported by a DLL. A definition file (usually a file with a @code{.def}
24637 suffix) has the following structure:
24639 @quotation
24641 @example
24642 [LIBRARY `@w{`}name`@w{`}]
24643 [DESCRIPTION `@w{`}string`@w{`}]
24644 EXPORTS
24645    `@w{`}symbol1`@w{`}
24646    `@w{`}symbol2`@w{`}
24647    ...
24648 @end example
24649 @end quotation
24652 @table @asis
24654 @item @emph{LIBRARY name}
24656 This section, which is optional, gives the name of the DLL.
24658 @item @emph{DESCRIPTION string}
24660 This section, which is optional, gives a description string that will be
24661 embedded in the import library.
24663 @item @emph{EXPORTS}
24665 This section gives the list of exported symbols (procedures, functions or
24666 variables). For instance in the case of @code{API.dll} the @code{EXPORTS}
24667 section of @code{API.def} looks like:
24669 @example
24670 EXPORTS
24671    some_var
24672    get
24673 @end example
24674 @end table
24676 Note that you must specify the correct suffix (@code{@@@emph{nn}})
24677 (see @ref{1ec,,Windows Calling Conventions}) for a Stdcall
24678 calling convention function in the exported symbols list.
24680 There can actually be other sections in a definition file, but these
24681 sections are not relevant to the discussion at hand.
24682 @anchor{gnat_ugn/platform_specific_information create-def-file-automatically}@anchor{1fe}
24683 @subsubheading Creating a Definition File Automatically
24686 You can automatically create the definition file @code{API.def}
24687 (see @ref{1f8,,The Definition File}) from a DLL.
24688 For that use the @code{dlltool} program as follows:
24690 @quotation
24692 @example
24693 $ dlltool API.dll -z API.def --export-all-symbols
24694 @end example
24696 Note that if some routines in the DLL have the @code{Stdcall} convention
24697 (@ref{1ec,,Windows Calling Conventions}) with stripped @code{@@@emph{nn}}
24698 suffix then you'll have to edit @code{api.def} to add it, and specify
24699 @code{-k} to @code{gnatdll} when creating the import library.
24701 Here are some hints to find the right @code{@@@emph{nn}} suffix.
24704 @itemize -
24706 @item 
24707 If you have the Microsoft import library (.lib), it is possible to get
24708 the right symbols by using Microsoft @code{dumpbin} tool (see the
24709 corresponding Microsoft documentation for further details).
24711 @example
24712 $ dumpbin /exports api.lib
24713 @end example
24715 @item 
24716 If you have a message about a missing symbol at link time the compiler
24717 tells you what symbol is expected. You just have to go back to the
24718 definition file and add the right suffix.
24719 @end itemize
24720 @end quotation
24721 @anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{1ff}
24722 @subsubheading GNAT-Style Import Library
24725 To create a static import library from @code{API.dll} with the GNAT tools
24726 you should create the .def file, then use @code{gnatdll} tool
24727 (see @ref{200,,Using gnatdll}) as follows:
24729 @quotation
24731 @example
24732 $ gnatdll -e API.def -d API.dll
24733 @end example
24735 @code{gnatdll} takes as input a definition file @code{API.def} and the
24736 name of the DLL containing the services listed in the definition file
24737 @code{API.dll}. The name of the static import library generated is
24738 computed from the name of the definition file as follows: if the
24739 definition file name is @code{xyz.def}, the import library name will
24740 be @code{libxyz.a}. Note that in the previous example option
24741 @code{-e} could have been removed because the name of the definition
24742 file (before the @code{.def} suffix) is the same as the name of the
24743 DLL (@ref{200,,Using gnatdll} for more information about @code{gnatdll}).
24744 @end quotation
24745 @anchor{gnat_ugn/platform_specific_information msvs-style-import-library}@anchor{201}
24746 @subsubheading Microsoft-Style Import Library
24749 A Microsoft import library is needed only if you plan to make an
24750 Ada DLL available to applications developed with Microsoft
24751 tools (@ref{1e9,,Mixed-Language Programming on Windows}).
24753 To create a Microsoft-style import library for @code{API.dll} you
24754 should create the .def file, then build the actual import library using
24755 Microsoft's @code{lib} utility:
24757 @quotation
24759 @example
24760 $ lib -machine:IX86 -def:API.def -out:API.lib
24761 @end example
24763 If you use the above command the definition file @code{API.def} must
24764 contain a line giving the name of the DLL:
24766 @example
24767 LIBRARY      "API"
24768 @end example
24770 See the Microsoft documentation for further details about the usage of
24771 @code{lib}.
24772 @end quotation
24774 @node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
24775 @anchor{gnat_ugn/platform_specific_information id23}@anchor{202}@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{1eb}
24776 @subsubsection Building DLLs with GNAT Project files
24779 @geindex DLLs
24780 @geindex building
24782 There is nothing specific to Windows in the build process.
24783 See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24784 chapter of the @emph{GPRbuild User's Guide}.
24786 Due to a system limitation, it is not possible under Windows to create threads
24787 when inside the @code{DllMain} routine which is used for auto-initialization
24788 of shared libraries, so it is not possible to have library level tasks in SALs.
24790 @node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
24791 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{203}@anchor{gnat_ugn/platform_specific_information id24}@anchor{204}
24792 @subsubsection Building DLLs with GNAT
24795 @geindex DLLs
24796 @geindex building
24798 This section explain how to build DLLs using the GNAT built-in DLL
24799 support. With the following procedure it is straight forward to build
24800 and use DLLs with GNAT.
24803 @itemize *
24805 @item 
24806 Building object files.
24807 The first step is to build all objects files that are to be included
24808 into the DLL. This is done by using the standard @code{gnatmake} tool.
24810 @item 
24811 Building the DLL.
24812 To build the DLL you must use the @code{gcc} @code{-shared} and
24813 @code{-shared-libgcc} options. It is quite simple to use this method:
24815 @example
24816 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
24817 @end example
24819 It is important to note that in this case all symbols found in the
24820 object files are automatically exported. It is possible to restrict
24821 the set of symbols to export by passing to @code{gcc} a definition
24822 file (see @ref{1f8,,The Definition File}).
24823 For example:
24825 @example
24826 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
24827 @end example
24829 If you use a definition file you must export the elaboration procedures
24830 for every package that required one. Elaboration procedures are named
24831 using the package name followed by "_E".
24833 @item 
24834 Preparing DLL to be used.
24835 For the DLL to be used by client programs the bodies must be hidden
24836 from it and the .ali set with read-only attribute. This is very important
24837 otherwise GNAT will recompile all packages and will not actually use
24838 the code in the DLL. For example:
24840 @example
24841 $ mkdir apilib
24842 $ copy *.ads *.ali api.dll apilib
24843 $ attrib +R apilib\\*.ali
24844 @end example
24845 @end itemize
24847 At this point it is possible to use the DLL by directly linking
24848 against it. Note that you must use the GNAT shared runtime when using
24849 GNAT shared libraries. This is achieved by using the @code{-shared} binder
24850 option.
24852 @quotation
24854 @example
24855 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
24856 @end example
24857 @end quotation
24859 @node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
24860 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{205}@anchor{gnat_ugn/platform_specific_information id25}@anchor{206}
24861 @subsubsection Building DLLs with gnatdll
24864 @geindex DLLs
24865 @geindex building
24867 Note that it is preferred to use GNAT Project files
24868 (@ref{1eb,,Building DLLs with GNAT Project files}) or the built-in GNAT
24869 DLL support (@ref{203,,Building DLLs with GNAT}) or to build DLLs.
24871 This section explains how to build DLLs containing Ada code using
24872 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
24873 remainder of this section.
24875 The steps required to build an Ada DLL that is to be used by Ada as well as
24876 non-Ada applications are as follows:
24879 @itemize *
24881 @item 
24882 You need to mark each Ada entity exported by the DLL with a @code{C} or
24883 @code{Stdcall} calling convention to avoid any Ada name mangling for the
24884 entities exported by the DLL
24885 (see @ref{207,,Exporting Ada Entities}). You can
24886 skip this step if you plan to use the Ada DLL only from Ada applications.
24888 @item 
24889 Your Ada code must export an initialization routine which calls the routine
24890 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
24891 the Ada code in the DLL (@ref{208,,Ada DLLs and Elaboration}). The initialization
24892 routine exported by the Ada DLL must be invoked by the clients of the DLL
24893 to initialize the DLL.
24895 @item 
24896 When useful, the DLL should also export a finalization routine which calls
24897 routine @code{adafinal} generated by @code{gnatbind} to perform the
24898 finalization of the Ada code in the DLL (@ref{209,,Ada DLLs and Finalization}).
24899 The finalization routine exported by the Ada DLL must be invoked by the
24900 clients of the DLL when the DLL services are no further needed.
24902 @item 
24903 You must provide a spec for the services exported by the Ada DLL in each
24904 of the programming languages to which you plan to make the DLL available.
24906 @item 
24907 You must provide a definition file listing the exported entities
24908 (@ref{1f8,,The Definition File}).
24910 @item 
24911 Finally you must use @code{gnatdll} to produce the DLL and the import
24912 library (@ref{200,,Using gnatdll}).
24913 @end itemize
24915 Note that a relocatable DLL stripped using the @code{strip}
24916 binutils tool will not be relocatable anymore. To build a DLL without
24917 debug information pass @code{-largs -s} to @code{gnatdll}. This
24918 restriction does not apply to a DLL built using a Library Project.
24919 See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24920 chapter of the @emph{GPRbuild User's Guide}.
24922 @c Limitations_When_Using_Ada_DLLs_from Ada:
24924 @menu
24925 * Limitations When Using Ada DLLs from Ada:: 
24926 * Exporting Ada Entities:: 
24927 * Ada DLLs and Elaboration:: 
24929 @end menu
24931 @node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
24932 @anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{20a}
24933 @subsubsection Limitations When Using Ada DLLs from Ada
24936 When using Ada DLLs from Ada applications there is a limitation users
24937 should be aware of. Because on Windows the GNAT run-time is not in a DLL of
24938 its own, each Ada DLL includes a part of the GNAT run-time. Specifically,
24939 each Ada DLL includes the services of the GNAT run-time that are necessary
24940 to the Ada code inside the DLL. As a result, when an Ada program uses an
24941 Ada DLL there are two independent GNAT run-times: one in the Ada DLL and
24942 one in the main program.
24944 It is therefore not possible to exchange GNAT run-time objects between the
24945 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
24946 handles (e.g., @code{Text_IO.File_Type}), tasks types, protected objects
24947 types, etc.
24949 It is completely safe to exchange plain elementary, array or record types,
24950 Windows object handles, etc.
24952 @node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
24953 @anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{207}@anchor{gnat_ugn/platform_specific_information id26}@anchor{20b}
24954 @subsubsection Exporting Ada Entities
24957 @geindex Export table
24959 Building a DLL is a way to encapsulate a set of services usable from any
24960 application. As a result, the Ada entities exported by a DLL should be
24961 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
24962 any Ada name mangling. As an example here is an Ada package
24963 @code{API}, spec and body, exporting two procedures, a function, and a
24964 variable:
24966 @quotation
24968 @example
24969 with Interfaces.C; use Interfaces;
24970 package API is
24971    Count : C.int := 0;
24972    function Factorial (Val : C.int) return C.int;
24974    procedure Initialize_API;
24975    procedure Finalize_API;
24976    --  Initialization & Finalization routines. More in the next section.
24977 private
24978    pragma Export (C, Initialize_API);
24979    pragma Export (C, Finalize_API);
24980    pragma Export (C, Count);
24981    pragma Export (C, Factorial);
24982 end API;
24983 @end example
24985 @example
24986 package body API is
24987    function Factorial (Val : C.int) return C.int is
24988       Fact : C.int := 1;
24989    begin
24990       Count := Count + 1;
24991       for K in 1 .. Val loop
24992          Fact := Fact * K;
24993       end loop;
24994       return Fact;
24995    end Factorial;
24997    procedure Initialize_API is
24998       procedure Adainit;
24999       pragma Import (C, Adainit);
25000    begin
25001       Adainit;
25002    end Initialize_API;
25004    procedure Finalize_API is
25005       procedure Adafinal;
25006       pragma Import (C, Adafinal);
25007    begin
25008       Adafinal;
25009    end Finalize_API;
25010 end API;
25011 @end example
25012 @end quotation
25014 If the Ada DLL you are building will only be used by Ada applications
25015 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
25016 convention. As an example, the previous package could be written as
25017 follows:
25019 @quotation
25021 @example
25022 package API is
25023    Count : Integer := 0;
25024    function Factorial (Val : Integer) return Integer;
25026    procedure Initialize_API;
25027    procedure Finalize_API;
25028    --  Initialization and Finalization routines.
25029 end API;
25030 @end example
25032 @example
25033 package body API is
25034    function Factorial (Val : Integer) return Integer is
25035       Fact : Integer := 1;
25036    begin
25037       Count := Count + 1;
25038       for K in 1 .. Val loop
25039          Fact := Fact * K;
25040       end loop;
25041       return Fact;
25042    end Factorial;
25044    ...
25045    --  The remainder of this package body is unchanged.
25046 end API;
25047 @end example
25048 @end quotation
25050 Note that if you do not export the Ada entities with a @code{C} or
25051 @code{Stdcall} convention you will have to provide the mangled Ada names
25052 in the definition file of the Ada DLL
25053 (@ref{20c,,Creating the Definition File}).
25055 @node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
25056 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{208}@anchor{gnat_ugn/platform_specific_information id27}@anchor{20d}
25057 @subsubsection Ada DLLs and Elaboration
25060 @geindex DLLs and elaboration
25062 The DLL that you are building contains your Ada code as well as all the
25063 routines in the Ada library that are needed by it. The first thing a
25064 user of your DLL must do is elaborate the Ada code
25065 (@ref{f,,Elaboration Order Handling in GNAT}).
25067 To achieve this you must export an initialization routine
25068 (@code{Initialize_API} in the previous example), which must be invoked
25069 before using any of the DLL services. This elaboration routine must call
25070 the Ada elaboration routine @code{adainit} generated by the GNAT binder
25071 (@ref{b4,,Binding with Non-Ada Main Programs}). See the body of
25072 @code{Initialize_Api} for an example. Note that the GNAT binder is
25073 automatically invoked during the DLL build process by the @code{gnatdll}
25074 tool (@ref{200,,Using gnatdll}).
25076 When a DLL is loaded, Windows systematically invokes a routine called
25077 @code{DllMain}. It would therefore be possible to call @code{adainit}
25078 directly from @code{DllMain} without having to provide an explicit
25079 initialization routine. Unfortunately, it is not possible to call
25080 @code{adainit} from the @code{DllMain} if your program has library level
25081 tasks because access to the @code{DllMain} entry point is serialized by
25082 the system (that is, only a single thread can execute 'through' it at a
25083 time), which means that the GNAT run-time will deadlock waiting for the
25084 newly created task to complete its initialization.
25086 @node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
25087 @anchor{gnat_ugn/platform_specific_information id28}@anchor{20e}@anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{209}
25088 @subsubsection Ada DLLs and Finalization
25091 @geindex DLLs and finalization
25093 When the services of an Ada DLL are no longer needed, the client code should
25094 invoke the DLL finalization routine, if available. The DLL finalization
25095 routine is in charge of releasing all resources acquired by the DLL. In the
25096 case of the Ada code contained in the DLL, this is achieved by calling
25097 routine @code{adafinal} generated by the GNAT binder
25098 (@ref{b4,,Binding with Non-Ada Main Programs}).
25099 See the body of @code{Finalize_Api} for an
25100 example. As already pointed out the GNAT binder is automatically invoked
25101 during the DLL build process by the @code{gnatdll} tool
25102 (@ref{200,,Using gnatdll}).
25104 @node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
25105 @anchor{gnat_ugn/platform_specific_information id29}@anchor{20f}@anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{210}
25106 @subsubsection Creating a Spec for Ada DLLs
25109 To use the services exported by the Ada DLL from another programming
25110 language (e.g., C), you have to translate the specs of the exported Ada
25111 entities in that language. For instance in the case of @code{API.dll},
25112 the corresponding C header file could look like:
25114 @quotation
25116 @example
25117 extern int *_imp__count;
25118 #define count (*_imp__count)
25119 int factorial (int);
25120 @end example
25121 @end quotation
25123 It is important to understand that when building an Ada DLL to be used by
25124 other Ada applications, you need two different specs for the packages
25125 contained in the DLL: one for building the DLL and the other for using
25126 the DLL. This is because the @code{DLL} calling convention is needed to
25127 use a variable defined in a DLL, but when building the DLL, the variable
25128 must have either the @code{Ada} or @code{C} calling convention. As an
25129 example consider a DLL comprising the following package @code{API}:
25131 @quotation
25133 @example
25134 package API is
25135    Count : Integer := 0;
25136    ...
25137    --  Remainder of the package omitted.
25138 end API;
25139 @end example
25140 @end quotation
25142 After producing a DLL containing package @code{API}, the spec that
25143 must be used to import @code{API.Count} from Ada code outside of the
25144 DLL is:
25146 @quotation
25148 @example
25149 package API is
25150    Count : Integer;
25151    pragma Import (DLL, Count);
25152 end API;
25153 @end example
25154 @end quotation
25156 @menu
25157 * Creating the Definition File:: 
25158 * Using gnatdll:: 
25160 @end menu
25162 @node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
25163 @anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{20c}@anchor{gnat_ugn/platform_specific_information id30}@anchor{211}
25164 @subsubsection Creating the Definition File
25167 The definition file is the last file needed to build the DLL. It lists
25168 the exported symbols. As an example, the definition file for a DLL
25169 containing only package @code{API} (where all the entities are exported
25170 with a @code{C} calling convention) is:
25172 @quotation
25174 @example
25175 EXPORTS
25176     count
25177     factorial
25178     finalize_api
25179     initialize_api
25180 @end example
25181 @end quotation
25183 If the @code{C} calling convention is missing from package @code{API},
25184 then the definition file contains the mangled Ada names of the above
25185 entities, which in this case are:
25187 @quotation
25189 @example
25190 EXPORTS
25191     api__count
25192     api__factorial
25193     api__finalize_api
25194     api__initialize_api
25195 @end example
25196 @end quotation
25198 @node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
25199 @anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{200}@anchor{gnat_ugn/platform_specific_information id31}@anchor{212}
25200 @subsubsection Using @code{gnatdll}
25203 @geindex gnatdll
25205 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
25206 and non-Ada sources that make up your DLL have been compiled.
25207 @code{gnatdll} is actually in charge of two distinct tasks: build the
25208 static import library for the DLL and the actual DLL. The form of the
25209 @code{gnatdll} command is
25211 @quotation
25213 @example
25214 $ gnatdll [ switches ] list-of-files [ -largs opts ]
25215 @end example
25216 @end quotation
25218 where @code{list-of-files} is a list of ALI and object files. The object
25219 file list must be the exact list of objects corresponding to the non-Ada
25220 sources whose services are to be included in the DLL. The ALI file list
25221 must be the exact list of ALI files for the corresponding Ada sources
25222 whose services are to be included in the DLL. If @code{list-of-files} is
25223 missing, only the static import library is generated.
25225 You may specify any of the following switches to @code{gnatdll}:
25227 @quotation
25229 @geindex -a (gnatdll)
25230 @end quotation
25233 @table @asis
25235 @item @code{-a[@emph{address}]}
25237 Build a non-relocatable DLL at @code{address}. If @code{address} is not
25238 specified the default address @code{0x11000000} will be used. By default,
25239 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
25240 advise the reader to build relocatable DLL.
25242 @geindex -b (gnatdll)
25244 @item @code{-b @emph{address}}
25246 Set the relocatable DLL base address. By default the address is
25247 @code{0x11000000}.
25249 @geindex -bargs (gnatdll)
25251 @item @code{-bargs @emph{opts}}
25253 Binder options. Pass @code{opts} to the binder.
25255 @geindex -d (gnatdll)
25257 @item @code{-d @emph{dllfile}}
25259 @code{dllfile} is the name of the DLL. This switch must be present for
25260 @code{gnatdll} to do anything. The name of the generated import library is
25261 obtained algorithmically from @code{dllfile} as shown in the following
25262 example: if @code{dllfile} is @code{xyz.dll}, the import library name is
25263 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
25264 by option @code{-e}) is obtained algorithmically from @code{dllfile}
25265 as shown in the following example:
25266 if @code{dllfile} is @code{xyz.dll}, the definition
25267 file used is @code{xyz.def}.
25269 @geindex -e (gnatdll)
25271 @item @code{-e @emph{deffile}}
25273 @code{deffile} is the name of the definition file.
25275 @geindex -g (gnatdll)
25277 @item @code{-g}
25279 Generate debugging information. This information is stored in the object
25280 file and copied from there to the final DLL file by the linker,
25281 where it can be read by the debugger. You must use the
25282 @code{-g} switch if you plan on using the debugger or the symbolic
25283 stack traceback.
25285 @geindex -h (gnatdll)
25287 @item @code{-h}
25289 Help mode. Displays @code{gnatdll} switch usage information.
25291 @geindex -I (gnatdll)
25293 @item @code{-I@emph{dir}}
25295 Direct @code{gnatdll} to search the @code{dir} directory for source and
25296 object files needed to build the DLL.
25297 (@ref{89,,Search Paths and the Run-Time Library (RTL)}).
25299 @geindex -k (gnatdll)
25301 @item @code{-k}
25303 Removes the @code{@@@emph{nn}} suffix from the import library's exported
25304 names, but keeps them for the link names. You must specify this
25305 option if you want to use a @code{Stdcall} function in a DLL for which
25306 the @code{@@@emph{nn}} suffix has been removed. This is the case for most
25307 of the Windows NT DLL for example. This option has no effect when
25308 @code{-n} option is specified.
25310 @geindex -l (gnatdll)
25312 @item @code{-l @emph{file}}
25314 The list of ALI and object files used to build the DLL are listed in
25315 @code{file}, instead of being given in the command line. Each line in
25316 @code{file} contains the name of an ALI or object file.
25318 @geindex -n (gnatdll)
25320 @item @code{-n}
25322 No Import. Do not create the import library.
25324 @geindex -q (gnatdll)
25326 @item @code{-q}
25328 Quiet mode. Do not display unnecessary messages.
25330 @geindex -v (gnatdll)
25332 @item @code{-v}
25334 Verbose mode. Display extra information.
25336 @geindex -largs (gnatdll)
25338 @item @code{-largs @emph{opts}}
25340 Linker options. Pass @code{opts} to the linker.
25341 @end table
25343 @subsubheading @code{gnatdll} Example
25346 As an example the command to build a relocatable DLL from @code{api.adb}
25347 once @code{api.adb} has been compiled and @code{api.def} created is
25349 @quotation
25351 @example
25352 $ gnatdll -d api.dll api.ali
25353 @end example
25354 @end quotation
25356 The above command creates two files: @code{libapi.dll.a} (the import
25357 library) and @code{api.dll} (the actual DLL). If you want to create
25358 only the DLL, just type:
25360 @quotation
25362 @example
25363 $ gnatdll -d api.dll -n api.ali
25364 @end example
25365 @end quotation
25367 Alternatively if you want to create just the import library, type:
25369 @quotation
25371 @example
25372 $ gnatdll -d api.dll
25373 @end example
25374 @end quotation
25376 @subsubheading @code{gnatdll} behind the Scenes
25379 This section details the steps involved in creating a DLL. @code{gnatdll}
25380 does these steps for you. Unless you are interested in understanding what
25381 goes on behind the scenes, you should skip this section.
25383 We use the previous example of a DLL containing the Ada package @code{API},
25384 to illustrate the steps necessary to build a DLL. The starting point is a
25385 set of objects that will make up the DLL and the corresponding ALI
25386 files. In the case of this example this means that @code{api.o} and
25387 @code{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
25388 the following:
25391 @itemize *
25393 @item 
25394 @code{gnatdll} builds the base file (@code{api.base}). A base file gives
25395 the information necessary to generate relocation information for the
25396 DLL.
25398 @example
25399 $ gnatbind -n api
25400 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
25401 @end example
25403 In addition to the base file, the @code{gnatlink} command generates an
25404 output file @code{api.jnk} which can be discarded. The @code{-mdll} switch
25405 asks @code{gnatlink} to generate the routines @code{DllMain} and
25406 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
25407 is loaded into memory.
25409 @item 
25410 @code{gnatdll} uses @code{dlltool} (see @ref{213,,Using dlltool}) to build the
25411 export table (@code{api.exp}). The export table contains the relocation
25412 information in a form which can be used during the final link to ensure
25413 that the Windows loader is able to place the DLL anywhere in memory.
25415 @example
25416 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
25417           --output-exp api.exp
25418 @end example
25420 @item 
25421 @code{gnatdll} builds the base file using the new export table. Note that
25422 @code{gnatbind} must be called once again since the binder generated file
25423 has been deleted during the previous call to @code{gnatlink}.
25425 @example
25426 $ gnatbind -n api
25427 $ gnatlink api -o api.jnk api.exp -mdll
25428       -Wl,--base-file,api.base
25429 @end example
25431 @item 
25432 @code{gnatdll} builds the new export table using the new base file and
25433 generates the DLL import library @code{libAPI.dll.a}.
25435 @example
25436 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
25437           --output-exp api.exp --output-lib libAPI.a
25438 @end example
25440 @item 
25441 Finally @code{gnatdll} builds the relocatable DLL using the final export
25442 table.
25444 @example
25445 $ gnatbind -n api
25446 $ gnatlink api api.exp -o api.dll -mdll
25447 @end example
25448 @end itemize
25449 @anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{213}
25450 @subsubheading Using @code{dlltool}
25453 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
25454 DLLs and static import libraries. This section summarizes the most
25455 common @code{dlltool} switches. The form of the @code{dlltool} command
25458 @quotation
25460 @example
25461 $ dlltool [`switches`]
25462 @end example
25463 @end quotation
25465 @code{dlltool} switches include:
25467 @geindex --base-file (dlltool)
25470 @table @asis
25472 @item @code{--base-file @emph{basefile}}
25474 Read the base file @code{basefile} generated by the linker. This switch
25475 is used to create a relocatable DLL.
25476 @end table
25478 @geindex --def (dlltool)
25481 @table @asis
25483 @item @code{--def @emph{deffile}}
25485 Read the definition file.
25486 @end table
25488 @geindex --dllname (dlltool)
25491 @table @asis
25493 @item @code{--dllname @emph{name}}
25495 Gives the name of the DLL. This switch is used to embed the name of the
25496 DLL in the static import library generated by @code{dlltool} with switch
25497 @code{--output-lib}.
25498 @end table
25500 @geindex -k (dlltool)
25503 @table @asis
25505 @item @code{-k}
25507 Kill @code{@@@emph{nn}} from exported names
25508 (@ref{1ec,,Windows Calling Conventions}
25509 for a discussion about @code{Stdcall}-style symbols.
25510 @end table
25512 @geindex --help (dlltool)
25515 @table @asis
25517 @item @code{--help}
25519 Prints the @code{dlltool} switches with a concise description.
25520 @end table
25522 @geindex --output-exp (dlltool)
25525 @table @asis
25527 @item @code{--output-exp @emph{exportfile}}
25529 Generate an export file @code{exportfile}. The export file contains the
25530 export table (list of symbols in the DLL) and is used to create the DLL.
25531 @end table
25533 @geindex --output-lib (dlltool)
25536 @table @asis
25538 @item @code{--output-lib @emph{libfile}}
25540 Generate a static import library @code{libfile}.
25541 @end table
25543 @geindex -v (dlltool)
25546 @table @asis
25548 @item @code{-v}
25550 Verbose mode.
25551 @end table
25553 @geindex --as (dlltool)
25556 @table @asis
25558 @item @code{--as @emph{assembler-name}}
25560 Use @code{assembler-name} as the assembler. The default is @code{as}.
25561 @end table
25563 @node GNAT and Windows Resources,Using GNAT DLLs from Microsoft Visual Studio Applications,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
25564 @anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{214}@anchor{gnat_ugn/platform_specific_information id32}@anchor{215}
25565 @subsubsection GNAT and Windows Resources
25568 @geindex Resources
25569 @geindex windows
25571 Resources are an easy way to add Windows specific objects to your
25572 application. The objects that can be added as resources include:
25575 @itemize *
25577 @item 
25578 menus
25580 @item 
25581 accelerators
25583 @item 
25584 dialog boxes
25586 @item 
25587 string tables
25589 @item 
25590 bitmaps
25592 @item 
25593 cursors
25595 @item 
25596 icons
25598 @item 
25599 fonts
25601 @item 
25602 version information
25603 @end itemize
25605 For example, a version information resource can be defined as follow and
25606 embedded into an executable or DLL:
25608 A version information resource can be used to embed information into an
25609 executable or a DLL. These information can be viewed using the file properties
25610 from the Windows Explorer. Here is an example of a version information
25611 resource:
25613 @quotation
25615 @example
25616 1 VERSIONINFO
25617 FILEVERSION     1,0,0,0
25618 PRODUCTVERSION  1,0,0,0
25619 BEGIN
25620   BLOCK "StringFileInfo"
25621   BEGIN
25622     BLOCK "080904E4"
25623     BEGIN
25624       VALUE "CompanyName", "My Company Name"
25625       VALUE "FileDescription", "My application"
25626       VALUE "FileVersion", "1.0"
25627       VALUE "InternalName", "my_app"
25628       VALUE "LegalCopyright", "My Name"
25629       VALUE "OriginalFilename", "my_app.exe"
25630       VALUE "ProductName", "My App"
25631       VALUE "ProductVersion", "1.0"
25632     END
25633   END
25635   BLOCK "VarFileInfo"
25636   BEGIN
25637     VALUE "Translation", 0x809, 1252
25638   END
25640 @end example
25641 @end quotation
25643 The value @code{0809} (langID) is for the U.K English language and
25644 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
25645 multilingual.
25647 This section explains how to build, compile and use resources. Note that this
25648 section does not cover all resource objects, for a complete description see
25649 the corresponding Microsoft documentation.
25651 @menu
25652 * Building Resources:: 
25653 * Compiling Resources:: 
25654 * Using Resources:: 
25656 @end menu
25658 @node Building Resources,Compiling Resources,,GNAT and Windows Resources
25659 @anchor{gnat_ugn/platform_specific_information building-resources}@anchor{216}@anchor{gnat_ugn/platform_specific_information id33}@anchor{217}
25660 @subsubsection Building Resources
25663 @geindex Resources
25664 @geindex building
25666 A resource file is an ASCII file. By convention resource files have an
25667 @code{.rc} extension.
25668 The easiest way to build a resource file is to use Microsoft tools
25669 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
25670 @code{dlgedit.exe} to build dialogs.
25671 It is always possible to build an @code{.rc} file yourself by writing a
25672 resource script.
25674 It is not our objective to explain how to write a resource file. A
25675 complete description of the resource script language can be found in the
25676 Microsoft documentation.
25678 @node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
25679 @anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{218}@anchor{gnat_ugn/platform_specific_information id34}@anchor{219}
25680 @subsubsection Compiling Resources
25683 @geindex rc
25685 @geindex windres
25687 @geindex Resources
25688 @geindex compiling
25690 This section describes how to build a GNAT-compatible (COFF) object file
25691 containing the resources. This is done using the Resource Compiler
25692 @code{windres} as follows:
25694 @quotation
25696 @example
25697 $ windres -i myres.rc -o myres.o
25698 @end example
25699 @end quotation
25701 By default @code{windres} will run @code{gcc} to preprocess the @code{.rc}
25702 file. You can specify an alternate preprocessor (usually named
25703 @code{cpp.exe}) using the @code{windres} @code{--preprocessor}
25704 parameter. A list of all possible options may be obtained by entering
25705 the command @code{windres} @code{--help}.
25707 It is also possible to use the Microsoft resource compiler @code{rc.exe}
25708 to produce a @code{.res} file (binary resource file). See the
25709 corresponding Microsoft documentation for further details. In this case
25710 you need to use @code{windres} to translate the @code{.res} file to a
25711 GNAT-compatible object file as follows:
25713 @quotation
25715 @example
25716 $ windres -i myres.res -o myres.o
25717 @end example
25718 @end quotation
25720 @node Using Resources,,Compiling Resources,GNAT and Windows Resources
25721 @anchor{gnat_ugn/platform_specific_information using-resources}@anchor{21a}@anchor{gnat_ugn/platform_specific_information id35}@anchor{21b}
25722 @subsubsection Using Resources
25725 @geindex Resources
25726 @geindex using
25728 To include the resource file in your program just add the
25729 GNAT-compatible object file for the resource(s) to the linker
25730 arguments. With @code{gnatmake} this is done by using the @code{-largs}
25731 option:
25733 @quotation
25735 @example
25736 $ gnatmake myprog -largs myres.o
25737 @end example
25738 @end quotation
25740 @node Using GNAT DLLs from Microsoft Visual Studio Applications,Debugging a DLL,GNAT and Windows Resources,Mixed-Language Programming on Windows
25741 @anchor{gnat_ugn/platform_specific_information using-gnat-dll-from-msvs}@anchor{21c}@anchor{gnat_ugn/platform_specific_information using-gnat-dlls-from-microsoft-visual-studio-applications}@anchor{21d}
25742 @subsubsection Using GNAT DLLs from Microsoft Visual Studio Applications
25745 @geindex Microsoft Visual Studio
25746 @geindex use with GNAT DLLs
25748 This section describes a common case of mixed GNAT/Microsoft Visual Studio
25749 application development, where the main program is developed using MSVS, and
25750 is linked with a DLL developed using GNAT. Such a mixed application should
25751 be developed following the general guidelines outlined above; below is the
25752 cookbook-style sequence of steps to follow:
25755 @enumerate 
25757 @item 
25758 First develop and build the GNAT shared library using a library project
25759 (let's assume the project is @code{mylib.gpr}, producing the library @code{libmylib.dll}):
25760 @end enumerate
25762 @quotation
25764 @example
25765 $ gprbuild -p mylib.gpr
25766 @end example
25767 @end quotation
25770 @enumerate 2
25772 @item 
25773 Produce a .def file for the symbols you need to interface with, either by
25774 hand or automatically with possibly some manual adjustments
25775 (see @ref{1fe,,Creating Definition File Automatically}):
25776 @end enumerate
25778 @quotation
25780 @example
25781 $ dlltool libmylib.dll -z libmylib.def --export-all-symbols
25782 @end example
25783 @end quotation
25786 @enumerate 3
25788 @item 
25789 Make sure that MSVS command-line tools are accessible on the path.
25791 @item 
25792 Create the Microsoft-style import library (see @ref{201,,MSVS-Style Import Library}):
25793 @end enumerate
25795 @quotation
25797 @example
25798 $ lib -machine:IX86 -def:libmylib.def -out:libmylib.lib
25799 @end example
25800 @end quotation
25802 If you are using a 64-bit toolchain, the above becomes...
25804 @quotation
25806 @example
25807 $ lib -machine:X64 -def:libmylib.def -out:libmylib.lib
25808 @end example
25809 @end quotation
25812 @enumerate 5
25814 @item 
25815 Build the C main
25816 @end enumerate
25818 @quotation
25820 @example
25821 $ cl /O2 /MD main.c libmylib.lib
25822 @end example
25823 @end quotation
25826 @enumerate 6
25828 @item 
25829 Before running the executable, make sure you have set the PATH to the DLL,
25830 or copy the DLL into into the directory containing the .exe.
25831 @end enumerate
25833 @node Debugging a DLL,Setting Stack Size from gnatlink,Using GNAT DLLs from Microsoft Visual Studio Applications,Mixed-Language Programming on Windows
25834 @anchor{gnat_ugn/platform_specific_information id36}@anchor{21e}@anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{21f}
25835 @subsubsection Debugging a DLL
25838 @geindex DLL debugging
25840 Debugging a DLL is similar to debugging a standard program. But
25841 we have to deal with two different executable parts: the DLL and the
25842 program that uses it. We have the following four possibilities:
25845 @itemize *
25847 @item 
25848 The program and the DLL are built with GCC/GNAT.
25850 @item 
25851 The program is built with foreign tools and the DLL is built with
25852 GCC/GNAT.
25854 @item 
25855 The program is built with GCC/GNAT and the DLL is built with
25856 foreign tools.
25857 @end itemize
25859 In this section we address only cases one and two above.
25860 There is no point in trying to debug
25861 a DLL with GNU/GDB, if there is no GDB-compatible debugging
25862 information in it. To do so you must use a debugger compatible with the
25863 tools suite used to build the DLL.
25865 @menu
25866 * Program and DLL Both Built with GCC/GNAT:: 
25867 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
25869 @end menu
25871 @node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
25872 @anchor{gnat_ugn/platform_specific_information id37}@anchor{220}@anchor{gnat_ugn/platform_specific_information program-and-dll-both-built-with-gcc-gnat}@anchor{221}
25873 @subsubsection Program and DLL Both Built with GCC/GNAT
25876 This is the simplest case. Both the DLL and the program have @code{GDB}
25877 compatible debugging information. It is then possible to break anywhere in
25878 the process. Let's suppose here that the main procedure is named
25879 @code{ada_main} and that in the DLL there is an entry point named
25880 @code{ada_dll}.
25882 The DLL (@ref{1f7,,Introduction to Dynamic Link Libraries (DLLs)}) and
25883 program must have been built with the debugging information (see GNAT -g
25884 switch). Here are the step-by-step instructions for debugging it:
25887 @itemize *
25889 @item 
25890 Launch @code{GDB} on the main program.
25892 @example
25893 $ gdb -nw ada_main
25894 @end example
25896 @item 
25897 Start the program and stop at the beginning of the main procedure
25899 @example
25900 (gdb) start
25901 @end example
25903 This step is required to be able to set a breakpoint inside the DLL. As long
25904 as the program is not run, the DLL is not loaded. This has the
25905 consequence that the DLL debugging information is also not loaded, so it is not
25906 possible to set a breakpoint in the DLL.
25908 @item 
25909 Set a breakpoint inside the DLL
25911 @example
25912 (gdb) break ada_dll
25913 (gdb) cont
25914 @end example
25915 @end itemize
25917 At this stage a breakpoint is set inside the DLL. From there on
25918 you can use the standard approach to debug the whole program
25919 (@ref{24,,Running and Debugging Ada Programs}).
25921 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
25922 @anchor{gnat_ugn/platform_specific_information program-built-with-foreign-tools-and-dll-built-with-gcc-gnat}@anchor{222}@anchor{gnat_ugn/platform_specific_information id38}@anchor{223}
25923 @subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
25926 In this case things are slightly more complex because it is not possible to
25927 start the main program and then break at the beginning to load the DLL and the
25928 associated DLL debugging information. It is not possible to break at the
25929 beginning of the program because there is no @code{GDB} debugging information,
25930 and therefore there is no direct way of getting initial control. This
25931 section addresses this issue by describing some methods that can be used
25932 to break somewhere in the DLL to debug it.
25934 First suppose that the main procedure is named @code{main} (this is for
25935 example some C code built with Microsoft Visual C) and that there is a
25936 DLL named @code{test.dll} containing an Ada entry point named
25937 @code{ada_dll}.
25939 The DLL (see @ref{1f7,,Introduction to Dynamic Link Libraries (DLLs)}) must have
25940 been built with debugging information (see the GNAT @code{-g} option).
25942 @subsubheading Debugging the DLL Directly
25946 @itemize *
25948 @item 
25949 Find out the executable starting address
25951 @example
25952 $ objdump --file-header main.exe
25953 @end example
25955 The starting address is reported on the last line. For example:
25957 @example
25958 main.exe:     file format pei-i386
25959 architecture: i386, flags 0x0000010a:
25960 EXEC_P, HAS_DEBUG, D_PAGED
25961 start address 0x00401010
25962 @end example
25964 @item 
25965 Launch the debugger on the executable.
25967 @example
25968 $ gdb main.exe
25969 @end example
25971 @item 
25972 Set a breakpoint at the starting address, and launch the program.
25974 @example
25975 $ (gdb) break *0x00401010
25976 $ (gdb) run
25977 @end example
25979 The program will stop at the given address.
25981 @item 
25982 Set a breakpoint on a DLL subroutine.
25984 @example
25985 (gdb) break ada_dll.adb:45
25986 @end example
25988 Or if you want to break using a symbol on the DLL, you need first to
25989 select the Ada language (language used by the DLL).
25991 @example
25992 (gdb) set language ada
25993 (gdb) break ada_dll
25994 @end example
25996 @item 
25997 Continue the program.
25999 @example
26000 (gdb) cont
26001 @end example
26003 This will run the program until it reaches the breakpoint that has been
26004 set. From that point you can use the standard way to debug a program
26005 as described in (@ref{24,,Running and Debugging Ada Programs}).
26006 @end itemize
26008 It is also possible to debug the DLL by attaching to a running process.
26010 @subsubheading Attaching to a Running Process
26013 @geindex DLL debugging
26014 @geindex attach to process
26016 With @code{GDB} it is always possible to debug a running process by
26017 attaching to it. It is possible to debug a DLL this way. The limitation
26018 of this approach is that the DLL must run long enough to perform the
26019 attach operation. It may be useful for instance to insert a time wasting
26020 loop in the code of the DLL to meet this criterion.
26023 @itemize *
26025 @item 
26026 Launch the main program @code{main.exe}.
26028 @example
26029 $ main
26030 @end example
26032 @item 
26033 Use the Windows @emph{Task Manager} to find the process ID. Let's say
26034 that the process PID for @code{main.exe} is 208.
26036 @item 
26037 Launch gdb.
26039 @example
26040 $ gdb
26041 @end example
26043 @item 
26044 Attach to the running process to be debugged.
26046 @example
26047 (gdb) attach 208
26048 @end example
26050 @item 
26051 Load the process debugging information.
26053 @example
26054 (gdb) symbol-file main.exe
26055 @end example
26057 @item 
26058 Break somewhere in the DLL.
26060 @example
26061 (gdb) break ada_dll
26062 @end example
26064 @item 
26065 Continue process execution.
26067 @example
26068 (gdb) cont
26069 @end example
26070 @end itemize
26072 This last step will resume the process execution, and stop at
26073 the breakpoint we have set. From there you can use the standard
26074 approach to debug a program as described in
26075 @ref{24,,Running and Debugging Ada Programs}.
26077 @node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
26078 @anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{136}@anchor{gnat_ugn/platform_specific_information id39}@anchor{224}
26079 @subsubsection Setting Stack Size from @code{gnatlink}
26082 It is possible to specify the program stack size at link time. On modern
26083 versions of Windows, starting with XP, this is mostly useful to set the size of
26084 the main stack (environment task). The other task stacks are set with pragma
26085 Storage_Size or with the @emph{gnatbind -d} command.
26087 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
26088 reserve size of individual tasks, the link-time stack size applies to all
26089 tasks, and pragma Storage_Size has no effect.
26090 In particular, Stack Overflow checks are made against this
26091 link-time specified size.
26093 This setting can be done with @code{gnatlink} using either of the following:
26096 @itemize *
26098 @item 
26099 @code{-Xlinker} linker option
26101 @example
26102 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
26103 @end example
26105 This sets the stack reserve size to 0x10000 bytes and the stack commit
26106 size to 0x1000 bytes.
26108 @item 
26109 @code{-Wl} linker option
26111 @example
26112 $ gnatlink hello -Wl,--stack=0x1000000
26113 @end example
26115 This sets the stack reserve size to 0x1000000 bytes. Note that with
26116 @code{-Wl} option it is not possible to set the stack commit size
26117 because the comma is a separator for this option.
26118 @end itemize
26120 @node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
26121 @anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{137}@anchor{gnat_ugn/platform_specific_information id40}@anchor{225}
26122 @subsubsection Setting Heap Size from @code{gnatlink}
26125 Under Windows systems, it is possible to specify the program heap size from
26126 @code{gnatlink} using either of the following:
26129 @itemize *
26131 @item 
26132 @code{-Xlinker} linker option
26134 @example
26135 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
26136 @end example
26138 This sets the heap reserve size to 0x10000 bytes and the heap commit
26139 size to 0x1000 bytes.
26141 @item 
26142 @code{-Wl} linker option
26144 @example
26145 $ gnatlink hello -Wl,--heap=0x1000000
26146 @end example
26148 This sets the heap reserve size to 0x1000000 bytes. Note that with
26149 @code{-Wl} option it is not possible to set the heap commit size
26150 because the comma is a separator for this option.
26151 @end itemize
26153 @node Windows Specific Add-Ons,,Mixed-Language Programming on Windows,Microsoft Windows Topics
26154 @anchor{gnat_ugn/platform_specific_information windows-specific-add-ons}@anchor{226}@anchor{gnat_ugn/platform_specific_information win32-specific-addons}@anchor{227}
26155 @subsection Windows Specific Add-Ons
26158 This section describes the Windows specific add-ons.
26160 @menu
26161 * Win32Ada:: 
26162 * wPOSIX:: 
26164 @end menu
26166 @node Win32Ada,wPOSIX,,Windows Specific Add-Ons
26167 @anchor{gnat_ugn/platform_specific_information win32ada}@anchor{228}@anchor{gnat_ugn/platform_specific_information id41}@anchor{229}
26168 @subsubsection Win32Ada
26171 Win32Ada is a binding for the Microsoft Win32 API. This binding can be
26172 easily installed from the provided installer. To use the Win32Ada
26173 binding you need to use a project file, and adding a single with_clause
26174 will give you full access to the Win32Ada binding sources and ensure
26175 that the proper libraries are passed to the linker.
26177 @quotation
26179 @example
26180 with "win32ada";
26181 project P is
26182    for Sources use ...;
26183 end P;
26184 @end example
26185 @end quotation
26187 To build the application you just need to call gprbuild for the
26188 application's project, here p.gpr:
26190 @quotation
26192 @example
26193 gprbuild p.gpr
26194 @end example
26195 @end quotation
26197 @node wPOSIX,,Win32Ada,Windows Specific Add-Ons
26198 @anchor{gnat_ugn/platform_specific_information id42}@anchor{22a}@anchor{gnat_ugn/platform_specific_information wposix}@anchor{22b}
26199 @subsubsection wPOSIX
26202 wPOSIX is a minimal POSIX binding whose goal is to help with building
26203 cross-platforms applications. This binding is not complete though, as
26204 the Win32 API does not provide the necessary support for all POSIX APIs.
26206 To use the wPOSIX binding you need to use a project file, and adding
26207 a single with_clause will give you full access to the wPOSIX binding
26208 sources and ensure that the proper libraries are passed to the linker.
26210 @quotation
26212 @example
26213 with "wposix";
26214 project P is
26215    for Sources use ...;
26216 end P;
26217 @end example
26218 @end quotation
26220 To build the application you just need to call gprbuild for the
26221 application's project, here p.gpr:
26223 @quotation
26225 @example
26226 gprbuild p.gpr
26227 @end example
26228 @end quotation
26230 @node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
26231 @anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{2d}@anchor{gnat_ugn/platform_specific_information id43}@anchor{22c}
26232 @section Mac OS Topics
26235 @geindex OS X
26237 This section describes topics that are specific to Apple's OS X
26238 platform.
26240 @menu
26241 * Codesigning the Debugger:: 
26243 @end menu
26245 @node Codesigning the Debugger,,,Mac OS Topics
26246 @anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{22d}
26247 @subsection Codesigning the Debugger
26250 The Darwin Kernel requires the debugger to have special permissions
26251 before it is allowed to control other processes. These permissions
26252 are granted by codesigning the GDB executable. Without these
26253 permissions, the debugger will report error messages such as:
26255 @example
26256 Starting program: /x/y/foo
26257 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
26258 (please check gdb is codesigned - see taskgated(8))
26259 @end example
26261 Codesigning requires a certificate.  The following procedure explains
26262 how to create one:
26265 @itemize *
26267 @item 
26268 Start the Keychain Access application (in
26269 /Applications/Utilities/Keychain Access.app)
26271 @item 
26272 Select the Keychain Access -> Certificate Assistant ->
26273 Create a Certificate... menu
26275 @item 
26276 Then:
26279 @itemize *
26281 @item 
26282 Choose a name for the new certificate (this procedure will use
26283 "gdb-cert" as an example)
26285 @item 
26286 Set "Identity Type" to "Self Signed Root"
26288 @item 
26289 Set "Certificate Type" to "Code Signing"
26291 @item 
26292 Activate the "Let me override defaults" option
26293 @end itemize
26295 @item 
26296 Click several times on "Continue" until the "Specify a Location
26297 For The Certificate" screen appears, then set "Keychain" to "System"
26299 @item 
26300 Click on "Continue" until the certificate is created
26302 @item 
26303 Finally, in the view, double-click on the new certificate,
26304 and set "When using this certificate" to "Always Trust"
26306 @item 
26307 Exit the Keychain Access application and restart the computer
26308 (this is unfortunately required)
26309 @end itemize
26311 Once a certificate has been created, the debugger can be codesigned
26312 as follow. In a Terminal, run the following command:
26314 @quotation
26316 @example
26317 $ codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
26318 @end example
26319 @end quotation
26321 where "gdb-cert" should be replaced by the actual certificate
26322 name chosen above, and <gnat_install_prefix> should be replaced by
26323 the location where you installed GNAT.  Also, be sure that users are
26324 in the Unix group @code{_developer}.
26326 @node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
26327 @anchor{gnat_ugn/example_of_binder_output example-of-binder-output-file}@anchor{e}@anchor{gnat_ugn/example_of_binder_output doc}@anchor{22e}@anchor{gnat_ugn/example_of_binder_output id1}@anchor{22f}
26328 @chapter Example of Binder Output File
26331 @geindex Binder output (example)
26333 This Appendix displays the source code for the output file
26334 generated by @emph{gnatbind} for a simple 'Hello World' program.
26335 Comments have been added for clarification purposes.
26337 @example
26338 --  The package is called Ada_Main unless this name is actually used
26339 --  as a unit name in the partition, in which case some other unique
26340 --  name is used.
26342 pragma Ada_95;
26343 with System;
26344 package ada_main is
26345    pragma Warnings (Off);
26347    --  The main program saves the parameters (argument count,
26348    --  argument values, environment pointer) in global variables
26349    --  for later access by other units including
26350    --  Ada.Command_Line.
26352    gnat_argc : Integer;
26353    gnat_argv : System.Address;
26354    gnat_envp : System.Address;
26356    --  The actual variables are stored in a library routine. This
26357    --  is useful for some shared library situations, where there
26358    --  are problems if variables are not in the library.
26360    pragma Import (C, gnat_argc);
26361    pragma Import (C, gnat_argv);
26362    pragma Import (C, gnat_envp);
26364    --  The exit status is similarly an external location
26366    gnat_exit_status : Integer;
26367    pragma Import (C, gnat_exit_status);
26369    GNAT_Version : constant String :=
26370                     "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
26371    pragma Export (C, GNAT_Version, "__gnat_version");
26373    Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
26374    pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
26376    --  This is the generated adainit routine that performs
26377    --  initialization at the start of execution. In the case
26378    --  where Ada is the main program, this main program makes
26379    --  a call to adainit at program startup.
26381    procedure adainit;
26382    pragma Export (C, adainit, "adainit");
26384    --  This is the generated adafinal routine that performs
26385    --  finalization at the end of execution. In the case where
26386    --  Ada is the main program, this main program makes a call
26387    --  to adafinal at program termination.
26389    procedure adafinal;
26390    pragma Export (C, adafinal, "adafinal");
26392    --  This routine is called at the start of execution. It is
26393    --  a dummy routine that is used by the debugger to breakpoint
26394    --  at the start of execution.
26396    --  This is the actual generated main program (it would be
26397    --  suppressed if the no main program switch were used). As
26398    --  required by standard system conventions, this program has
26399    --  the external name main.
26401    function main
26402      (argc : Integer;
26403       argv : System.Address;
26404       envp : System.Address)
26405       return Integer;
26406    pragma Export (C, main, "main");
26408    --  The following set of constants give the version
26409    --  identification values for every unit in the bound
26410    --  partition. This identification is computed from all
26411    --  dependent semantic units, and corresponds to the
26412    --  string that would be returned by use of the
26413    --  Body_Version or Version attributes.
26415    --  The following Export pragmas export the version numbers
26416    --  with symbolic names ending in B (for body) or S
26417    --  (for spec) so that they can be located in a link. The
26418    --  information provided here is sufficient to track down
26419    --  the exact versions of units used in a given build.
26421    type Version_32 is mod 2 ** 32;
26422    u00001 : constant Version_32 := 16#8ad6e54a#;
26423    pragma Export (C, u00001, "helloB");
26424    u00002 : constant Version_32 := 16#fbff4c67#;
26425    pragma Export (C, u00002, "system__standard_libraryB");
26426    u00003 : constant Version_32 := 16#1ec6fd90#;
26427    pragma Export (C, u00003, "system__standard_libraryS");
26428    u00004 : constant Version_32 := 16#3ffc8e18#;
26429    pragma Export (C, u00004, "adaS");
26430    u00005 : constant Version_32 := 16#28f088c2#;
26431    pragma Export (C, u00005, "ada__text_ioB");
26432    u00006 : constant Version_32 := 16#f372c8ac#;
26433    pragma Export (C, u00006, "ada__text_ioS");
26434    u00007 : constant Version_32 := 16#2c143749#;
26435    pragma Export (C, u00007, "ada__exceptionsB");
26436    u00008 : constant Version_32 := 16#f4f0cce8#;
26437    pragma Export (C, u00008, "ada__exceptionsS");
26438    u00009 : constant Version_32 := 16#a46739c0#;
26439    pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
26440    u00010 : constant Version_32 := 16#3aac8c92#;
26441    pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
26442    u00011 : constant Version_32 := 16#1d274481#;
26443    pragma Export (C, u00011, "systemS");
26444    u00012 : constant Version_32 := 16#a207fefe#;
26445    pragma Export (C, u00012, "system__soft_linksB");
26446    u00013 : constant Version_32 := 16#467d9556#;
26447    pragma Export (C, u00013, "system__soft_linksS");
26448    u00014 : constant Version_32 := 16#b01dad17#;
26449    pragma Export (C, u00014, "system__parametersB");
26450    u00015 : constant Version_32 := 16#630d49fe#;
26451    pragma Export (C, u00015, "system__parametersS");
26452    u00016 : constant Version_32 := 16#b19b6653#;
26453    pragma Export (C, u00016, "system__secondary_stackB");
26454    u00017 : constant Version_32 := 16#b6468be8#;
26455    pragma Export (C, u00017, "system__secondary_stackS");
26456    u00018 : constant Version_32 := 16#39a03df9#;
26457    pragma Export (C, u00018, "system__storage_elementsB");
26458    u00019 : constant Version_32 := 16#30e40e85#;
26459    pragma Export (C, u00019, "system__storage_elementsS");
26460    u00020 : constant Version_32 := 16#41837d1e#;
26461    pragma Export (C, u00020, "system__stack_checkingB");
26462    u00021 : constant Version_32 := 16#93982f69#;
26463    pragma Export (C, u00021, "system__stack_checkingS");
26464    u00022 : constant Version_32 := 16#393398c1#;
26465    pragma Export (C, u00022, "system__exception_tableB");
26466    u00023 : constant Version_32 := 16#b33e2294#;
26467    pragma Export (C, u00023, "system__exception_tableS");
26468    u00024 : constant Version_32 := 16#ce4af020#;
26469    pragma Export (C, u00024, "system__exceptionsB");
26470    u00025 : constant Version_32 := 16#75442977#;
26471    pragma Export (C, u00025, "system__exceptionsS");
26472    u00026 : constant Version_32 := 16#37d758f1#;
26473    pragma Export (C, u00026, "system__exceptions__machineS");
26474    u00027 : constant Version_32 := 16#b895431d#;
26475    pragma Export (C, u00027, "system__exceptions_debugB");
26476    u00028 : constant Version_32 := 16#aec55d3f#;
26477    pragma Export (C, u00028, "system__exceptions_debugS");
26478    u00029 : constant Version_32 := 16#570325c8#;
26479    pragma Export (C, u00029, "system__img_intB");
26480    u00030 : constant Version_32 := 16#1ffca443#;
26481    pragma Export (C, u00030, "system__img_intS");
26482    u00031 : constant Version_32 := 16#b98c3e16#;
26483    pragma Export (C, u00031, "system__tracebackB");
26484    u00032 : constant Version_32 := 16#831a9d5a#;
26485    pragma Export (C, u00032, "system__tracebackS");
26486    u00033 : constant Version_32 := 16#9ed49525#;
26487    pragma Export (C, u00033, "system__traceback_entriesB");
26488    u00034 : constant Version_32 := 16#1d7cb2f1#;
26489    pragma Export (C, u00034, "system__traceback_entriesS");
26490    u00035 : constant Version_32 := 16#8c33a517#;
26491    pragma Export (C, u00035, "system__wch_conB");
26492    u00036 : constant Version_32 := 16#065a6653#;
26493    pragma Export (C, u00036, "system__wch_conS");
26494    u00037 : constant Version_32 := 16#9721e840#;
26495    pragma Export (C, u00037, "system__wch_stwB");
26496    u00038 : constant Version_32 := 16#2b4b4a52#;
26497    pragma Export (C, u00038, "system__wch_stwS");
26498    u00039 : constant Version_32 := 16#92b797cb#;
26499    pragma Export (C, u00039, "system__wch_cnvB");
26500    u00040 : constant Version_32 := 16#09eddca0#;
26501    pragma Export (C, u00040, "system__wch_cnvS");
26502    u00041 : constant Version_32 := 16#6033a23f#;
26503    pragma Export (C, u00041, "interfacesS");
26504    u00042 : constant Version_32 := 16#ece6fdb6#;
26505    pragma Export (C, u00042, "system__wch_jisB");
26506    u00043 : constant Version_32 := 16#899dc581#;
26507    pragma Export (C, u00043, "system__wch_jisS");
26508    u00044 : constant Version_32 := 16#10558b11#;
26509    pragma Export (C, u00044, "ada__streamsB");
26510    u00045 : constant Version_32 := 16#2e6701ab#;
26511    pragma Export (C, u00045, "ada__streamsS");
26512    u00046 : constant Version_32 := 16#db5c917c#;
26513    pragma Export (C, u00046, "ada__io_exceptionsS");
26514    u00047 : constant Version_32 := 16#12c8cd7d#;
26515    pragma Export (C, u00047, "ada__tagsB");
26516    u00048 : constant Version_32 := 16#ce72c228#;
26517    pragma Export (C, u00048, "ada__tagsS");
26518    u00049 : constant Version_32 := 16#c3335bfd#;
26519    pragma Export (C, u00049, "system__htableB");
26520    u00050 : constant Version_32 := 16#99e5f76b#;
26521    pragma Export (C, u00050, "system__htableS");
26522    u00051 : constant Version_32 := 16#089f5cd0#;
26523    pragma Export (C, u00051, "system__string_hashB");
26524    u00052 : constant Version_32 := 16#3bbb9c15#;
26525    pragma Export (C, u00052, "system__string_hashS");
26526    u00053 : constant Version_32 := 16#807fe041#;
26527    pragma Export (C, u00053, "system__unsigned_typesS");
26528    u00054 : constant Version_32 := 16#d27be59e#;
26529    pragma Export (C, u00054, "system__val_lluB");
26530    u00055 : constant Version_32 := 16#fa8db733#;
26531    pragma Export (C, u00055, "system__val_lluS");
26532    u00056 : constant Version_32 := 16#27b600b2#;
26533    pragma Export (C, u00056, "system__val_utilB");
26534    u00057 : constant Version_32 := 16#b187f27f#;
26535    pragma Export (C, u00057, "system__val_utilS");
26536    u00058 : constant Version_32 := 16#d1060688#;
26537    pragma Export (C, u00058, "system__case_utilB");
26538    u00059 : constant Version_32 := 16#392e2d56#;
26539    pragma Export (C, u00059, "system__case_utilS");
26540    u00060 : constant Version_32 := 16#84a27f0d#;
26541    pragma Export (C, u00060, "interfaces__c_streamsB");
26542    u00061 : constant Version_32 := 16#8bb5f2c0#;
26543    pragma Export (C, u00061, "interfaces__c_streamsS");
26544    u00062 : constant Version_32 := 16#6db6928f#;
26545    pragma Export (C, u00062, "system__crtlS");
26546    u00063 : constant Version_32 := 16#4e6a342b#;
26547    pragma Export (C, u00063, "system__file_ioB");
26548    u00064 : constant Version_32 := 16#ba56a5e4#;
26549    pragma Export (C, u00064, "system__file_ioS");
26550    u00065 : constant Version_32 := 16#b7ab275c#;
26551    pragma Export (C, u00065, "ada__finalizationB");
26552    u00066 : constant Version_32 := 16#19f764ca#;
26553    pragma Export (C, u00066, "ada__finalizationS");
26554    u00067 : constant Version_32 := 16#95817ed8#;
26555    pragma Export (C, u00067, "system__finalization_rootB");
26556    u00068 : constant Version_32 := 16#52d53711#;
26557    pragma Export (C, u00068, "system__finalization_rootS");
26558    u00069 : constant Version_32 := 16#769e25e6#;
26559    pragma Export (C, u00069, "interfaces__cB");
26560    u00070 : constant Version_32 := 16#4a38bedb#;
26561    pragma Export (C, u00070, "interfaces__cS");
26562    u00071 : constant Version_32 := 16#07e6ee66#;
26563    pragma Export (C, u00071, "system__os_libB");
26564    u00072 : constant Version_32 := 16#d7b69782#;
26565    pragma Export (C, u00072, "system__os_libS");
26566    u00073 : constant Version_32 := 16#1a817b8e#;
26567    pragma Export (C, u00073, "system__stringsB");
26568    u00074 : constant Version_32 := 16#639855e7#;
26569    pragma Export (C, u00074, "system__stringsS");
26570    u00075 : constant Version_32 := 16#e0b8de29#;
26571    pragma Export (C, u00075, "system__file_control_blockS");
26572    u00076 : constant Version_32 := 16#b5b2aca1#;
26573    pragma Export (C, u00076, "system__finalization_mastersB");
26574    u00077 : constant Version_32 := 16#69316dc1#;
26575    pragma Export (C, u00077, "system__finalization_mastersS");
26576    u00078 : constant Version_32 := 16#57a37a42#;
26577    pragma Export (C, u00078, "system__address_imageB");
26578    u00079 : constant Version_32 := 16#bccbd9bb#;
26579    pragma Export (C, u00079, "system__address_imageS");
26580    u00080 : constant Version_32 := 16#7268f812#;
26581    pragma Export (C, u00080, "system__img_boolB");
26582    u00081 : constant Version_32 := 16#e8fe356a#;
26583    pragma Export (C, u00081, "system__img_boolS");
26584    u00082 : constant Version_32 := 16#d7aac20c#;
26585    pragma Export (C, u00082, "system__ioB");
26586    u00083 : constant Version_32 := 16#8365b3ce#;
26587    pragma Export (C, u00083, "system__ioS");
26588    u00084 : constant Version_32 := 16#6d4d969a#;
26589    pragma Export (C, u00084, "system__storage_poolsB");
26590    u00085 : constant Version_32 := 16#e87cc305#;
26591    pragma Export (C, u00085, "system__storage_poolsS");
26592    u00086 : constant Version_32 := 16#e34550ca#;
26593    pragma Export (C, u00086, "system__pool_globalB");
26594    u00087 : constant Version_32 := 16#c88d2d16#;
26595    pragma Export (C, u00087, "system__pool_globalS");
26596    u00088 : constant Version_32 := 16#9d39c675#;
26597    pragma Export (C, u00088, "system__memoryB");
26598    u00089 : constant Version_32 := 16#445a22b5#;
26599    pragma Export (C, u00089, "system__memoryS");
26600    u00090 : constant Version_32 := 16#6a859064#;
26601    pragma Export (C, u00090, "system__storage_pools__subpoolsB");
26602    u00091 : constant Version_32 := 16#e3b008dc#;
26603    pragma Export (C, u00091, "system__storage_pools__subpoolsS");
26604    u00092 : constant Version_32 := 16#63f11652#;
26605    pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
26606    u00093 : constant Version_32 := 16#fe2f4b3a#;
26607    pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
26609    --  BEGIN ELABORATION ORDER
26610    --  ada%s
26611    --  interfaces%s
26612    --  system%s
26613    --  system.case_util%s
26614    --  system.case_util%b
26615    --  system.htable%s
26616    --  system.img_bool%s
26617    --  system.img_bool%b
26618    --  system.img_int%s
26619    --  system.img_int%b
26620    --  system.io%s
26621    --  system.io%b
26622    --  system.parameters%s
26623    --  system.parameters%b
26624    --  system.crtl%s
26625    --  interfaces.c_streams%s
26626    --  interfaces.c_streams%b
26627    --  system.standard_library%s
26628    --  system.exceptions_debug%s
26629    --  system.exceptions_debug%b
26630    --  system.storage_elements%s
26631    --  system.storage_elements%b
26632    --  system.stack_checking%s
26633    --  system.stack_checking%b
26634    --  system.string_hash%s
26635    --  system.string_hash%b
26636    --  system.htable%b
26637    --  system.strings%s
26638    --  system.strings%b
26639    --  system.os_lib%s
26640    --  system.traceback_entries%s
26641    --  system.traceback_entries%b
26642    --  ada.exceptions%s
26643    --  system.soft_links%s
26644    --  system.unsigned_types%s
26645    --  system.val_llu%s
26646    --  system.val_util%s
26647    --  system.val_util%b
26648    --  system.val_llu%b
26649    --  system.wch_con%s
26650    --  system.wch_con%b
26651    --  system.wch_cnv%s
26652    --  system.wch_jis%s
26653    --  system.wch_jis%b
26654    --  system.wch_cnv%b
26655    --  system.wch_stw%s
26656    --  system.wch_stw%b
26657    --  ada.exceptions.last_chance_handler%s
26658    --  ada.exceptions.last_chance_handler%b
26659    --  system.address_image%s
26660    --  system.exception_table%s
26661    --  system.exception_table%b
26662    --  ada.io_exceptions%s
26663    --  ada.tags%s
26664    --  ada.streams%s
26665    --  ada.streams%b
26666    --  interfaces.c%s
26667    --  system.exceptions%s
26668    --  system.exceptions%b
26669    --  system.exceptions.machine%s
26670    --  system.finalization_root%s
26671    --  system.finalization_root%b
26672    --  ada.finalization%s
26673    --  ada.finalization%b
26674    --  system.storage_pools%s
26675    --  system.storage_pools%b
26676    --  system.finalization_masters%s
26677    --  system.storage_pools.subpools%s
26678    --  system.storage_pools.subpools.finalization%s
26679    --  system.storage_pools.subpools.finalization%b
26680    --  system.memory%s
26681    --  system.memory%b
26682    --  system.standard_library%b
26683    --  system.pool_global%s
26684    --  system.pool_global%b
26685    --  system.file_control_block%s
26686    --  system.file_io%s
26687    --  system.secondary_stack%s
26688    --  system.file_io%b
26689    --  system.storage_pools.subpools%b
26690    --  system.finalization_masters%b
26691    --  interfaces.c%b
26692    --  ada.tags%b
26693    --  system.soft_links%b
26694    --  system.os_lib%b
26695    --  system.secondary_stack%b
26696    --  system.address_image%b
26697    --  system.traceback%s
26698    --  ada.exceptions%b
26699    --  system.traceback%b
26700    --  ada.text_io%s
26701    --  ada.text_io%b
26702    --  hello%b
26703    --  END ELABORATION ORDER
26705 end ada_main;
26706 @end example
26708 @example
26709 pragma Ada_95;
26710 --  The following source file name pragmas allow the generated file
26711 --  names to be unique for different main programs. They are needed
26712 --  since the package name will always be Ada_Main.
26714 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26715 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26717 pragma Suppress (Overflow_Check);
26718 with Ada.Exceptions;
26720 --  Generated package body for Ada_Main starts here
26722 package body ada_main is
26723    pragma Warnings (Off);
26725    --  These values are reference counter associated to units which have
26726    --  been elaborated. It is also used to avoid elaborating the
26727    --  same unit twice.
26729    E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
26730    E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
26731    E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
26732    E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
26733    E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
26734    E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
26735    E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
26736    E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
26737    E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
26738    E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
26739    E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
26740    E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
26741    E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
26742    E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
26743    E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
26744    E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
26745    E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
26746    E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
26748    Local_Priority_Specific_Dispatching : constant String := "";
26749    Local_Interrupt_States : constant String := "";
26751    Is_Elaborated : Boolean := False;
26753    procedure finalize_library is
26754    begin
26755       E06 := E06 - 1;
26756       declare
26757          procedure F1;
26758          pragma Import (Ada, F1, "ada__text_io__finalize_spec");
26759       begin
26760          F1;
26761       end;
26762       E77 := E77 - 1;
26763       E91 := E91 - 1;
26764       declare
26765          procedure F2;
26766          pragma Import (Ada, F2, "system__file_io__finalize_body");
26767       begin
26768          E64 := E64 - 1;
26769          F2;
26770       end;
26771       declare
26772          procedure F3;
26773          pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
26774       begin
26775          E75 := E75 - 1;
26776          F3;
26777       end;
26778       E87 := E87 - 1;
26779       declare
26780          procedure F4;
26781          pragma Import (Ada, F4, "system__pool_global__finalize_spec");
26782       begin
26783          F4;
26784       end;
26785       declare
26786          procedure F5;
26787          pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
26788       begin
26789          F5;
26790       end;
26791       declare
26792          procedure F6;
26793          pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
26794       begin
26795          F6;
26796       end;
26797       declare
26798          procedure Reraise_Library_Exception_If_Any;
26799          pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
26800       begin
26801          Reraise_Library_Exception_If_Any;
26802       end;
26803    end finalize_library;
26805    -------------
26806    -- adainit --
26807    -------------
26809    procedure adainit is
26811       Main_Priority : Integer;
26812       pragma Import (C, Main_Priority, "__gl_main_priority");
26813       Time_Slice_Value : Integer;
26814       pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
26815       WC_Encoding : Character;
26816       pragma Import (C, WC_Encoding, "__gl_wc_encoding");
26817       Locking_Policy : Character;
26818       pragma Import (C, Locking_Policy, "__gl_locking_policy");
26819       Queuing_Policy : Character;
26820       pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
26821       Task_Dispatching_Policy : Character;
26822       pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
26823       Priority_Specific_Dispatching : System.Address;
26824       pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
26825       Num_Specific_Dispatching : Integer;
26826       pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
26827       Main_CPU : Integer;
26828       pragma Import (C, Main_CPU, "__gl_main_cpu");
26829       Interrupt_States : System.Address;
26830       pragma Import (C, Interrupt_States, "__gl_interrupt_states");
26831       Num_Interrupt_States : Integer;
26832       pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
26833       Unreserve_All_Interrupts : Integer;
26834       pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
26835       Detect_Blocking : Integer;
26836       pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
26837       Default_Stack_Size : Integer;
26838       pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
26839       Leap_Seconds_Support : Integer;
26840       pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
26842       procedure Runtime_Initialize;
26843       pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
26845       Finalize_Library_Objects : No_Param_Proc;
26846       pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
26848    --  Start of processing for adainit
26850    begin
26852       --  Record various information for this partition.  The values
26853       --  are derived by the binder from information stored in the ali
26854       --  files by the compiler.
26856       if Is_Elaborated then
26857          return;
26858       end if;
26859       Is_Elaborated := True;
26860       Main_Priority := -1;
26861       Time_Slice_Value := -1;
26862       WC_Encoding := 'b';
26863       Locking_Policy := ' ';
26864       Queuing_Policy := ' ';
26865       Task_Dispatching_Policy := ' ';
26866       Priority_Specific_Dispatching :=
26867         Local_Priority_Specific_Dispatching'Address;
26868       Num_Specific_Dispatching := 0;
26869       Main_CPU := -1;
26870       Interrupt_States := Local_Interrupt_States'Address;
26871       Num_Interrupt_States := 0;
26872       Unreserve_All_Interrupts := 0;
26873       Detect_Blocking := 0;
26874       Default_Stack_Size := -1;
26875       Leap_Seconds_Support := 0;
26877       Runtime_Initialize;
26879       Finalize_Library_Objects := finalize_library'access;
26881       --  Now we have the elaboration calls for all units in the partition.
26882       --  The Elab_Spec and Elab_Body attributes generate references to the
26883       --  implicit elaboration procedures generated by the compiler for
26884       --  each unit that requires elaboration. Increment a counter of
26885       --  reference for each unit.
26887       System.Soft_Links'Elab_Spec;
26888       System.Exception_Table'Elab_Body;
26889       E23 := E23 + 1;
26890       Ada.Io_Exceptions'Elab_Spec;
26891       E46 := E46 + 1;
26892       Ada.Tags'Elab_Spec;
26893       Ada.Streams'Elab_Spec;
26894       E45 := E45 + 1;
26895       Interfaces.C'Elab_Spec;
26896       System.Exceptions'Elab_Spec;
26897       E25 := E25 + 1;
26898       System.Finalization_Root'Elab_Spec;
26899       E68 := E68 + 1;
26900       Ada.Finalization'Elab_Spec;
26901       E66 := E66 + 1;
26902       System.Storage_Pools'Elab_Spec;
26903       E85 := E85 + 1;
26904       System.Finalization_Masters'Elab_Spec;
26905       System.Storage_Pools.Subpools'Elab_Spec;
26906       System.Pool_Global'Elab_Spec;
26907       E87 := E87 + 1;
26908       System.File_Control_Block'Elab_Spec;
26909       E75 := E75 + 1;
26910       System.File_Io'Elab_Body;
26911       E64 := E64 + 1;
26912       E91 := E91 + 1;
26913       System.Finalization_Masters'Elab_Body;
26914       E77 := E77 + 1;
26915       E70 := E70 + 1;
26916       Ada.Tags'Elab_Body;
26917       E48 := E48 + 1;
26918       System.Soft_Links'Elab_Body;
26919       E13 := E13 + 1;
26920       System.Os_Lib'Elab_Body;
26921       E72 := E72 + 1;
26922       System.Secondary_Stack'Elab_Body;
26923       E17 := E17 + 1;
26924       Ada.Text_Io'Elab_Spec;
26925       Ada.Text_Io'Elab_Body;
26926       E06 := E06 + 1;
26927    end adainit;
26929    --------------
26930    -- adafinal --
26931    --------------
26933    procedure adafinal is
26934       procedure s_stalib_adafinal;
26935       pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
26937       procedure Runtime_Finalize;
26938       pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
26940    begin
26941       if not Is_Elaborated then
26942          return;
26943       end if;
26944       Is_Elaborated := False;
26945       Runtime_Finalize;
26946       s_stalib_adafinal;
26947    end adafinal;
26949    --  We get to the main program of the partition by using
26950    --  pragma Import because if we try to with the unit and
26951    --  call it Ada style, then not only do we waste time
26952    --  recompiling it, but also, we don't really know the right
26953    --  switches (e.g.@@: identifier character set) to be used
26954    --  to compile it.
26956    procedure Ada_Main_Program;
26957    pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26959    ----------
26960    -- main --
26961    ----------
26963    --  main is actually a function, as in the ANSI C standard,
26964    --  defined to return the exit status. The three parameters
26965    --  are the argument count, argument values and environment
26966    --  pointer.
26968    function main
26969      (argc : Integer;
26970       argv : System.Address;
26971       envp : System.Address)
26972       return Integer
26973    is
26974       --  The initialize routine performs low level system
26975       --  initialization using a standard library routine which
26976       --  sets up signal handling and performs any other
26977       --  required setup. The routine can be found in file
26978       --  a-init.c.
26980       procedure initialize;
26981       pragma Import (C, initialize, "__gnat_initialize");
26983       --  The finalize routine performs low level system
26984       --  finalization using a standard library routine. The
26985       --  routine is found in file a-final.c and in the standard
26986       --  distribution is a dummy routine that does nothing, so
26987       --  really this is a hook for special user finalization.
26989       procedure finalize;
26990       pragma Import (C, finalize, "__gnat_finalize");
26992       --  The following is to initialize the SEH exceptions
26994       SEH : aliased array (1 .. 2) of Integer;
26996       Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
26997       pragma Volatile (Ensure_Reference);
26999    --  Start of processing for main
27001    begin
27002       --  Save global variables
27004       gnat_argc := argc;
27005       gnat_argv := argv;
27006       gnat_envp := envp;
27008       --  Call low level system initialization
27010       Initialize (SEH'Address);
27012       --  Call our generated Ada initialization routine
27014       adainit;
27016       --  Now we call the main program of the partition
27018       Ada_Main_Program;
27020       --  Perform Ada finalization
27022       adafinal;
27024       --  Perform low level system finalization
27026       Finalize;
27028       --  Return the proper exit status
27029       return (gnat_exit_status);
27030    end;
27032 --  This section is entirely comments, so it has no effect on the
27033 --  compilation of the Ada_Main package. It provides the list of
27034 --  object files and linker options, as well as some standard
27035 --  libraries needed for the link. The gnatlink utility parses
27036 --  this b~hello.adb file to read these comment lines to generate
27037 --  the appropriate command line arguments for the call to the
27038 --  system linker. The BEGIN/END lines are used for sentinels for
27039 --  this parsing operation.
27041 --  The exact file names will of course depend on the environment,
27042 --  host/target and location of files on the host system.
27044 -- BEGIN Object file/option list
27045    --   ./hello.o
27046    --   -L./
27047    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
27048    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
27049 -- END Object file/option list
27051 end ada_main;
27052 @end example
27054 The Ada code in the above example is exactly what is generated by the
27055 binder. We have added comments to more clearly indicate the function
27056 of each part of the generated @code{Ada_Main} package.
27058 The code is standard Ada in all respects, and can be processed by any
27059 tools that handle Ada. In particular, it is possible to use the debugger
27060 in Ada mode to debug the generated @code{Ada_Main} package. For example,
27061 suppose that for reasons that you do not understand, your program is crashing
27062 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
27063 you can place a breakpoint on the call:
27065 @quotation
27067 @example
27068 Ada.Text_Io'Elab_Body;
27069 @end example
27070 @end quotation
27072 and trace the elaboration routine for this package to find out where
27073 the problem might be (more usually of course you would be debugging
27074 elaboration code in your own application).
27076 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
27078 @node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
27079 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order-handling-in-gnat}@anchor{f}@anchor{gnat_ugn/elaboration_order_handling_in_gnat doc}@anchor{230}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id1}@anchor{231}
27080 @chapter Elaboration Order Handling in GNAT
27083 @geindex Order of elaboration
27085 @geindex Elaboration control
27087 This appendix describes the handling of elaboration code in Ada and GNAT, and
27088 discusses how the order of elaboration of program units can be controlled in
27089 GNAT, either automatically or with explicit programming features.
27091 @menu
27092 * Elaboration Code:: 
27093 * Elaboration Order:: 
27094 * Checking the Elaboration Order:: 
27095 * Controlling the Elaboration Order in Ada:: 
27096 * Controlling the Elaboration Order in GNAT:: 
27097 * Common Elaboration-model Traits:: 
27098 * Dynamic Elaboration Model in GNAT:: 
27099 * Static Elaboration Model in GNAT:: 
27100 * SPARK Elaboration Model in GNAT:: 
27101 * Legacy Elaboration Model in GNAT:: 
27102 * Mixing Elaboration Models:: 
27103 * Elaboration Circularities:: 
27104 * Resolving Elaboration Circularities:: 
27105 * Resolving Task Issues:: 
27106 * Elaboration-related Compiler Switches:: 
27107 * Summary of Procedures for Elaboration Control:: 
27108 * Inspecting the Chosen Elaboration Order:: 
27110 @end menu
27112 @node Elaboration Code,Elaboration Order,,Elaboration Order Handling in GNAT
27113 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{232}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{233}
27114 @section Elaboration Code
27117 Ada defines the term @emph{execution} as the process by which a construct achieves
27118 its run-time effect. This process is also referred to as @strong{elaboration} for
27119 declarations and @emph{evaluation} for expressions.
27121 The execution model in Ada allows for certain sections of an Ada program to be
27122 executed prior to execution of the program itself, primarily with the intent of
27123 initializing data. These sections are referred to as @strong{elaboration code}.
27124 Elaboration code is executed as follows:
27127 @itemize *
27129 @item 
27130 All partitions of an Ada program are executed in parallel with one another,
27131 possibly in a separate address space, and possibly on a separate computer.
27133 @item 
27134 The execution of a partition involves running the environment task for that
27135 partition.
27137 @item 
27138 The environment task executes all elaboration code (if available) for all
27139 units within that partition. This code is said to be executed at
27140 @strong{elaboration time}.
27142 @item 
27143 The environment task executes the Ada program (if available) for that
27144 partition.
27145 @end itemize
27147 In addition to the Ada terminology, this appendix defines the following terms:
27150 @itemize *
27152 @item 
27153 @emph{Scenario}
27155 A construct that is elaborated or executed by elaboration code is referred to
27156 as an @emph{elaboration scenario} or simply a @strong{scenario}. GNAT recognizes the
27157 following scenarios:
27160 @itemize -
27162 @item 
27163 @code{'Access} of entries, operators, and subprograms
27165 @item 
27166 Activation of tasks
27168 @item 
27169 Calls to entries, operators, and subprograms
27171 @item 
27172 Instantiations of generic templates
27173 @end itemize
27175 @item 
27176 @emph{Target}
27178 A construct elaborated by a scenario is referred to as @emph{elaboration target}
27179 or simply @strong{target}. GNAT recognizes the following targets:
27182 @itemize -
27184 @item 
27185 For @code{'Access} of entries, operators, and subprograms, the target is the
27186 entry, operator, or subprogram being aliased.
27188 @item 
27189 For activation of tasks, the target is the task body
27191 @item 
27192 For calls to entries, operators, and subprograms, the target is the entry,
27193 operator, or subprogram being invoked.
27195 @item 
27196 For instantiations of generic templates, the target is the generic template
27197 being instantiated.
27198 @end itemize
27199 @end itemize
27201 Elaboration code may appear in two distinct contexts:
27204 @itemize *
27206 @item 
27207 @emph{Library level}
27209 A scenario appears at the library level when it is encapsulated by a package
27210 [body] compilation unit, ignoring any other package [body] declarations in
27211 between.
27213 @example
27214 with Server;
27215 package Client is
27216    procedure Proc;
27218    package Nested is
27219       Val : ... := Server.Func;
27220    end Nested;
27221 end Client;
27222 @end example
27224 In the example above, the call to @code{Server.Func} is an elaboration scenario
27225 because it appears at the library level of package @code{Client}. Note that the
27226 declaration of package @code{Nested} is ignored according to the definition
27227 given above. As a result, the call to @code{Server.Func} will be executed when
27228 the spec of unit @code{Client} is elaborated.
27230 @item 
27231 @emph{Package body statements}
27233 A scenario appears within the statement sequence of a package body when it is
27234 bounded by the region starting from the @code{begin} keyword of the package body
27235 and ending at the @code{end} keyword of the package body.
27237 @example
27238 package body Client is
27239    procedure Proc is
27240    begin
27241       ...
27242    end Proc;
27243 begin
27244    Proc;
27245 end Client;
27246 @end example
27248 In the example above, the call to @code{Proc} is an elaboration scenario because
27249 it appears within the statement sequence of package body @code{Client}. As a
27250 result, the call to @code{Proc} will be executed when the body of @code{Client} is
27251 elaborated.
27252 @end itemize
27254 @node Elaboration Order,Checking the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
27255 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order}@anchor{234}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{235}
27256 @section Elaboration Order
27259 The sequence by which the elaboration code of all units within a partition is
27260 executed is referred to as @strong{elaboration order}.
27262 Within a single unit, elaboration code is executed in sequential order.
27264 @example
27265 package body Client is
27266    Result : ... := Server.Func;
27268    procedure Proc is
27269       package Inst is new Server.Gen;
27270    begin
27271       Inst.Eval (Result);
27272    end Proc;
27273 begin
27274    Proc;
27275 end Client;
27276 @end example
27278 In the example above, the elaboration order within package body @code{Client} is
27279 as follows:
27282 @enumerate 
27284 @item 
27285 The object declaration of @code{Result} is elaborated.
27288 @itemize *
27290 @item 
27291 Function @code{Server.Func} is invoked.
27292 @end itemize
27294 @item 
27295 The subprogram body of @code{Proc} is elaborated.
27297 @item 
27298 Procedure @code{Proc} is invoked.
27301 @itemize *
27303 @item 
27304 Generic unit @code{Server.Gen} is instantiated as @code{Inst}.
27306 @item 
27307 Instance @code{Inst} is elaborated.
27309 @item 
27310 Procedure @code{Inst.Eval} is invoked.
27311 @end itemize
27312 @end enumerate
27314 The elaboration order of all units within a partition depends on the following
27315 factors:
27318 @itemize *
27320 @item 
27321 @emph{with}ed units
27323 @item 
27324 purity of units
27326 @item 
27327 preelaborability of units
27329 @item 
27330 presence of elaboration control pragmas
27331 @end itemize
27333 A program may have several elaboration orders depending on its structure.
27335 @example
27336 package Server is
27337    function Func (Index : Integer) return Integer;
27338 end Server;
27339 @end example
27341 @example
27342 package body Server is
27343    Results : array (1 .. 5) of Integer := (1, 2, 3, 4, 5);
27345    function Func (Index : Integer) return Integer is
27346    begin
27347       return Results (Index);
27348    end Func;
27349 end Server;
27350 @end example
27352 @example
27353 with Server;
27354 package Client is
27355    Val : constant Integer := Server.Func (3);
27356 end Client;
27357 @end example
27359 @example
27360 with Client;
27361 procedure Main is begin null; end Main;
27362 @end example
27364 The following elaboration order exhibits a fundamental problem referred to as
27365 @emph{access-before-elaboration} or simply @strong{ABE}.
27367 @example
27368 spec of Server
27369 spec of Client
27370 body of Server
27371 body of Main
27372 @end example
27374 The elaboration of @code{Server}'s spec materializes function @code{Func}, making it
27375 callable. The elaboration of @code{Client}'s spec elaborates the declaration of
27376 @code{Val}. This invokes function @code{Server.Func}, however the body of
27377 @code{Server.Func} has not been elaborated yet because @code{Server}'s body comes
27378 after @code{Client}'s spec in the elaboration order. As a result, the value of
27379 constant @code{Val} is now undefined.
27381 Without any guarantees from the language, an undetected ABE problem may hinder
27382 proper initialization of data, which in turn may lead to undefined behavior at
27383 run time. To prevent such ABE problems, Ada employs dynamic checks in the same
27384 vein as index or null exclusion checks. A failed ABE check raises exception
27385 @code{Program_Error}.
27387 The following elaboration order avoids the ABE problem and the program can be
27388 successfully elaborated.
27390 @example
27391 spec of Server
27392 body of Server
27393 spec of Client
27394 body of Main
27395 @end example
27397 Ada states that a total elaboration order must exist, but it does not define
27398 what this order is. A compiler is thus tasked with choosing a suitable
27399 elaboration order which satisfies the dependencies imposed by @emph{with} clauses,
27400 unit categorization, and elaboration control pragmas. Ideally an order which
27401 avoids ABE problems should be chosen, however a compiler may not always find
27402 such an order due to complications with respect to control and data flow.
27404 @node Checking the Elaboration Order,Controlling the Elaboration Order in Ada,Elaboration Order,Elaboration Order Handling in GNAT
27405 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id4}@anchor{236}@anchor{gnat_ugn/elaboration_order_handling_in_gnat checking-the-elaboration-order}@anchor{237}
27406 @section Checking the Elaboration Order
27409 To avoid placing the entire elaboration order burden on the programmer, Ada
27410 provides three lines of defense:
27413 @itemize *
27415 @item 
27416 @emph{Static semantics}
27418 Static semantic rules restrict the possible choice of elaboration order. For
27419 instance, if unit Client @emph{with}s unit Server, then the spec of Server is
27420 always elaborated prior to Client. The same principle applies to child units
27421 - the spec of a parent unit is always elaborated prior to the child unit.
27423 @item 
27424 @emph{Dynamic semantics}
27426 Dynamic checks are performed at run time, to ensure that a target is
27427 elaborated prior to a scenario that executes it, thus avoiding ABE problems.
27428 A failed run-time check raises exception @code{Program_Error}. The following
27429 restrictions apply:
27432 @itemize -
27434 @item 
27435 @emph{Restrictions on calls}
27437 An entry, operator, or subprogram can be called from elaboration code only
27438 when the corresponding body has been elaborated.
27440 @item 
27441 @emph{Restrictions on instantiations}
27443 A generic unit can be instantiated by elaboration code only when the
27444 corresponding body has been elaborated.
27446 @item 
27447 @emph{Restrictions on task activation}
27449 A task can be activated by elaboration code only when the body of the
27450 associated task type has been elaborated.
27451 @end itemize
27453 The restrictions above can be summarized by the following rule:
27455 @emph{If a target has a body, then this body must be elaborated prior to the
27456 execution of the scenario that invokes, instantiates, or activates the
27457 target.}
27459 @item 
27460 @emph{Elaboration control}
27462 Pragmas are provided for the programmer to specify the desired elaboration
27463 order.
27464 @end itemize
27466 @node Controlling the Elaboration Order in Ada,Controlling the Elaboration Order in GNAT,Checking the Elaboration Order,Elaboration Order Handling in GNAT
27467 @anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order-in-ada}@anchor{238}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id5}@anchor{239}
27468 @section Controlling the Elaboration Order in Ada
27471 Ada provides several idioms and pragmas to aid the programmer with specifying
27472 the desired elaboration order and avoiding ABE problems altogether.
27475 @itemize *
27477 @item 
27478 @emph{Packages without a body}
27480 A library package which does not require a completing body does not suffer
27481 from ABE problems.
27483 @example
27484 package Pack is
27485    generic
27486       type Element is private;
27487    package Containers is
27488       type Element_Array is array (1 .. 10) of Element;
27489    end Containers;
27490 end Pack;
27491 @end example
27493 In the example above, package @code{Pack} does not require a body because it
27494 does not contain any constructs which require completion in a body. As a
27495 result, generic @code{Pack.Containers} can be instantiated without encountering
27496 any ABE problems.
27497 @end itemize
27499 @geindex pragma Pure
27502 @itemize *
27504 @item 
27505 @emph{pragma Pure}
27507 Pragma @code{Pure} places sufficient restrictions on a unit to guarantee that no
27508 scenario within the unit can result in an ABE problem.
27509 @end itemize
27511 @geindex pragma Preelaborate
27514 @itemize *
27516 @item 
27517 @emph{pragma Preelaborate}
27519 Pragma @code{Preelaborate} is slightly less restrictive than pragma @code{Pure},
27520 but still strong enough to prevent ABE problems within a unit.
27521 @end itemize
27523 @geindex pragma Elaborate_Body
27526 @itemize *
27528 @item 
27529 @emph{pragma Elaborate_Body}
27531 Pragma @code{Elaborate_Body} requires that the body of a unit is elaborated
27532 immediately after its spec. This restriction guarantees that no client
27533 scenario can execute a server target before the target body has been
27534 elaborated because the spec and body are effectively "glued" together.
27536 @example
27537 package Server is
27538    pragma Elaborate_Body;
27540    function Func return Integer;
27541 end Server;
27542 @end example
27544 @example
27545 package body Server is
27546    function Func return Integer is
27547    begin
27548       ...
27549    end Func;
27550 end Server;
27551 @end example
27553 @example
27554 with Server;
27555 package Client is
27556    Val : constant Integer := Server.Func;
27557 end Client;
27558 @end example
27560 In the example above, pragma @code{Elaborate_Body} guarantees the following
27561 elaboration order:
27563 @example
27564 spec of Server
27565 body of Server
27566 spec of Client
27567 @end example
27569 because the spec of @code{Server} must be elaborated prior to @code{Client} by
27570 virtue of the @emph{with} clause, and in addition the body of @code{Server} must be
27571 elaborated immediately after the spec of @code{Server}.
27573 Removing pragma @code{Elaborate_Body} could result in the following incorrect
27574 elaboration order:
27576 @example
27577 spec of Server
27578 spec of Client
27579 body of Server
27580 @end example
27582 where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func} has
27583 not been elaborated yet.
27584 @end itemize
27586 The pragmas outlined above allow a server unit to guarantee safe elaboration
27587 use by client units. Thus it is a good rule to mark units as @code{Pure} or
27588 @code{Preelaborate}, and if this is not possible, mark them as @code{Elaborate_Body}.
27590 There are however situations where @code{Pure}, @code{Preelaborate}, and
27591 @code{Elaborate_Body} are not applicable. Ada provides another set of pragmas for
27592 use by client units to help ensure the elaboration safety of server units they
27593 depend on.
27595 @geindex pragma Elaborate (Unit)
27598 @itemize *
27600 @item 
27601 @emph{pragma Elaborate (Unit)}
27603 Pragma @code{Elaborate} can be placed in the context clauses of a unit, after a
27604 @emph{with} clause. It guarantees that both the spec and body of its argument will
27605 be elaborated prior to the unit with the pragma. Note that other unrelated
27606 units may be elaborated in between the spec and the body.
27608 @example
27609 package Server is
27610    function Func return Integer;
27611 end Server;
27612 @end example
27614 @example
27615 package body Server is
27616    function Func return Integer is
27617    begin
27618       ...
27619    end Func;
27620 end Server;
27621 @end example
27623 @example
27624 with Server;
27625 pragma Elaborate (Server);
27626 package Client is
27627    Val : constant Integer := Server.Func;
27628 end Client;
27629 @end example
27631 In the example above, pragma @code{Elaborate} guarantees the following
27632 elaboration order:
27634 @example
27635 spec of Server
27636 body of Server
27637 spec of Client
27638 @end example
27640 Removing pragma @code{Elaborate} could result in the following incorrect
27641 elaboration order:
27643 @example
27644 spec of Server
27645 spec of Client
27646 body of Server
27647 @end example
27649 where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func}
27650 has not been elaborated yet.
27651 @end itemize
27653 @geindex pragma Elaborate_All (Unit)
27656 @itemize *
27658 @item 
27659 @emph{pragma Elaborate_All (Unit)}
27661 Pragma @code{Elaborate_All} is placed in the context clauses of a unit, after
27662 a @emph{with} clause. It guarantees that both the spec and body of its argument
27663 will be elaborated prior to the unit with the pragma, as well as all units
27664 @emph{with}ed by the spec and body of the argument, recursively. Note that other
27665 unrelated units may be elaborated in between the spec and the body.
27667 @example
27668 package Math is
27669    function Factorial (Val : Natural) return Natural;
27670 end Math;
27671 @end example
27673 @example
27674 package body Math is
27675    function Factorial (Val : Natural) return Natural is
27676    begin
27677       ...;
27678    end Factorial;
27679 end Math;
27680 @end example
27682 @example
27683 package Computer is
27684    type Operation_Kind is (None, Op_Factorial);
27686    function Compute
27687      (Val : Natural;
27688       Op  : Operation_Kind) return Natural;
27689 end Computer;
27690 @end example
27692 @example
27693 with Math;
27694 package body Computer is
27695    function Compute
27696      (Val : Natural;
27697       Op  : Operation_Kind) return Natural
27698    is
27699       if Op = Op_Factorial then
27700          return Math.Factorial (Val);
27701       end if;
27703       return 0;
27704    end Compute;
27705 end Computer;
27706 @end example
27708 @example
27709 with Computer;
27710 pragma Elaborate_All (Computer);
27711 package Client is
27712    Val : constant Natural :=
27713            Computer.Compute (123, Computer.Op_Factorial);
27714 end Client;
27715 @end example
27717 In the example above, pragma @code{Elaborate_All} can result in the following
27718 elaboration order:
27720 @example
27721 spec of Math
27722 body of Math
27723 spec of Computer
27724 body of Computer
27725 spec of Client
27726 @end example
27728 Note that there are several allowable suborders for the specs and bodies of
27729 @code{Math} and @code{Computer}, but the point is that these specs and bodies will
27730 be elaborated prior to @code{Client}.
27732 Removing pragma @code{Elaborate_All} could result in the following incorrect
27733 elaboration order
27735 @example
27736 spec of Math
27737 spec of Computer
27738 body of Computer
27739 spec of Client
27740 body of Math
27741 @end example
27743 where @code{Client} invokes @code{Computer.Compute}, which in turn invokes
27744 @code{Math.Factorial}, but the body of @code{Math.Factorial} has not been
27745 elaborated yet.
27746 @end itemize
27748 All pragmas shown above can be summarized by the following rule:
27750 @emph{If a client unit elaborates a server target directly or indirectly, then if
27751 the server unit requires a body and does not have pragma Pure, Preelaborate,
27752 or Elaborate_Body, then the client unit should have pragma Elaborate or
27753 Elaborate_All for the server unit.}
27755 If the rule outlined above is not followed, then a program may fall in one of
27756 the following states:
27759 @itemize *
27761 @item 
27762 @emph{No elaboration order exists}
27764 In this case a compiler must diagnose the situation, and refuse to build an
27765 executable program.
27767 @item 
27768 @emph{One or more incorrect elaboration orders exist}
27770 In this case a compiler can build an executable program, but
27771 @code{Program_Error} will be raised when the program is run.
27773 @item 
27774 @emph{Several elaboration orders exist, some correct, some incorrect}
27776 In this case the programmer has not controlled the elaboration order. As a
27777 result, a compiler may or may not pick one of the correct orders, and the
27778 program may or may not raise @code{Program_Error} when it is run. This is the
27779 worst possible state because the program may fail on another compiler, or
27780 even another version of the same compiler.
27782 @item 
27783 @emph{One or more correct orders exist}
27785 In this case a compiler can build an executable program, and the program is
27786 run successfully. This state may be guaranteed by following the outlined
27787 rules, or may be the result of good program architecture.
27788 @end itemize
27790 Note that one additional advantage of using @code{Elaborate} and @code{Elaborate_All}
27791 is that the program continues to stay in the last state (one or more correct
27792 orders exist) even if maintenance changes the bodies of targets.
27794 @node Controlling the Elaboration Order in GNAT,Common Elaboration-model Traits,Controlling the Elaboration Order in Ada,Elaboration Order Handling in GNAT
27795 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id6}@anchor{23a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order-in-gnat}@anchor{23b}
27796 @section Controlling the Elaboration Order in GNAT
27799 In addition to Ada semantics and rules synthesized from them, GNAT offers
27800 three elaboration models to aid the programmer with specifying the correct
27801 elaboration order and to diagnose elaboration problems.
27803 @geindex Dynamic elaboration model
27806 @itemize *
27808 @item 
27809 @emph{Dynamic elaboration model}
27811 This is the most permissive of the three elaboration models. When the
27812 dynamic model is in effect, GNAT assumes that all code within all units in
27813 a partition is elaboration code. GNAT performs very few diagnostics and
27814 generates run-time checks to verify the elaboration order of a program. This
27815 behavior is identical to that specified by the Ada Reference Manual. The
27816 dynamic model is enabled with compiler switch @code{-gnatE}.
27817 @end itemize
27819 @geindex Static elaboration model
27822 @itemize *
27824 @item 
27825 @emph{Static elaboration model}
27827 This is the middle ground of the three models. When the static model is in
27828 effect, GNAT performs extensive diagnostics on a unit-by-unit basis for all
27829 scenarios that elaborate or execute internal targets. GNAT also generates
27830 run-time checks for all external targets and for all scenarios that may
27831 exhibit ABE problems. Finally, GNAT installs implicit @code{Elaborate} and
27832 @code{Elaborate_All} pragmas for server units based on the dependencies of
27833 client units. The static model is the default model in GNAT.
27834 @end itemize
27836 @geindex SPARK elaboration model
27839 @itemize *
27841 @item 
27842 @emph{SPARK elaboration model}
27844 This is the most conservative of the three models and enforces the SPARK
27845 rules of elaboration as defined in the SPARK Reference Manual, section 7.7.
27846 The SPARK model is in effect only when a scenario and a target reside in a
27847 region subject to SPARK_Mode On, otherwise the dynamic or static model is in
27848 effect.
27849 @end itemize
27851 @geindex Legacy elaboration model
27854 @itemize *
27856 @item 
27857 @emph{Legacy elaboration model}
27859 In addition to the three elaboration models outlined above, GNAT provides the
27860 elaboration model of pre-18.x versions referred to as @cite{legacy elaboration model}. The legacy elaboration model is enabled with compiler switch
27861 @code{-gnatH}.
27862 @end itemize
27864 @geindex Relaxed elaboration mode
27866 The dynamic, legacy, and static models can be relaxed using compiler switch
27867 @code{-gnatJ}, making them more permissive. Note that in this mode, GNAT
27868 may not diagnose certain elaboration issues or install run-time checks.
27870 @node Common Elaboration-model Traits,Dynamic Elaboration Model in GNAT,Controlling the Elaboration Order in GNAT,Elaboration Order Handling in GNAT
27871 @anchor{gnat_ugn/elaboration_order_handling_in_gnat common-elaboration-model-traits}@anchor{23c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{23d}
27872 @section Common Elaboration-model Traits
27875 All three GNAT models are able to detect elaboration problems related to
27876 dispatching calls and a particular kind of ABE referred to as @emph{guaranteed ABE}.
27879 @itemize *
27881 @item 
27882 @emph{Dispatching calls}
27884 GNAT installs run-time checks for each primitive subprogram of each tagged
27885 type defined in a partition on the assumption that a dispatching call
27886 invoked at elaboration time will execute one of these primitives. As a
27887 result, a dispatching call that executes a primitive whose body has not
27888 been elaborated yet will raise exception @code{Program_Error} at run time. The
27889 checks can be suppressed using pragma @code{Suppress (Elaboration_Check)}.
27891 @item 
27892 @emph{Guaranteed ABE}
27894 A guaranteed ABE arises when the body of a target is not elaborated early
27895 enough, and causes all scenarios that directly execute the target to fail.
27897 @example
27898 package body Guaranteed_ABE is
27899    function ABE return Integer;
27901    Val : constant Integer := ABE;
27903    function ABE return Integer is
27904    begin
27905       ...
27906    end ABE;
27907 end Guaranteed_ABE;
27908 @end example
27910 In the example above, the elaboration of @code{Guaranteed_ABE}'s body elaborates
27911 the declaration of @code{Val}. This invokes function @code{ABE}, however the body
27912 of @code{ABE} has not been elaborated yet. GNAT emits similar diagnostics in all
27913 three models:
27915 @example
27916 1. package body Guaranteed_ABE is
27917 2.    function ABE return Integer;
27919 4.    Val : constant Integer := ABE;
27920                                 |
27921    >>> warning: cannot call "ABE" before body seen
27922    >>> warning: Program_Error will be raised at run time
27925 6.    function ABE return Integer is
27926 7.    begin
27927 8.       ...
27928 9.    end ABE;
27929 10. end Guaranteed_ABE;
27930 @end example
27931 @end itemize
27933 Note that GNAT emits warnings rather than hard errors whenever it encounters an
27934 elaboration problem. This is because the elaboration model in effect may be too
27935 conservative, or a particular scenario may not be elaborated or executed due to
27936 data and control flow. The warnings can be suppressed selectively with @code{pragma
27937 Warnigns (Off)} or globally with compiler switch @code{-gnatwL}.
27939 @node Dynamic Elaboration Model in GNAT,Static Elaboration Model in GNAT,Common Elaboration-model Traits,Elaboration Order Handling in GNAT
27940 @anchor{gnat_ugn/elaboration_order_handling_in_gnat dynamic-elaboration-model-in-gnat}@anchor{23e}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{23f}
27941 @section Dynamic Elaboration Model in GNAT
27944 The dynamic model assumes that all code within all units in a partition is
27945 elaboration code. As a result, run-time checks are installed for each scenario
27946 regardless of whether the target is internal or external. The checks can be
27947 suppressed using pragma @code{Suppress (Elaboration_Check)}. This behavior is
27948 identical to that specified by the Ada Reference Manual. The following example
27949 showcases run-time checks installed by GNAT to verify the elaboration state of
27950 package @code{Dynamic_Model}.
27952 @example
27953 with Server;
27954 package body Dynamic_Model is
27955    procedure API is
27956    begin
27957       ...
27958    end API;
27960    <check that the body of Server.Gen is elaborated>
27961    package Inst is new Server.Gen;
27963    T : Server.Task_Type;
27965 begin
27966    <check that the body of Server.Task_Type is elaborated>
27968    <check that the body of Server.Proc is elaborated>
27969    Server.Proc;
27970 end Dynamic_Model;
27971 @end example
27973 The checks verify that the body of a target has been successfully elaborated
27974 before a scenario activates, calls, or instantiates a target.
27976 Note that no scenario within package @code{Dynamic_Model} calls procedure @code{API}.
27977 In fact, procedure @code{API} may not be invoked by elaboration code within the
27978 partition, however the dynamic model assumes that this can happen.
27980 The dynamic model emits very few diagnostics, but can make suggestions on
27981 missing @code{Elaborate} and @code{Elaborate_All} pragmas for library-level
27982 scenarios. This information is available when compiler switch @code{-gnatel}
27983 is in effect.
27985 @example
27986 1. with Server;
27987 2. package body Dynamic_Model is
27988 3.    Val : constant Integer := Server.Func;
27989                                       |
27990    >>> info: call to "Func" during elaboration
27991    >>> info: missing pragma "Elaborate_All" for unit "Server"
27993 4. end Dynamic_Model;
27994 @end example
27996 @node Static Elaboration Model in GNAT,SPARK Elaboration Model in GNAT,Dynamic Elaboration Model in GNAT,Elaboration Order Handling in GNAT
27997 @anchor{gnat_ugn/elaboration_order_handling_in_gnat static-elaboration-model-in-gnat}@anchor{240}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{241}
27998 @section Static Elaboration Model in GNAT
28001 In contrast to the dynamic model, the static model is more precise in its
28002 analysis of elaboration code. The model makes a clear distinction between
28003 internal and external targets, and resorts to different diagnostics and
28004 run-time checks based on the nature of the target.
28007 @itemize *
28009 @item 
28010 @emph{Internal targets}
28012 The static model performs extensive diagnostics on scenarios which elaborate
28013 or execute internal targets. The warnings resulting from these diagnostics
28014 are enabled by default, but can be suppressed selectively with @code{pragma
28015 Warnings (Off)} or globally with compiler switch @code{-gnatwL}.
28017 @example
28018  1. package body Static_Model is
28019  2.    generic
28020  3.       with function Func return Integer;
28021  4.    package Gen is
28022  5.       Val : constant Integer := Func;
28023  6.    end Gen;
28024  7.
28025  8.    function ABE return Integer;
28026  9.
28027 10.    function Cause_ABE return Boolean is
28028 11.       package Inst is new Gen (ABE);
28029           |
28030     >>> warning: in instantiation at line 5
28031     >>> warning: cannot call "ABE" before body seen
28032     >>> warning: Program_Error may be raised at run time
28033     >>> warning:   body of unit "Static_Model" elaborated
28034     >>> warning:   function "Cause_ABE" called at line 16
28035     >>> warning:   function "ABE" called at line 5, instance at line 11
28037 12.    begin
28038 13.       ...
28039 14.    end Cause_ABE;
28041 16.    Val : constant Boolean := Cause_ABE;
28043 18.    function ABE return Integer is
28044 19.    begin
28045 20.       ...
28046 21.    end ABE;
28047 22. end Static_Model;
28048 @end example
28050 The example above illustrates an ABE problem within package @code{Static_Model},
28051 which is hidden by several layers of indirection. The elaboration of package
28052 body @code{Static_Model} elaborates the declaration of @code{Val}. This invokes
28053 function @code{Cause_ABE}, which instantiates generic unit @code{Gen} as @code{Inst}.
28054 The elaboration of @code{Inst} invokes function @code{ABE}, however the body of
28055 @code{ABE} has not been elaborated yet.
28057 @item 
28058 @emph{External targets}
28060 The static model installs run-time checks to verify the elaboration status
28061 of server targets only when the scenario that elaborates or executes that
28062 target is part of the elaboration code of the client unit. The checks can be
28063 suppressed using pragma @code{Suppress (Elaboration_Check)}.
28065 @example
28066 with Server;
28067 package body Static_Model is
28068    generic
28069       with function Func return Integer;
28070    package Gen is
28071       Val : constant Integer := Func;
28072    end Gen;
28074    function Call_Func return Boolean is
28075       <check that the body of Server.Func is elaborated>
28076       package Inst is new Gen (Server.Func);
28077    begin
28078       ...
28079    end Call_Func;
28081    Val : constant Boolean := Call_Func;
28082 end Static_Model;
28083 @end example
28085 In the example above, the elaboration of package body @code{Static_Model}
28086 elaborates the declaration of @code{Val}. This invokes function @code{Call_Func},
28087 which instantiates generic unit @code{Gen} as @code{Inst}. The elaboration of
28088 @code{Inst} invokes function @code{Server.Func}. Since @code{Server.Func} is an
28089 external target, GNAT installs a run-time check to verify that its body has
28090 been elaborated.
28092 In addition to checks, the static model installs implicit @code{Elaborate} and
28093 @code{Elaborate_All} pragmas to guarantee safe elaboration use of server units.
28094 This information is available when compiler switch @code{-gnatel} is in
28095 effect.
28097 @example
28098  1. with Server;
28099  2. package body Static_Model is
28100  3.    generic
28101  4.       with function Func return Integer;
28102  5.    package Gen is
28103  6.       Val : constant Integer := Func;
28104  7.    end Gen;
28105  8.
28106  9.    function Call_Func return Boolean is
28107 10.       package Inst is new Gen (Server.Func);
28108           |
28109     >>> info: instantiation of "Gen" during elaboration
28110     >>> info: in instantiation at line 6
28111     >>> info: call to "Func" during elaboration
28112     >>> info: in instantiation at line 6
28113     >>> info: implicit pragma "Elaborate_All" generated for unit "Server"
28114     >>> info:   body of unit "Static_Model" elaborated
28115     >>> info:   function "Call_Func" called at line 15
28116     >>> info:   function "Func" called at line 6, instance at line 10
28118 11.    begin
28119 12.       ...
28120 13.    end Call_Func;
28122 15.    Val : constant Boolean := Call_Func;
28123                                  |
28124     >>> info: call to "Call_Func" during elaboration
28126 16. end Static_Model;
28127 @end example
28129 In the example above, the elaboration of package body @code{Static_Model}
28130 elaborates the declaration of @code{Val}. This invokes function @code{Call_Func},
28131 which instantiates generic unit @code{Gen} as @code{Inst}. The elaboration of
28132 @code{Inst} invokes function @code{Server.Func}. Since @code{Server.Func} is an
28133 external target, GNAT installs an implicit @code{Elaborate_All} pragma for unit
28134 @code{Server}. The pragma guarantees that both the spec and body of @code{Server},
28135 along with any additional dependencies that @code{Server} may require, are
28136 elaborated prior to the body of @code{Static_Model}.
28137 @end itemize
28139 @node SPARK Elaboration Model in GNAT,Legacy Elaboration Model in GNAT,Static Elaboration Model in GNAT,Elaboration Order Handling in GNAT
28140 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{242}@anchor{gnat_ugn/elaboration_order_handling_in_gnat spark-elaboration-model-in-gnat}@anchor{243}
28141 @section SPARK Elaboration Model in GNAT
28144 The SPARK model is identical to the static model in its handling of internal
28145 targets. The SPARK model, however, requires explicit @code{Elaborate} or
28146 @code{Elaborate_All} pragmas to be present in the program when a target is
28147 external, and compiler switch @code{-gnatd.v} is in effect.
28149 @example
28150 1. with Server;
28151 2. package body SPARK_Model with SPARK_Mode is
28152 3.    Val : constant Integer := Server.Func;
28153                                       |
28154    >>> call to "Func" during elaboration in SPARK
28155    >>> unit "SPARK_Model" requires pragma "Elaborate_All" for "Server"
28156    >>>   body of unit "SPARK_Model" elaborated
28157    >>>   function "Func" called at line 3
28159 4. end SPARK_Model;
28160 @end example
28162 @node Legacy Elaboration Model in GNAT,Mixing Elaboration Models,SPARK Elaboration Model in GNAT,Elaboration Order Handling in GNAT
28163 @anchor{gnat_ugn/elaboration_order_handling_in_gnat legacy-elaboration-model-in-gnat}@anchor{244}
28164 @section Legacy Elaboration Model in GNAT
28167 The legacy elaboration model is provided for compatibility with code bases
28168 developed with pre-18.x versions of GNAT. It is similar in functionality to
28169 the dynamic and static models of post-18.x version of GNAT, but may differ
28170 in terms of diagnostics and run-time checks. The legacy elaboration model is
28171 enabled with compiler switch @code{-gnatH}.
28173 @node Mixing Elaboration Models,Elaboration Circularities,Legacy Elaboration Model in GNAT,Elaboration Order Handling in GNAT
28174 @anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{245}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{246}
28175 @section Mixing Elaboration Models
28178 It is possible to mix units compiled with a different elaboration model,
28179 however the following rules must be observed:
28182 @itemize *
28184 @item 
28185 A client unit compiled with the dynamic model can only @emph{with} a server unit
28186 that meets at least one of the following criteria:
28189 @itemize -
28191 @item 
28192 The server unit is compiled with the dynamic model.
28194 @item 
28195 The server unit is a GNAT implementation unit from the Ada, GNAT,
28196 Interfaces, or System hierarchies.
28198 @item 
28199 The server unit has pragma @code{Pure} or @code{Preelaborate}.
28201 @item 
28202 The client unit has an explicit @code{Elaborate_All} pragma for the server
28203 unit.
28204 @end itemize
28205 @end itemize
28207 These rules ensure that elaboration checks are not omitted. If the rules are
28208 violated, the binder emits a warning:
28210 @example
28211 warning: "x.ads" has dynamic elaboration checks and with's
28212 warning:   "y.ads" which has static elaboration checks
28213 @end example
28215 The warnings can be suppressed by binder switch @code{-ws}.
28217 @node Elaboration Circularities,Resolving Elaboration Circularities,Mixing Elaboration Models,Elaboration Order Handling in GNAT
28218 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id12}@anchor{247}@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-circularities}@anchor{248}
28219 @section Elaboration Circularities
28222 If the binder cannot find an acceptable elaboration order, it outputs detailed
28223 diagnostics describing an @strong{elaboration circularity}.
28225 @example
28226 package Server is
28227    function Func return Integer;
28228 end Server;
28229 @end example
28231 @example
28232 with Client;
28233 package body Server is
28234    function Func return Integer is
28235    begin
28236       ...
28237    end Func;
28238 end Server;
28239 @end example
28241 @example
28242 with Server;
28243 package Client is
28244    Val : constant Integer := Server.Func;
28245 end Client;
28246 @end example
28248 @example
28249 with Client;
28250 procedure Main is begin null; end Main;
28251 @end example
28253 @example
28254 error: elaboration circularity detected
28255 info:    "server (body)" must be elaborated before "client (spec)"
28256 info:       reason: implicit Elaborate_All in unit "client (spec)"
28257 info:       recompile "client (spec)" with -gnatel for full details
28258 info:          "server (body)"
28259 info:             must be elaborated along with its spec:
28260 info:          "server (spec)"
28261 info:             which is withed by:
28262 info:          "client (spec)"
28263 info:    "client (spec)" must be elaborated before "server (body)"
28264 info:       reason: with clause
28265 @end example
28267 In the example above, @code{Client} must be elaborated prior to @code{Main} by virtue
28268 of a @emph{with} clause. The elaboration of @code{Client} invokes @code{Server.Func}, and
28269 static model generates an implicit @code{Elaborate_All} pragma for @code{Server}. The
28270 pragma implies that both the spec and body of @code{Server}, along with any units
28271 they @emph{with}, must be elaborated prior to @code{Client}. However, @code{Server}'s body
28272 @emph{with}s @code{Client}, implying that @code{Client} must be elaborated prior to
28273 @code{Server}. The end result is that @code{Client} must be elaborated prior to
28274 @code{Client}, and this leads to a circularity.
28276 @node Resolving Elaboration Circularities,Resolving Task Issues,Elaboration Circularities,Elaboration Order Handling in GNAT
28277 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id13}@anchor{249}@anchor{gnat_ugn/elaboration_order_handling_in_gnat resolving-elaboration-circularities}@anchor{24a}
28278 @section Resolving Elaboration Circularities
28281 When faced with an elaboration circularity, a programmer has several options
28282 available.
28285 @itemize *
28287 @item 
28288 @emph{Fix the program}
28290 The most desirable option from the point of view of long-term maintenance
28291 is to rearrange the program so that the elaboration problems are avoided.
28292 One useful technique is to place the elaboration code into separate child
28293 packages. Another is to move some of the initialization code to explicitly
28294 invoked subprograms, where the program controls the order of initialization
28295 explicitly. Although this is the most desirable option, it may be impractical
28296 and involve too much modification, especially in the case of complex legacy
28297 code.
28299 @item 
28300 @emph{Switch to more permissive elaboration model}
28302 If the compilation was performed using the static model, enable the dynamic
28303 model with compiler switch @code{-gnatE}. GNAT will no longer generate
28304 implicit @code{Elaborate} and @code{Elaborate_All} pragmas, resulting in a behavior
28305 identical to that specified by the Ada Reference Manual. The binder will
28306 generate an executable program that may or may not raise @code{Program_Error},
28307 and it is the programmer's responsibility to ensure that it does not raise
28308 @code{Program_Error}.
28310 If the compilation was performed using a post-18.x version of GNAT, consider
28311 using the legacy elaboration model, in the following order:
28314 @itemize -
28316 @item 
28317 Use the legacy static elaboration model, with compiler switch
28318 @code{-gnatH}.
28320 @item 
28321 Use the legacy dynamic elaboration model, with compiler switches
28322 @code{-gnatH} @code{-gnatE}.
28324 @item 
28325 Use the relaxed legacy static elaboration model, with compiler switches
28326 @code{-gnatH} @code{-gnatJ}.
28328 @item 
28329 Use the relaxed legacy dynamic elaboration model, with compiler switches
28330 @code{-gnatH} @code{-gnatJ} @code{-gnatE}.
28331 @end itemize
28333 @item 
28334 @emph{Suppress all elaboration checks}
28336 The drawback of run-time checks is that they generate overhead at run time,
28337 both in space and time. If the programmer is absolutely sure that a program
28338 will not raise an elaboration-related @code{Program_Error}, then using the
28339 pragma @code{Suppress (Elaboration_Check)} globally (as a configuration pragma)
28340 will eliminate all run-time checks.
28342 @item 
28343 @emph{Suppress elaboration checks selectively}
28345 If a scenario cannot possibly lead to an elaboration @code{Program_Error},
28346 and the binder nevertheless complains about implicit @code{Elaborate} and
28347 @code{Elaborate_All} pragmas that lead to elaboration circularities, it
28348 is possible to suppress the generation of implicit @code{Elaborate} and
28349 @code{Elaborate_All} pragmas, as well as run-time checks. Clearly this can
28350 be unsafe, and it is the responsibility of the programmer to make sure
28351 that the resulting program has no elaboration anomalies. Pragma
28352 @code{Suppress (Elaboration_Check)} can be used with different levels of
28353 granularity to achieve these effects.
28356 @itemize -
28358 @item 
28359 @emph{Target suppression}
28361 When the pragma is placed in a declarative part, without a second argument
28362 naming an entity, it will suppress implicit @code{Elaborate} and
28363 @code{Elaborate_All} pragma generation, as well as run-time checks, on all
28364 targets within the region.
28366 @example
28367 package Range_Suppress is
28368    pragma Suppress (Elaboration_Check);
28370    function Func return Integer;
28372    generic
28373    procedure Gen;
28375    pragma Unsuppress (Elaboration_Check);
28377    task type Tsk;
28378 end Range_Suppress;
28379 @end example
28381 In the example above, a pair of Suppress/Unsuppress pragmas define a region
28382 of suppression within package @code{Range_Suppress}. As a result, no implicit
28383 @code{Elaborate} and @code{Elaborate_All} pragmas, nor any run-time checks, will
28384 be generated by callers of @code{Func} and instantiators of @code{Gen}. Note that
28385 task type @code{Tsk} is not within this region.
28387 An alternative to the region-based suppression is to use multiple
28388 @code{Suppress} pragmas with arguments naming specific entities for which
28389 elaboration checks should be suppressed:
28391 @example
28392 package Range_Suppress is
28393    function Func return Integer;
28394    pragma Suppress (Elaboration_Check, Func);
28396    generic
28397    procedure Gen;
28398    pragma Suppress (Elaboration_Check, Gen);
28400    task type Tsk;
28401 end Range_Suppress;
28402 @end example
28404 @item 
28405 @emph{Scenario suppression}
28407 When the pragma @code{Suppress} is placed in a declarative or statement
28408 part, without an entity argument, it will suppress implicit @code{Elaborate}
28409 and @code{Elaborate_All} pragma generation, as well as run-time checks, on
28410 all scenarios within the region.
28412 @example
28413 with Server;
28414 package body Range_Suppress is
28415    pragma Suppress (Elaboration_Check);
28417    function Func return Integer is
28418    begin
28419       return Server.Func;
28420    end Func;
28422    procedure Gen is
28423    begin
28424       Server.Proc;
28425    end Gen;
28427    pragma Unsuppress (Elaboration_Check);
28429    task body Tsk is
28430    begin
28431       Server.Proc;
28432    end Tsk;
28433 end Range_Suppress;
28434 @end example
28436 In the example above, a pair of Suppress/Unsuppress pragmas define a region
28437 of suppression within package body @code{Range_Suppress}. As a result, the
28438 calls to @code{Server.Func} in @code{Func} and @code{Server.Proc} in @code{Gen} will
28439 not generate any implicit @code{Elaborate} and @code{Elaborate_All} pragmas or
28440 run-time checks.
28441 @end itemize
28442 @end itemize
28444 @node Resolving Task Issues,Elaboration-related Compiler Switches,Resolving Elaboration Circularities,Elaboration Order Handling in GNAT
28445 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id14}@anchor{24b}@anchor{gnat_ugn/elaboration_order_handling_in_gnat resolving-task-issues}@anchor{24c}
28446 @section Resolving Task Issues
28449 The model of execution in Ada dictates that elaboration must first take place,
28450 and only then can the main program be started. Tasks which are activated during
28451 elaboration violate this model and may lead to serious concurrent problems at
28452 elaboration time.
28454 A task can be activated in two different ways:
28457 @itemize *
28459 @item 
28460 The task is created by an allocator in which case it is activated immediately
28461 after the allocator is evaluated.
28463 @item 
28464 The task is declared at the library level or within some nested master in
28465 which case it is activated before starting execution of the statement
28466 sequence of the master defining the task.
28467 @end itemize
28469 Since the elaboration of a partition is performed by the environment task
28470 servicing that partition, any tasks activated during elaboration may be in
28471 a race with the environment task, and lead to unpredictable state and behavior.
28472 The static model seeks to avoid such interactions by assuming that all code in
28473 the task body is executed at elaboration time, if the task was activated by
28474 elaboration code.
28476 @example
28477 package Decls is
28478    task Lib_Task is
28479       entry Start;
28480    end Lib_Task;
28482    type My_Int is new Integer;
28484    function Ident (M : My_Int) return My_Int;
28485 end Decls;
28486 @end example
28488 @example
28489 with Utils;
28490 package body Decls is
28491    task body Lib_Task is
28492    begin
28493       accept Start;
28494       Utils.Put_Val (2);
28495    end Lib_Task;
28497    function Ident (M : My_Int) return My_Int is
28498    begin
28499       return M;
28500    end Ident;
28501 end Decls;
28502 @end example
28504 @example
28505 with Decls;
28506 package Utils is
28507    procedure Put_Val (Arg : Decls.My_Int);
28508 end Utils;
28509 @end example
28511 @example
28512 with Ada.Text_IO; use Ada.Text_IO;
28513 package body Utils is
28514    procedure Put_Val (Arg : Decls.My_Int) is
28515    begin
28516       Put_Line (Arg'Img);
28517    end Put_Val;
28518 end Utils;
28519 @end example
28521 @example
28522 with Decls;
28523 procedure Main is
28524 begin
28525    Decls.Lib_Task.Start;
28526 end Main;
28527 @end example
28529 When the above example is compiled with the static model, an elaboration
28530 circularity arises:
28532 @example
28533 error: elaboration circularity detected
28534 info:    "decls (body)" must be elaborated before "decls (body)"
28535 info:       reason: implicit Elaborate_All in unit "decls (body)"
28536 info:       recompile "decls (body)" with -gnatel for full details
28537 info:          "decls (body)"
28538 info:             must be elaborated along with its spec:
28539 info:          "decls (spec)"
28540 info:             which is withed by:
28541 info:          "utils (spec)"
28542 info:             which is withed by:
28543 info:          "decls (body)"
28544 @end example
28546 In the above example, @code{Decls} must be elaborated prior to @code{Main} by virtue
28547 of a with clause. The elaboration of @code{Decls} activates task @code{Lib_Task}. The
28548 static model conservatibely assumes that all code within the body of
28549 @code{Lib_Task} is executed, and generates an implicit @code{Elaborate_All} pragma
28550 for @code{Units} due to the call to @code{Utils.Put_Val}. The pragma implies that
28551 both the spec and body of @code{Utils}, along with any units they @emph{with},
28552 must be elaborated prior to @code{Decls}. However, @code{Utils}'s spec @emph{with}s
28553 @code{Decls}, implying that @code{Decls} must be elaborated before @code{Utils}. The end
28554 result is that @code{Utils} must be elaborated prior to @code{Utils}, and this
28555 leads to a circularity.
28557 In reality, the example above will not exhibit an ABE problem at run time.
28558 When the body of task @code{Lib_Task} is activated, execution will wait for entry
28559 @code{Start} to be accepted, and the call to @code{Utils.Put_Val} will not take place
28560 at elaboration time. Task @code{Lib_Task} will resume its execution after the main
28561 program is executed because @code{Main} performs a rendezvous with
28562 @code{Lib_Task.Start}, and at that point all units have already been elaborated.
28563 As a result, the static model may seem overly conservative, partly because it
28564 does not take control and data flow into account.
28566 When faced with a task elaboration circularity, a programmer has several
28567 options available:
28570 @itemize *
28572 @item 
28573 @emph{Use the dynamic model}
28575 The dynamic model does not generate implicit @code{Elaborate} and
28576 @code{Elaborate_All} pragmas. Instead, it will install checks prior to every
28577 call in the example above, thus verifying the successful elaboration of
28578 @code{Utils.Put_Val} in case the call to it takes place at elaboration time.
28579 The dynamic model is enabled with compiler switch @code{-gnatE}.
28581 @item 
28582 @emph{Isolate the tasks}
28584 Relocating tasks in their own separate package could decouple them from
28585 dependencies that would otherwise cause an elaboration circularity. The
28586 example above can be rewritten as follows:
28588 @example
28589 package Decls1 is                --  new
28590    task Lib_Task is
28591       entry Start;
28592    end Lib_Task;
28593 end Decls1;
28594 @end example
28596 @example
28597 with Utils;
28598 package body Decls1 is           --  new
28599    task body Lib_Task is
28600    begin
28601       accept Start;
28602       Utils.Put_Val (2);
28603    end Lib_Task;
28604 end Decls1;
28605 @end example
28607 @example
28608 package Decls2 is                --  new
28609    type My_Int is new Integer;
28610    function Ident (M : My_Int) return My_Int;
28611 end Decls2;
28612 @end example
28614 @example
28615 with Utils;
28616 package body Decls2 is           --  new
28617    function Ident (M : My_Int) return My_Int is
28618    begin
28619       return M;
28620    end Ident;
28621 end Decls2;
28622 @end example
28624 @example
28625 with Decls2;
28626 package Utils is
28627    procedure Put_Val (Arg : Decls2.My_Int);
28628 end Utils;
28629 @end example
28631 @example
28632 with Ada.Text_IO; use Ada.Text_IO;
28633 package body Utils is
28634    procedure Put_Val (Arg : Decls2.My_Int) is
28635    begin
28636       Put_Line (Arg'Img);
28637    end Put_Val;
28638 end Utils;
28639 @end example
28641 @example
28642 with Decls1;
28643 procedure Main is
28644 begin
28645    Decls1.Lib_Task.Start;
28646 end Main;
28647 @end example
28649 @item 
28650 @emph{Declare the tasks}
28652 The original example uses a single task declaration for @code{Lib_Task}. An
28653 explicit task type declaration and a properly placed task object could avoid
28654 the dependencies that would otherwise cause an elaboration circularity. The
28655 example can be rewritten as follows:
28657 @example
28658 package Decls is
28659    task type Lib_Task is         --  new
28660       entry Start;
28661    end Lib_Task;
28663    type My_Int is new Integer;
28665    function Ident (M : My_Int) return My_Int;
28666 end Decls;
28667 @end example
28669 @example
28670 with Utils;
28671 package body Decls is
28672    task body Lib_Task is
28673    begin
28674       accept Start;
28675       Utils.Put_Val (2);
28676    end Lib_Task;
28678    function Ident (M : My_Int) return My_Int is
28679    begin
28680       return M;
28681    end Ident;
28682 end Decls;
28683 @end example
28685 @example
28686 with Decls;
28687 package Utils is
28688    procedure Put_Val (Arg : Decls.My_Int);
28689 end Utils;
28690 @end example
28692 @example
28693 with Ada.Text_IO; use Ada.Text_IO;
28694 package body Utils is
28695    procedure Put_Val (Arg : Decls.My_Int) is
28696    begin
28697       Put_Line (Arg'Img);
28698    end Put_Val;
28699 end Utils;
28700 @end example
28702 @example
28703 with Decls;
28704 package Obj_Decls is             --  new
28705    Task_Obj : Decls.Lib_Task;
28706 end Obj_Decls;
28707 @end example
28709 @example
28710 with Obj_Decls;
28711 procedure Main is
28712 begin
28713    Obj_Decls.Task_Obj.Start;     --  new
28714 end Main;
28715 @end example
28717 @item 
28718 @emph{Use restriction No_Entry_Calls_In_Elaboration_Code}
28720 The issue exhibited in the original example under this section revolves
28721 around the body of @code{Lib_Task} blocking on an accept statement. There is
28722 no rule to prevent elaboration code from performing entry calls, however in
28723 practice this is highly unusual. In addition, the pattern of starting tasks
28724 at elaboration time and then immediately blocking on accept or select
28725 statements is quite common.
28727 If a programmer knows that elaboration code will not perform any entry
28728 calls, then the programmer can indicate that the static model should not
28729 process the remainder of a task body once an accept or select statement has
28730 been encountered. This behavior can be specified by a configuration pragma:
28732 @example
28733 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28734 @end example
28736 In addition to the change in behavior with respect to task bodies, the
28737 static model will verify that no entry calls take place at elaboration time.
28738 @end itemize
28740 @node Elaboration-related Compiler Switches,Summary of Procedures for Elaboration Control,Resolving Task Issues,Elaboration Order Handling in GNAT
28741 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-related-compiler-switches}@anchor{24d}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id15}@anchor{24e}
28742 @section Elaboration-related Compiler Switches
28745 GNAT has several switches that affect the elaboration model and consequently
28746 the elaboration order chosen by the binder.
28748 @geindex -gnatE (gnat)
28751 @table @asis
28753 @item @code{-gnatE}
28755 Dynamic elaboration checking mode enabled
28757 When this switch is in effect, GNAT activates the dynamic elaboration model.
28758 @end table
28760 @geindex -gnatel (gnat)
28763 @table @asis
28765 @item @code{-gnatel}
28767 Turn on info messages on generated Elaborate[_All] pragmas
28769 When this switch is in effect, GNAT will emit the following supplementary
28770 information depending on the elaboration model in effect.
28773 @itemize -
28775 @item 
28776 @emph{Dynamic model}
28778 GNAT will indicate missing @code{Elaborate} and @code{Elaborate_All} pragmas for
28779 all library-level scenarios within the partition.
28781 @item 
28782 @emph{Static model}
28784 GNAT will indicate all scenarios executed during elaboration. In addition,
28785 it will provide detailed traceback when an implicit @code{Elaborate} or
28786 @code{Elaborate_All} pragma is generated.
28788 @item 
28789 @emph{SPARK model}
28791 GNAT will indicate how an elaboration requirement is met by the context of
28792 a unit. This diagnostic requires compiler switch @code{-gnatd.v}.
28794 @example
28795 1. with Server; pragma Elaborate_All (Server);
28796 2. package Client with SPARK_Mode is
28797 3.    Val : constant Integer := Server.Func;
28798                                       |
28799    >>> info: call to "Func" during elaboration in SPARK
28800    >>> info: "Elaborate_All" requirement for unit "Server" met by pragma at line 1
28802 4. end Client;
28803 @end example
28804 @end itemize
28805 @end table
28807 @geindex -gnatH (gnat)
28810 @table @asis
28812 @item @code{-gnatH}
28814 Legacy elaboration checking mode enabled
28816 When this switch is in effect, GNAT will utilize the pre-18.x elaboration
28817 model.
28818 @end table
28820 @geindex -gnatJ (gnat)
28823 @table @asis
28825 @item @code{-gnatJ}
28827 Relaxed elaboration checking mode enabled
28829 When this switch is in effect, GNAT will not process certain scenarios,
28830 resulting in a more permissive elaboration model. Note that this may
28831 eliminate some diagnostics and run-time checks.
28832 @end table
28834 @geindex -gnatw.f (gnat)
28837 @table @asis
28839 @item @code{-gnatw.f}
28841 Turn on warnings for suspicious Subp'Access
28843 When this switch is in effect, GNAT will treat @code{'Access} of an entry,
28844 operator, or subprogram as a potential call to the target and issue warnings:
28846 @example
28847  1. package body Attribute_Call is
28848  2.    function Func return Integer;
28849  3.    type Func_Ptr is access function return Integer;
28850  4.
28851  5.    Ptr : constant Func_Ptr := Func'Access;
28852                                       |
28853     >>> warning: "Access" attribute of "Func" before body seen
28854     >>> warning: possible Program_Error on later references
28855     >>> warning:   body of unit "Attribute_Call" elaborated
28856     >>> warning:   "Access" of "Func" taken at line 5
28858  6.
28859  7.    function Func return Integer is
28860  8.    begin
28861  9.       ...
28862 10.    end Func;
28863 11. end Attribute_Call;
28864 @end example
28866 In the example above, the elaboration of declaration @code{Ptr} is assigned
28867 @code{Func'Access} before the body of @code{Func} has been elaborated.
28868 @end table
28870 @geindex -gnatwl (gnat)
28873 @table @asis
28875 @item @code{-gnatwl}
28877 Turn on warnings for elaboration problems
28879 When this switch is in effect, GNAT emits diagnostics in the form of warnings
28880 concerning various elaboration problems. The warnings are enabled by default.
28881 The switch is provided in case all warnings are suppressed, but elaboration
28882 warnings are still desired.
28884 @item @code{-gnatwL}
28886 Turn off warnings for elaboration problems
28888 When this switch is in effect, GNAT no longer emits any diagnostics in the
28889 form of warnings. Selective suppression of elaboration problems is possible
28890 using @code{pragma Warnings (Off)}.
28892 @example
28893  1. package body Selective_Suppression is
28894  2.    function ABE return Integer;
28895  3.
28896  4.    Val_1 : constant Integer := ABE;
28897                                    |
28898     >>> warning: cannot call "ABE" before body seen
28899     >>> warning: Program_Error will be raised at run time
28901  5.
28902  6.    pragma Warnings (Off);
28903  7.    Val_2 : constant Integer := ABE;
28904  8.    pragma Warnings (On);
28905  9.
28906 10.    function ABE return Integer is
28907 11.    begin
28908 12.       ...
28909 13.    end ABE;
28910 14. end Selective_Suppression;
28911 @end example
28913 Note that suppressing elaboration warnings does not eliminate run-time
28914 checks. The example above will still fail at run time with an ABE.
28915 @end table
28917 @node Summary of Procedures for Elaboration Control,Inspecting the Chosen Elaboration Order,Elaboration-related Compiler Switches,Elaboration Order Handling in GNAT
28918 @anchor{gnat_ugn/elaboration_order_handling_in_gnat summary-of-procedures-for-elaboration-control}@anchor{24f}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id16}@anchor{250}
28919 @section Summary of Procedures for Elaboration Control
28922 A programmer should first compile the program with the default options, using
28923 none of the binder or compiler switches. If the binder succeeds in finding an
28924 elaboration order, then apart from possible cases involing dispatching calls
28925 and access-to-subprogram types, the program is free of elaboration errors.
28927 If it is important for the program to be portable to compilers other than GNAT,
28928 then the programmer should use compiler switch @code{-gnatel} and consider
28929 the messages about missing or implicitly created @code{Elaborate} and
28930 @code{Elaborate_All} pragmas.
28932 If the binder reports an elaboration circularity, the programmer has several
28933 options:
28936 @itemize *
28938 @item 
28939 Ensure that elaboration warnings are enabled. This will allow the static
28940 model to output trace information of elaboration issues. The trace
28941 information could shed light on previously unforeseen dependencies, as well
28942 as their origins. Elaboration warnings are enabled with compiler switch
28943 @code{-gnatwl}.
28945 @item 
28946 Use switch @code{-gnatel} to obtain messages on generated implicit
28947 @code{Elaborate} and @code{Elaborate_All} pragmas. The trace information could
28948 indicate why a server unit must be elaborated prior to a client unit.
28950 @item 
28951 If the warnings produced by the static model indicate that a task is
28952 involved, consider the options in section @ref{24b,,Resolving Task Issues}.
28954 @item 
28955 If none of the steps outlined above resolve the circularity, use a more
28956 permissive elaboration model, in the following order:
28959 @itemize -
28961 @item 
28962 Use the dynamic elaboration model, with compiler switch @code{-gnatE}.
28964 @item 
28965 Use the legacy static elaboration model, with compiler switch
28966 @code{-gnatH}.
28968 @item 
28969 Use the legacy dynamic elaboration model, with compiler switches
28970 @code{-gnatH} @code{-gnatE}.
28972 @item 
28973 Use the relaxed legacy static elaboration model, with compiler switches
28974 @code{-gnatH} @code{-gnatJ}.
28976 @item 
28977 Use the relaxed legacy dynamic elaboration model, with compiler switches
28978 @code{-gnatH} @code{-gnatJ} @code{-gnatE}.
28979 @end itemize
28980 @end itemize
28982 @node Inspecting the Chosen Elaboration Order,,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
28983 @anchor{gnat_ugn/elaboration_order_handling_in_gnat inspecting-the-chosen-elaboration-order}@anchor{251}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id17}@anchor{252}
28984 @section Inspecting the Chosen Elaboration Order
28987 To see the elaboration order chosen by the binder, inspect the contents of file
28988 @cite{b~xxx.adb}. On certain targets, this file appears as @cite{b_xxx.adb}. The
28989 elaboration order appears as a sequence of calls to @code{Elab_Body} and
28990 @code{Elab_Spec}, interspersed with assignments to @cite{Exxx} which indicates that a
28991 particular unit is elaborated. For example:
28993 @example
28994 System.Soft_Links'Elab_Body;
28995 E14 := True;
28996 System.Secondary_Stack'Elab_Body;
28997 E18 := True;
28998 System.Exception_Table'Elab_Body;
28999 E24 := True;
29000 Ada.Io_Exceptions'Elab_Spec;
29001 E67 := True;
29002 Ada.Tags'Elab_Spec;
29003 Ada.Streams'Elab_Spec;
29004 E43 := True;
29005 Interfaces.C'Elab_Spec;
29006 E69 := True;
29007 System.Finalization_Root'Elab_Spec;
29008 E60 := True;
29009 System.Os_Lib'Elab_Body;
29010 E71 := True;
29011 System.Finalization_Implementation'Elab_Spec;
29012 System.Finalization_Implementation'Elab_Body;
29013 E62 := True;
29014 Ada.Finalization'Elab_Spec;
29015 E58 := True;
29016 Ada.Finalization.List_Controller'Elab_Spec;
29017 E76 := True;
29018 System.File_Control_Block'Elab_Spec;
29019 E74 := True;
29020 System.File_Io'Elab_Body;
29021 E56 := True;
29022 Ada.Tags'Elab_Body;
29023 E45 := True;
29024 Ada.Text_Io'Elab_Spec;
29025 Ada.Text_Io'Elab_Body;
29026 E07 := True;
29027 @end example
29029 Note also binder switch @code{-l}, which outputs the chosen elaboration
29030 order and provides a more readable form of the above:
29032 @example
29033 ada (spec)
29034 interfaces (spec)
29035 system (spec)
29036 system.case_util (spec)
29037 system.case_util (body)
29038 system.concat_2 (spec)
29039 system.concat_2 (body)
29040 system.concat_3 (spec)
29041 system.concat_3 (body)
29042 system.htable (spec)
29043 system.parameters (spec)
29044 system.parameters (body)
29045 system.crtl (spec)
29046 interfaces.c_streams (spec)
29047 interfaces.c_streams (body)
29048 system.restrictions (spec)
29049 system.restrictions (body)
29050 system.standard_library (spec)
29051 system.exceptions (spec)
29052 system.exceptions (body)
29053 system.storage_elements (spec)
29054 system.storage_elements (body)
29055 system.secondary_stack (spec)
29056 system.stack_checking (spec)
29057 system.stack_checking (body)
29058 system.string_hash (spec)
29059 system.string_hash (body)
29060 system.htable (body)
29061 system.strings (spec)
29062 system.strings (body)
29063 system.traceback (spec)
29064 system.traceback (body)
29065 system.traceback_entries (spec)
29066 system.traceback_entries (body)
29067 ada.exceptions (spec)
29068 ada.exceptions.last_chance_handler (spec)
29069 system.soft_links (spec)
29070 system.soft_links (body)
29071 ada.exceptions.last_chance_handler (body)
29072 system.secondary_stack (body)
29073 system.exception_table (spec)
29074 system.exception_table (body)
29075 ada.io_exceptions (spec)
29076 ada.tags (spec)
29077 ada.streams (spec)
29078 interfaces.c (spec)
29079 interfaces.c (body)
29080 system.finalization_root (spec)
29081 system.finalization_root (body)
29082 system.memory (spec)
29083 system.memory (body)
29084 system.standard_library (body)
29085 system.os_lib (spec)
29086 system.os_lib (body)
29087 system.unsigned_types (spec)
29088 system.stream_attributes (spec)
29089 system.stream_attributes (body)
29090 system.finalization_implementation (spec)
29091 system.finalization_implementation (body)
29092 ada.finalization (spec)
29093 ada.finalization (body)
29094 ada.finalization.list_controller (spec)
29095 ada.finalization.list_controller (body)
29096 system.file_control_block (spec)
29097 system.file_io (spec)
29098 system.file_io (body)
29099 system.val_uns (spec)
29100 system.val_util (spec)
29101 system.val_util (body)
29102 system.val_uns (body)
29103 system.wch_con (spec)
29104 system.wch_con (body)
29105 system.wch_cnv (spec)
29106 system.wch_jis (spec)
29107 system.wch_jis (body)
29108 system.wch_cnv (body)
29109 system.wch_stw (spec)
29110 system.wch_stw (body)
29111 ada.tags (body)
29112 ada.exceptions (body)
29113 ada.text_io (spec)
29114 ada.text_io (body)
29115 text_io (spec)
29116 gdbstr (body)
29117 @end example
29119 @node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
29120 @anchor{gnat_ugn/inline_assembler inline-assembler}@anchor{10}@anchor{gnat_ugn/inline_assembler doc}@anchor{253}@anchor{gnat_ugn/inline_assembler id1}@anchor{254}
29121 @chapter Inline Assembler
29124 @geindex Inline Assembler
29126 If you need to write low-level software that interacts directly
29127 with the hardware, Ada provides two ways to incorporate assembly
29128 language code into your program.  First, you can import and invoke
29129 external routines written in assembly language, an Ada feature fully
29130 supported by GNAT.  However, for small sections of code it may be simpler
29131 or more efficient to include assembly language statements directly
29132 in your Ada source program, using the facilities of the implementation-defined
29133 package @code{System.Machine_Code}, which incorporates the gcc
29134 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
29135 including the following:
29138 @itemize *
29140 @item 
29141 No need to use non-Ada tools
29143 @item 
29144 Consistent interface over different targets
29146 @item 
29147 Automatic usage of the proper calling conventions
29149 @item 
29150 Access to Ada constants and variables
29152 @item 
29153 Definition of intrinsic routines
29155 @item 
29156 Possibility of inlining a subprogram comprising assembler code
29158 @item 
29159 Code optimizer can take Inline Assembler code into account
29160 @end itemize
29162 This appendix presents a series of examples to show you how to use
29163 the Inline Assembler.  Although it focuses on the Intel x86,
29164 the general approach applies also to other processors.
29165 It is assumed that you are familiar with Ada
29166 and with assembly language programming.
29168 @menu
29169 * Basic Assembler Syntax:: 
29170 * A Simple Example of Inline Assembler:: 
29171 * Output Variables in Inline Assembler:: 
29172 * Input Variables in Inline Assembler:: 
29173 * Inlining Inline Assembler Code:: 
29174 * Other Asm Functionality:: 
29176 @end menu
29178 @node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
29179 @anchor{gnat_ugn/inline_assembler id2}@anchor{255}@anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{256}
29180 @section Basic Assembler Syntax
29183 The assembler used by GNAT and gcc is based not on the Intel assembly
29184 language, but rather on a language that descends from the AT&T Unix
29185 assembler @code{as} (and which is often referred to as 'AT&T syntax').
29186 The following table summarizes the main features of @code{as} syntax
29187 and points out the differences from the Intel conventions.
29188 See the gcc @code{as} and @code{gas} (an @code{as} macro
29189 pre-processor) documentation for further information.
29192 @display
29193 @emph{Register names}@w{ }
29194 @display
29195 gcc / @code{as}: Prefix with '%'; for example @code{%eax}@w{ }
29196 Intel: No extra punctuation; for example @code{eax}@w{ }
29197 @end display
29198 @end display
29203 @display
29204 @emph{Immediate operand}@w{ }
29205 @display
29206 gcc / @code{as}: Prefix with '$'; for example @code{$4}@w{ }
29207 Intel: No extra punctuation; for example @code{4}@w{ }
29208 @end display
29209 @end display
29214 @display
29215 @emph{Address}@w{ }
29216 @display
29217 gcc / @code{as}: Prefix with '$'; for example @code{$loc}@w{ }
29218 Intel: No extra punctuation; for example @code{loc}@w{ }
29219 @end display
29220 @end display
29225 @display
29226 @emph{Memory contents}@w{ }
29227 @display
29228 gcc / @code{as}: No extra punctuation; for example @code{loc}@w{ }
29229 Intel: Square brackets; for example @code{[loc]}@w{ }
29230 @end display
29231 @end display
29236 @display
29237 @emph{Register contents}@w{ }
29238 @display
29239 gcc / @code{as}: Parentheses; for example @code{(%eax)}@w{ }
29240 Intel: Square brackets; for example @code{[eax]}@w{ }
29241 @end display
29242 @end display
29247 @display
29248 @emph{Hexadecimal numbers}@w{ }
29249 @display
29250 gcc / @code{as}: Leading '0x' (C language syntax); for example @code{0xA0}@w{ }
29251 Intel: Trailing 'h'; for example @code{A0h}@w{ }
29252 @end display
29253 @end display
29258 @display
29259 @emph{Operand size}@w{ }
29260 @display
29261 gcc / @code{as}: Explicit in op code; for example @code{movw} to move a 16-bit word@w{ }
29262 Intel: Implicit, deduced by assembler; for example @code{mov}@w{ }
29263 @end display
29264 @end display
29269 @display
29270 @emph{Instruction repetition}@w{ }
29271 @display
29272 gcc / @code{as}: Split into two lines; for example@w{ }
29273 @display
29274 @code{rep}@w{ }
29275 @code{stosl}@w{ }
29276 @end display
29277 Intel: Keep on one line; for example @code{rep stosl}@w{ }
29278 @end display
29279 @end display
29284 @display
29285 @emph{Order of operands}@w{ }
29286 @display
29287 gcc / @code{as}: Source first; for example @code{movw $4, %eax}@w{ }
29288 Intel: Destination first; for example @code{mov eax, 4}@w{ }
29289 @end display
29290 @end display
29294 @node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
29295 @anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{257}@anchor{gnat_ugn/inline_assembler id3}@anchor{258}
29296 @section A Simple Example of Inline Assembler
29299 The following example will generate a single assembly language statement,
29300 @code{nop}, which does nothing.  Despite its lack of run-time effect,
29301 the example will be useful in illustrating the basics of
29302 the Inline Assembler facility.
29304 @quotation
29306 @example
29307 with System.Machine_Code; use System.Machine_Code;
29308 procedure Nothing is
29309 begin
29310    Asm ("nop");
29311 end Nothing;
29312 @end example
29313 @end quotation
29315 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
29316 here it takes one parameter, a @emph{template string} that must be a static
29317 expression and that will form the generated instruction.
29318 @code{Asm} may be regarded as a compile-time procedure that parses
29319 the template string and additional parameters (none here),
29320 from which it generates a sequence of assembly language instructions.
29322 The examples in this chapter will illustrate several of the forms
29323 for invoking @code{Asm}; a complete specification of the syntax
29324 is found in the @code{Machine_Code_Insertions} section of the
29325 @cite{GNAT Reference Manual}.
29327 Under the standard GNAT conventions, the @code{Nothing} procedure
29328 should be in a file named @code{nothing.adb}.
29329 You can build the executable in the usual way:
29331 @quotation
29333 @example
29334 $ gnatmake nothing
29335 @end example
29336 @end quotation
29338 However, the interesting aspect of this example is not its run-time behavior
29339 but rather the generated assembly code.
29340 To see this output, invoke the compiler as follows:
29342 @quotation
29344 @example
29345 $  gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
29346 @end example
29347 @end quotation
29349 where the options are:
29352 @itemize *
29354 @item 
29356 @table @asis
29358 @item @code{-c}
29360 compile only (no bind or link)
29361 @end table
29363 @item 
29365 @table @asis
29367 @item @code{-S}
29369 generate assembler listing
29370 @end table
29372 @item 
29374 @table @asis
29376 @item @code{-fomit-frame-pointer}
29378 do not set up separate stack frames
29379 @end table
29381 @item 
29383 @table @asis
29385 @item @code{-gnatp}
29387 do not add runtime checks
29388 @end table
29389 @end itemize
29391 This gives a human-readable assembler version of the code. The resulting
29392 file will have the same name as the Ada source file, but with a @code{.s}
29393 extension. In our example, the file @code{nothing.s} has the following
29394 contents:
29396 @quotation
29398 @example
29399 .file "nothing.adb"
29400 gcc2_compiled.:
29401 ___gnu_compiled_ada:
29402 .text
29403    .align 4
29404 .globl __ada_nothing
29405 __ada_nothing:
29406 #APP
29407    nop
29408 #NO_APP
29409    jmp L1
29410    .align 2,0x90
29412    ret
29413 @end example
29414 @end quotation
29416 The assembly code you included is clearly indicated by
29417 the compiler, between the @code{#APP} and @code{#NO_APP}
29418 delimiters. The character before the 'APP' and 'NOAPP'
29419 can differ on different targets. For example, GNU/Linux uses '#APP' while
29420 on NT you will see '/APP'.
29422 If you make a mistake in your assembler code (such as using the
29423 wrong size modifier, or using a wrong operand for the instruction) GNAT
29424 will report this error in a temporary file, which will be deleted when
29425 the compilation is finished.  Generating an assembler file will help
29426 in such cases, since you can assemble this file separately using the
29427 @code{as} assembler that comes with gcc.
29429 Assembling the file using the command
29431 @quotation
29433 @example
29434 $ as nothing.s
29435 @end example
29436 @end quotation
29438 will give you error messages whose lines correspond to the assembler
29439 input file, so you can easily find and correct any mistakes you made.
29440 If there are no errors, @code{as} will generate an object file
29441 @code{nothing.out}.
29443 @node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
29444 @anchor{gnat_ugn/inline_assembler id4}@anchor{259}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{25a}
29445 @section Output Variables in Inline Assembler
29448 The examples in this section, showing how to access the processor flags,
29449 illustrate how to specify the destination operands for assembly language
29450 statements.
29452 @quotation
29454 @example
29455 with Interfaces; use Interfaces;
29456 with Ada.Text_IO; use Ada.Text_IO;
29457 with System.Machine_Code; use System.Machine_Code;
29458 procedure Get_Flags is
29459    Flags : Unsigned_32;
29460    use ASCII;
29461 begin
29462    Asm ("pushfl"          & LF & HT & -- push flags on stack
29463         "popl %%eax"      & LF & HT & -- load eax with flags
29464         "movl %%eax, %0",             -- store flags in variable
29465         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29466    Put_Line ("Flags register:" & Flags'Img);
29467 end Get_Flags;
29468 @end example
29469 @end quotation
29471 In order to have a nicely aligned assembly listing, we have separated
29472 multiple assembler statements in the Asm template string with linefeed
29473 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
29474 The resulting section of the assembly output file is:
29476 @quotation
29478 @example
29479 #APP
29480    pushfl
29481    popl %eax
29482    movl %eax, -40(%ebp)
29483 #NO_APP
29484 @end example
29485 @end quotation
29487 It would have been legal to write the Asm invocation as:
29489 @quotation
29491 @example
29492 Asm ("pushfl popl %%eax movl %%eax, %0")
29493 @end example
29494 @end quotation
29496 but in the generated assembler file, this would come out as:
29498 @quotation
29500 @example
29501 #APP
29502    pushfl popl %eax movl %eax, -40(%ebp)
29503 #NO_APP
29504 @end example
29505 @end quotation
29507 which is not so convenient for the human reader.
29509 We use Ada comments
29510 at the end of each line to explain what the assembler instructions
29511 actually do.  This is a useful convention.
29513 When writing Inline Assembler instructions, you need to precede each register
29514 and variable name with a percent sign.  Since the assembler already requires
29515 a percent sign at the beginning of a register name, you need two consecutive
29516 percent signs for such names in the Asm template string, thus @code{%%eax}.
29517 In the generated assembly code, one of the percent signs will be stripped off.
29519 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
29520 variables: operands you later define using @code{Input} or @code{Output}
29521 parameters to @code{Asm}.
29522 An output variable is illustrated in
29523 the third statement in the Asm template string:
29525 @quotation
29527 @example
29528 movl %%eax, %0
29529 @end example
29530 @end quotation
29532 The intent is to store the contents of the eax register in a variable that can
29533 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
29534 necessarily work, since the compiler might optimize by using a register
29535 to hold Flags, and the expansion of the @code{movl} instruction would not be
29536 aware of this optimization.  The solution is not to store the result directly
29537 but rather to advise the compiler to choose the correct operand form;
29538 that is the purpose of the @code{%0} output variable.
29540 Information about the output variable is supplied in the @code{Outputs}
29541 parameter to @code{Asm}:
29543 @quotation
29545 @example
29546 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29547 @end example
29548 @end quotation
29550 The output is defined by the @code{Asm_Output} attribute of the target type;
29551 the general format is
29553 @quotation
29555 @example
29556 Type'Asm_Output (constraint_string, variable_name)
29557 @end example
29558 @end quotation
29560 The constraint string directs the compiler how
29561 to store/access the associated variable.  In the example
29563 @quotation
29565 @example
29566 Unsigned_32'Asm_Output ("=m", Flags);
29567 @end example
29568 @end quotation
29570 the @code{"m"} (memory) constraint tells the compiler that the variable
29571 @code{Flags} should be stored in a memory variable, thus preventing
29572 the optimizer from keeping it in a register.  In contrast,
29574 @quotation
29576 @example
29577 Unsigned_32'Asm_Output ("=r", Flags);
29578 @end example
29579 @end quotation
29581 uses the @code{"r"} (register) constraint, telling the compiler to
29582 store the variable in a register.
29584 If the constraint is preceded by the equal character '=', it tells
29585 the compiler that the variable will be used to store data into it.
29587 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
29588 allowing the optimizer to choose whatever it deems best.
29590 There are a fairly large number of constraints, but the ones that are
29591 most useful (for the Intel x86 processor) are the following:
29593 @quotation
29596 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
29597 @item
29599 @emph{=}
29601 @tab
29603 output constraint
29605 @item
29607 @emph{g}
29609 @tab
29611 global (i.e., can be stored anywhere)
29613 @item
29615 @emph{m}
29617 @tab
29619 in memory
29621 @item
29623 @emph{I}
29625 @tab
29627 a constant
29629 @item
29631 @emph{a}
29633 @tab
29635 use eax
29637 @item
29639 @emph{b}
29641 @tab
29643 use ebx
29645 @item
29647 @emph{c}
29649 @tab
29651 use ecx
29653 @item
29655 @emph{d}
29657 @tab
29659 use edx
29661 @item
29663 @emph{S}
29665 @tab
29667 use esi
29669 @item
29671 @emph{D}
29673 @tab
29675 use edi
29677 @item
29679 @emph{r}
29681 @tab
29683 use one of eax, ebx, ecx or edx
29685 @item
29687 @emph{q}
29689 @tab
29691 use one of eax, ebx, ecx, edx, esi or edi
29693 @end multitable
29695 @end quotation
29697 The full set of constraints is described in the gcc and @code{as}
29698 documentation; note that it is possible to combine certain constraints
29699 in one constraint string.
29701 You specify the association of an output variable with an assembler operand
29702 through the @code{%@emph{n}} notation, where @emph{n} is a non-negative
29703 integer.  Thus in
29705 @quotation
29707 @example
29708 Asm ("pushfl"          & LF & HT & -- push flags on stack
29709      "popl %%eax"      & LF & HT & -- load eax with flags
29710      "movl %%eax, %0",             -- store flags in variable
29711      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29712 @end example
29713 @end quotation
29715 @code{%0} will be replaced in the expanded code by the appropriate operand,
29716 whatever
29717 the compiler decided for the @code{Flags} variable.
29719 In general, you may have any number of output variables:
29722 @itemize *
29724 @item 
29725 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
29727 @item 
29728 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
29729 of @code{Asm_Output} attributes
29730 @end itemize
29732 For example:
29734 @quotation
29736 @example
29737 Asm ("movl %%eax, %0" & LF & HT &
29738      "movl %%ebx, %1" & LF & HT &
29739      "movl %%ecx, %2",
29740      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
29741                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
29742                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
29743 @end example
29744 @end quotation
29746 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
29747 in the Ada program.
29749 As a variation on the @code{Get_Flags} example, we can use the constraints
29750 string to direct the compiler to store the eax register into the @code{Flags}
29751 variable, instead of including the store instruction explicitly in the
29752 @code{Asm} template string:
29754 @quotation
29756 @example
29757 with Interfaces; use Interfaces;
29758 with Ada.Text_IO; use Ada.Text_IO;
29759 with System.Machine_Code; use System.Machine_Code;
29760 procedure Get_Flags_2 is
29761    Flags : Unsigned_32;
29762    use ASCII;
29763 begin
29764    Asm ("pushfl"      & LF & HT & -- push flags on stack
29765         "popl %%eax",             -- save flags in eax
29766         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
29767    Put_Line ("Flags register:" & Flags'Img);
29768 end Get_Flags_2;
29769 @end example
29770 @end quotation
29772 The @code{"a"} constraint tells the compiler that the @code{Flags}
29773 variable will come from the eax register. Here is the resulting code:
29775 @quotation
29777 @example
29778 #APP
29779    pushfl
29780    popl %eax
29781 #NO_APP
29782    movl %eax,-40(%ebp)
29783 @end example
29784 @end quotation
29786 The compiler generated the store of eax into Flags after
29787 expanding the assembler code.
29789 Actually, there was no need to pop the flags into the eax register;
29790 more simply, we could just pop the flags directly into the program variable:
29792 @quotation
29794 @example
29795 with Interfaces; use Interfaces;
29796 with Ada.Text_IO; use Ada.Text_IO;
29797 with System.Machine_Code; use System.Machine_Code;
29798 procedure Get_Flags_3 is
29799    Flags : Unsigned_32;
29800    use ASCII;
29801 begin
29802    Asm ("pushfl"  & LF & HT & -- push flags on stack
29803         "pop %0",             -- save flags in Flags
29804         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29805    Put_Line ("Flags register:" & Flags'Img);
29806 end Get_Flags_3;
29807 @end example
29808 @end quotation
29810 @node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
29811 @anchor{gnat_ugn/inline_assembler id5}@anchor{25b}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{25c}
29812 @section Input Variables in Inline Assembler
29815 The example in this section illustrates how to specify the source operands
29816 for assembly language statements.
29817 The program simply increments its input value by 1:
29819 @quotation
29821 @example
29822 with Interfaces; use Interfaces;
29823 with Ada.Text_IO; use Ada.Text_IO;
29824 with System.Machine_Code; use System.Machine_Code;
29825 procedure Increment is
29827    function Incr (Value : Unsigned_32) return Unsigned_32 is
29828       Result : Unsigned_32;
29829    begin
29830       Asm ("incl %0",
29831            Outputs => Unsigned_32'Asm_Output ("=a", Result),
29832            Inputs  => Unsigned_32'Asm_Input ("a", Value));
29833       return Result;
29834    end Incr;
29836    Value : Unsigned_32;
29838 begin
29839    Value := 5;
29840    Put_Line ("Value before is" & Value'Img);
29841    Value := Incr (Value);
29842   Put_Line ("Value after is" & Value'Img);
29843 end Increment;
29844 @end example
29845 @end quotation
29847 The @code{Outputs} parameter to @code{Asm} specifies
29848 that the result will be in the eax register and that it is to be stored
29849 in the @code{Result} variable.
29851 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
29852 but with an @code{Asm_Input} attribute.
29853 The @code{"="} constraint, indicating an output value, is not present.
29855 You can have multiple input variables, in the same way that you can have more
29856 than one output variable.
29858 The parameter count (%0, %1) etc, still starts at the first output statement,
29859 and continues with the input statements.
29861 Just as the @code{Outputs} parameter causes the register to be stored into the
29862 target variable after execution of the assembler statements, so does the
29863 @code{Inputs} parameter cause its variable to be loaded into the register
29864 before execution of the assembler statements.
29866 Thus the effect of the @code{Asm} invocation is:
29869 @itemize *
29871 @item 
29872 load the 32-bit value of @code{Value} into eax
29874 @item 
29875 execute the @code{incl %eax} instruction
29877 @item 
29878 store the contents of eax into the @code{Result} variable
29879 @end itemize
29881 The resulting assembler file (with @code{-O2} optimization) contains:
29883 @quotation
29885 @example
29886 _increment__incr.1:
29887    subl $4,%esp
29888    movl 8(%esp),%eax
29889 #APP
29890    incl %eax
29891 #NO_APP
29892    movl %eax,%edx
29893    movl %ecx,(%esp)
29894    addl $4,%esp
29895    ret
29896 @end example
29897 @end quotation
29899 @node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
29900 @anchor{gnat_ugn/inline_assembler id6}@anchor{25d}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{25e}
29901 @section Inlining Inline Assembler Code
29904 For a short subprogram such as the @code{Incr} function in the previous
29905 section, the overhead of the call and return (creating / deleting the stack
29906 frame) can be significant, compared to the amount of code in the subprogram
29907 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
29908 which directs the compiler to expand invocations of the subprogram at the
29909 point(s) of call, instead of setting up a stack frame for out-of-line calls.
29910 Here is the resulting program:
29912 @quotation
29914 @example
29915 with Interfaces; use Interfaces;
29916 with Ada.Text_IO; use Ada.Text_IO;
29917 with System.Machine_Code; use System.Machine_Code;
29918 procedure Increment_2 is
29920    function Incr (Value : Unsigned_32) return Unsigned_32 is
29921       Result : Unsigned_32;
29922    begin
29923       Asm ("incl %0",
29924            Outputs => Unsigned_32'Asm_Output ("=a", Result),
29925            Inputs  => Unsigned_32'Asm_Input ("a", Value));
29926       return Result;
29927    end Incr;
29928    pragma Inline (Increment);
29930    Value : Unsigned_32;
29932 begin
29933    Value := 5;
29934    Put_Line ("Value before is" & Value'Img);
29935    Value := Increment (Value);
29936    Put_Line ("Value after is" & Value'Img);
29937 end Increment_2;
29938 @end example
29939 @end quotation
29941 Compile the program with both optimization (@code{-O2}) and inlining
29942 (@code{-gnatn}) enabled.
29944 The @code{Incr} function is still compiled as usual, but at the
29945 point in @code{Increment} where our function used to be called:
29947 @quotation
29949 @example
29950 pushl %edi
29951 call _increment__incr.1
29952 @end example
29953 @end quotation
29955 the code for the function body directly appears:
29957 @quotation
29959 @example
29960 movl %esi,%eax
29961 #APP
29962    incl %eax
29963 #NO_APP
29964    movl %eax,%edx
29965 @end example
29966 @end quotation
29968 thus saving the overhead of stack frame setup and an out-of-line call.
29970 @node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
29971 @anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{25f}@anchor{gnat_ugn/inline_assembler id7}@anchor{260}
29972 @section Other @code{Asm} Functionality
29975 This section describes two important parameters to the @code{Asm}
29976 procedure: @code{Clobber}, which identifies register usage;
29977 and @code{Volatile}, which inhibits unwanted optimizations.
29979 @menu
29980 * The Clobber Parameter:: 
29981 * The Volatile Parameter:: 
29983 @end menu
29985 @node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
29986 @anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{261}@anchor{gnat_ugn/inline_assembler id8}@anchor{262}
29987 @subsection The @code{Clobber} Parameter
29990 One of the dangers of intermixing assembly language and a compiled language
29991 such as Ada is that the compiler needs to be aware of which registers are
29992 being used by the assembly code.  In some cases, such as the earlier examples,
29993 the constraint string is sufficient to indicate register usage (e.g.,
29994 @code{"a"} for
29995 the eax register).  But more generally, the compiler needs an explicit
29996 identification of the registers that are used by the Inline Assembly
29997 statements.
29999 Using a register that the compiler doesn't know about
30000 could be a side effect of an instruction (like @code{mull}
30001 storing its result in both eax and edx).
30002 It can also arise from explicit register usage in your
30003 assembly code; for example:
30005 @quotation
30007 @example
30008 Asm ("movl %0, %%ebx" & LF & HT &
30009      "movl %%ebx, %1",
30010      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30011      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
30012 @end example
30013 @end quotation
30015 where the compiler (since it does not analyze the @code{Asm} template string)
30016 does not know you are using the ebx register.
30018 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
30019 to identify the registers that will be used by your assembly code:
30021 @quotation
30023 @example
30024 Asm ("movl %0, %%ebx" & LF & HT &
30025      "movl %%ebx, %1",
30026      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30027      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30028      Clobber => "ebx");
30029 @end example
30030 @end quotation
30032 The Clobber parameter is a static string expression specifying the
30033 register(s) you are using.  Note that register names are @emph{not} prefixed
30034 by a percent sign. Also, if more than one register is used then their names
30035 are separated by commas; e.g., @code{"eax, ebx"}
30037 The @code{Clobber} parameter has several additional uses:
30040 @itemize *
30042 @item 
30043 Use 'register' name @code{cc} to indicate that flags might have changed
30045 @item 
30046 Use 'register' name @code{memory} if you changed a memory location
30047 @end itemize
30049 @node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
30050 @anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{263}@anchor{gnat_ugn/inline_assembler id9}@anchor{264}
30051 @subsection The @code{Volatile} Parameter
30054 @geindex Volatile parameter
30056 Compiler optimizations in the presence of Inline Assembler may sometimes have
30057 unwanted effects.  For example, when an @code{Asm} invocation with an input
30058 variable is inside a loop, the compiler might move the loading of the input
30059 variable outside the loop, regarding it as a one-time initialization.
30061 If this effect is not desired, you can disable such optimizations by setting
30062 the @code{Volatile} parameter to @code{True}; for example:
30064 @quotation
30066 @example
30067 Asm ("movl %0, %%ebx" & LF & HT &
30068      "movl %%ebx, %1",
30069      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
30070      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
30071      Clobber  => "ebx",
30072      Volatile => True);
30073 @end example
30074 @end quotation
30076 By default, @code{Volatile} is set to @code{False} unless there is no
30077 @code{Outputs} parameter.
30079 Although setting @code{Volatile} to @code{True} prevents unwanted
30080 optimizations, it will also disable other optimizations that might be
30081 important for efficiency. In general, you should set @code{Volatile}
30082 to @code{True} only if the compiler's optimizations have created
30083 problems.
30085 @node GNU Free Documentation License,Index,Inline Assembler,Top
30086 @anchor{share/gnu_free_documentation_license gnu-fdl}@anchor{1}@anchor{share/gnu_free_documentation_license doc}@anchor{265}@anchor{share/gnu_free_documentation_license gnu-free-documentation-license}@anchor{266}
30087 @chapter GNU Free Documentation License
30090 Version 1.3, 3 November 2008
30092 Copyright  2000, 2001, 2002, 2007, 2008  Free Software Foundation, Inc
30093 @indicateurl{http://fsf.org/}
30095 Everyone is permitted to copy and distribute verbatim copies of this
30096 license document, but changing it is not allowed.
30098 @strong{Preamble}
30100 The purpose of this License is to make a manual, textbook, or other
30101 functional and useful document "free" in the sense of freedom: to
30102 assure everyone the effective freedom to copy and redistribute it,
30103 with or without modifying it, either commercially or noncommercially.
30104 Secondarily, this License preserves for the author and publisher a way
30105 to get credit for their work, while not being considered responsible
30106 for modifications made by others.
30108 This License is a kind of "copyleft", which means that derivative
30109 works of the document must themselves be free in the same sense.  It
30110 complements the GNU General Public License, which is a copyleft
30111 license designed for free software.
30113 We have designed this License in order to use it for manuals for free
30114 software, because free software needs free documentation: a free
30115 program should come with manuals providing the same freedoms that the
30116 software does.  But this License is not limited to software manuals;
30117 it can be used for any textual work, regardless of subject matter or
30118 whether it is published as a printed book.  We recommend this License
30119 principally for works whose purpose is instruction or reference.
30121 @strong{1. APPLICABILITY AND DEFINITIONS}
30123 This License applies to any manual or other work, in any medium, that
30124 contains a notice placed by the copyright holder saying it can be
30125 distributed under the terms of this License.  Such a notice grants a
30126 world-wide, royalty-free license, unlimited in duration, to use that
30127 work under the conditions stated herein.  The @strong{Document}, below,
30128 refers to any such manual or work.  Any member of the public is a
30129 licensee, and is addressed as "@strong{you}".  You accept the license if you
30130 copy, modify or distribute the work in a way requiring permission
30131 under copyright law.
30133 A "@strong{Modified Version}" of the Document means any work containing the
30134 Document or a portion of it, either copied verbatim, or with
30135 modifications and/or translated into another language.
30137 A "@strong{Secondary Section}" is a named appendix or a front-matter section of
30138 the Document that deals exclusively with the relationship of the
30139 publishers or authors of the Document to the Document's overall subject
30140 (or to related matters) and contains nothing that could fall directly
30141 within that overall subject.  (Thus, if the Document is in part a
30142 textbook of mathematics, a Secondary Section may not explain any
30143 mathematics.)  The relationship could be a matter of historical
30144 connection with the subject or with related matters, or of legal,
30145 commercial, philosophical, ethical or political position regarding
30146 them.
30148 The "@strong{Invariant Sections}" are certain Secondary Sections whose titles
30149 are designated, as being those of Invariant Sections, in the notice
30150 that says that the Document is released under this License.  If a
30151 section does not fit the above definition of Secondary then it is not
30152 allowed to be designated as Invariant.  The Document may contain zero
30153 Invariant Sections.  If the Document does not identify any Invariant
30154 Sections then there are none.
30156 The "@strong{Cover Texts}" are certain short passages of text that are listed,
30157 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
30158 the Document is released under this License.  A Front-Cover Text may
30159 be at most 5 words, and a Back-Cover Text may be at most 25 words.
30161 A "@strong{Transparent}" copy of the Document means a machine-readable copy,
30162 represented in a format whose specification is available to the
30163 general public, that is suitable for revising the document
30164 straightforwardly with generic text editors or (for images composed of
30165 pixels) generic paint programs or (for drawings) some widely available
30166 drawing editor, and that is suitable for input to text formatters or
30167 for automatic translation to a variety of formats suitable for input
30168 to text formatters.  A copy made in an otherwise Transparent file
30169 format whose markup, or absence of markup, has been arranged to thwart
30170 or discourage subsequent modification by readers is not Transparent.
30171 An image format is not Transparent if used for any substantial amount
30172 of text.  A copy that is not "Transparent" is called @strong{Opaque}.
30174 Examples of suitable formats for Transparent copies include plain
30175 ASCII without markup, Texinfo input format, LaTeX input format, SGML
30176 or XML using a publicly available DTD, and standard-conforming simple
30177 HTML, PostScript or PDF designed for human modification.  Examples of
30178 transparent image formats include PNG, XCF and JPG.  Opaque formats
30179 include proprietary formats that can be read and edited only by
30180 proprietary word processors, SGML or XML for which the DTD and/or
30181 processing tools are not generally available, and the
30182 machine-generated HTML, PostScript or PDF produced by some word
30183 processors for output purposes only.
30185 The "@strong{Title Page}" means, for a printed book, the title page itself,
30186 plus such following pages as are needed to hold, legibly, the material
30187 this License requires to appear in the title page.  For works in
30188 formats which do not have any title page as such, "Title Page" means
30189 the text near the most prominent appearance of the work's title,
30190 preceding the beginning of the body of the text.
30192 The "@strong{publisher}" means any person or entity that distributes
30193 copies of the Document to the public.
30195 A section "@strong{Entitled XYZ}" means a named subunit of the Document whose
30196 title either is precisely XYZ or contains XYZ in parentheses following
30197 text that translates XYZ in another language.  (Here XYZ stands for a
30198 specific section name mentioned below, such as "@strong{Acknowledgements}",
30199 "@strong{Dedications}", "@strong{Endorsements}", or "@strong{History}".)
30200 To "@strong{Preserve the Title}"
30201 of such a section when you modify the Document means that it remains a
30202 section "Entitled XYZ" according to this definition.
30204 The Document may include Warranty Disclaimers next to the notice which
30205 states that this License applies to the Document.  These Warranty
30206 Disclaimers are considered to be included by reference in this
30207 License, but only as regards disclaiming warranties: any other
30208 implication that these Warranty Disclaimers may have is void and has
30209 no effect on the meaning of this License.
30211 @strong{2. VERBATIM COPYING}
30213 You may copy and distribute the Document in any medium, either
30214 commercially or noncommercially, provided that this License, the
30215 copyright notices, and the license notice saying this License applies
30216 to the Document are reproduced in all copies, and that you add no other
30217 conditions whatsoever to those of this License.  You may not use
30218 technical measures to obstruct or control the reading or further
30219 copying of the copies you make or distribute.  However, you may accept
30220 compensation in exchange for copies.  If you distribute a large enough
30221 number of copies you must also follow the conditions in section 3.
30223 You may also lend copies, under the same conditions stated above, and
30224 you may publicly display copies.
30226 @strong{3. COPYING IN QUANTITY}
30228 If you publish printed copies (or copies in media that commonly have
30229 printed covers) of the Document, numbering more than 100, and the
30230 Document's license notice requires Cover Texts, you must enclose the
30231 copies in covers that carry, clearly and legibly, all these Cover
30232 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
30233 the back cover.  Both covers must also clearly and legibly identify
30234 you as the publisher of these copies.  The front cover must present
30235 the full title with all words of the title equally prominent and
30236 visible.  You may add other material on the covers in addition.
30237 Copying with changes limited to the covers, as long as they preserve
30238 the title of the Document and satisfy these conditions, can be treated
30239 as verbatim copying in other respects.
30241 If the required texts for either cover are too voluminous to fit
30242 legibly, you should put the first ones listed (as many as fit
30243 reasonably) on the actual cover, and continue the rest onto adjacent
30244 pages.
30246 If you publish or distribute Opaque copies of the Document numbering
30247 more than 100, you must either include a machine-readable Transparent
30248 copy along with each Opaque copy, or state in or with each Opaque copy
30249 a computer-network location from which the general network-using
30250 public has access to download using public-standard network protocols
30251 a complete Transparent copy of the Document, free of added material.
30252 If you use the latter option, you must take reasonably prudent steps,
30253 when you begin distribution of Opaque copies in quantity, to ensure
30254 that this Transparent copy will remain thus accessible at the stated
30255 location until at least one year after the last time you distribute an
30256 Opaque copy (directly or through your agents or retailers) of that
30257 edition to the public.
30259 It is requested, but not required, that you contact the authors of the
30260 Document well before redistributing any large number of copies, to give
30261 them a chance to provide you with an updated version of the Document.
30263 @strong{4. MODIFICATIONS}
30265 You may copy and distribute a Modified Version of the Document under
30266 the conditions of sections 2 and 3 above, provided that you release
30267 the Modified Version under precisely this License, with the Modified
30268 Version filling the role of the Document, thus licensing distribution
30269 and modification of the Modified Version to whoever possesses a copy
30270 of it.  In addition, you must do these things in the Modified Version:
30273 @enumerate A
30275 @item 
30276 Use in the Title Page (and on the covers, if any) a title distinct
30277 from that of the Document, and from those of previous versions
30278 (which should, if there were any, be listed in the History section
30279 of the Document).  You may use the same title as a previous version
30280 if the original publisher of that version gives permission.
30282 @item 
30283 List on the Title Page, as authors, one or more persons or entities
30284 responsible for authorship of the modifications in the Modified
30285 Version, together with at least five of the principal authors of the
30286 Document (all of its principal authors, if it has fewer than five),
30287 unless they release you from this requirement.
30289 @item 
30290 State on the Title page the name of the publisher of the
30291 Modified Version, as the publisher.
30293 @item 
30294 Preserve all the copyright notices of the Document.
30296 @item 
30297 Add an appropriate copyright notice for your modifications
30298 adjacent to the other copyright notices.
30300 @item 
30301 Include, immediately after the copyright notices, a license notice
30302 giving the public permission to use the Modified Version under the
30303 terms of this License, in the form shown in the Addendum below.
30305 @item 
30306 Preserve in that license notice the full lists of Invariant Sections
30307 and required Cover Texts given in the Document's license notice.
30309 @item 
30310 Include an unaltered copy of this License.
30312 @item 
30313 Preserve the section Entitled "History", Preserve its Title, and add
30314 to it an item stating at least the title, year, new authors, and
30315 publisher of the Modified Version as given on the Title Page.  If
30316 there is no section Entitled "History" in the Document, create one
30317 stating the title, year, authors, and publisher of the Document as
30318 given on its Title Page, then add an item describing the Modified
30319 Version as stated in the previous sentence.
30321 @item 
30322 Preserve the network location, if any, given in the Document for
30323 public access to a Transparent copy of the Document, and likewise
30324 the network locations given in the Document for previous versions
30325 it was based on.  These may be placed in the "History" section.
30326 You may omit a network location for a work that was published at
30327 least four years before the Document itself, or if the original
30328 publisher of the version it refers to gives permission.
30330 @item 
30331 For any section Entitled "Acknowledgements" or "Dedications",
30332 Preserve the Title of the section, and preserve in the section all
30333 the substance and tone of each of the contributor acknowledgements
30334 and/or dedications given therein.
30336 @item 
30337 Preserve all the Invariant Sections of the Document,
30338 unaltered in their text and in their titles.  Section numbers
30339 or the equivalent are not considered part of the section titles.
30341 @item 
30342 Delete any section Entitled "Endorsements".  Such a section
30343 may not be included in the Modified Version.
30345 @item 
30346 Do not retitle any existing section to be Entitled "Endorsements"
30347 or to conflict in title with any Invariant Section.
30349 @item 
30350 Preserve any Warranty Disclaimers.
30351 @end enumerate
30353 If the Modified Version includes new front-matter sections or
30354 appendices that qualify as Secondary Sections and contain no material
30355 copied from the Document, you may at your option designate some or all
30356 of these sections as invariant.  To do this, add their titles to the
30357 list of Invariant Sections in the Modified Version's license notice.
30358 These titles must be distinct from any other section titles.
30360 You may add a section Entitled "Endorsements", provided it contains
30361 nothing but endorsements of your Modified Version by various
30362 parties---for example, statements of peer review or that the text has
30363 been approved by an organization as the authoritative definition of a
30364 standard.
30366 You may add a passage of up to five words as a Front-Cover Text, and a
30367 passage of up to 25 words as a Back-Cover Text, to the end of the list
30368 of Cover Texts in the Modified Version.  Only one passage of
30369 Front-Cover Text and one of Back-Cover Text may be added by (or
30370 through arrangements made by) any one entity.  If the Document already
30371 includes a cover text for the same cover, previously added by you or
30372 by arrangement made by the same entity you are acting on behalf of,
30373 you may not add another; but you may replace the old one, on explicit
30374 permission from the previous publisher that added the old one.
30376 The author(s) and publisher(s) of the Document do not by this License
30377 give permission to use their names for publicity for or to assert or
30378 imply endorsement of any Modified Version.
30380 @strong{5. COMBINING DOCUMENTS}
30382 You may combine the Document with other documents released under this
30383 License, under the terms defined in section 4 above for modified
30384 versions, provided that you include in the combination all of the
30385 Invariant Sections of all of the original documents, unmodified, and
30386 list them all as Invariant Sections of your combined work in its
30387 license notice, and that you preserve all their Warranty Disclaimers.
30389 The combined work need only contain one copy of this License, and
30390 multiple identical Invariant Sections may be replaced with a single
30391 copy.  If there are multiple Invariant Sections with the same name but
30392 different contents, make the title of each such section unique by
30393 adding at the end of it, in parentheses, the name of the original
30394 author or publisher of that section if known, or else a unique number.
30395 Make the same adjustment to the section titles in the list of
30396 Invariant Sections in the license notice of the combined work.
30398 In the combination, you must combine any sections Entitled "History"
30399 in the various original documents, forming one section Entitled
30400 "History"; likewise combine any sections Entitled "Acknowledgements",
30401 and any sections Entitled "Dedications".  You must delete all sections
30402 Entitled "Endorsements".
30404 @strong{6. COLLECTIONS OF DOCUMENTS}
30406 You may make a collection consisting of the Document and other documents
30407 released under this License, and replace the individual copies of this
30408 License in the various documents with a single copy that is included in
30409 the collection, provided that you follow the rules of this License for
30410 verbatim copying of each of the documents in all other respects.
30412 You may extract a single document from such a collection, and distribute
30413 it individually under this License, provided you insert a copy of this
30414 License into the extracted document, and follow this License in all
30415 other respects regarding verbatim copying of that document.
30417 @strong{7. AGGREGATION WITH INDEPENDENT WORKS}
30419 A compilation of the Document or its derivatives with other separate
30420 and independent documents or works, in or on a volume of a storage or
30421 distribution medium, is called an "aggregate" if the copyright
30422 resulting from the compilation is not used to limit the legal rights
30423 of the compilation's users beyond what the individual works permit.
30424 When the Document is included in an aggregate, this License does not
30425 apply to the other works in the aggregate which are not themselves
30426 derivative works of the Document.
30428 If the Cover Text requirement of section 3 is applicable to these
30429 copies of the Document, then if the Document is less than one half of
30430 the entire aggregate, the Document's Cover Texts may be placed on
30431 covers that bracket the Document within the aggregate, or the
30432 electronic equivalent of covers if the Document is in electronic form.
30433 Otherwise they must appear on printed covers that bracket the whole
30434 aggregate.
30436 @strong{8. TRANSLATION}
30438 Translation is considered a kind of modification, so you may
30439 distribute translations of the Document under the terms of section 4.
30440 Replacing Invariant Sections with translations requires special
30441 permission from their copyright holders, but you may include
30442 translations of some or all Invariant Sections in addition to the
30443 original versions of these Invariant Sections.  You may include a
30444 translation of this License, and all the license notices in the
30445 Document, and any Warranty Disclaimers, provided that you also include
30446 the original English version of this License and the original versions
30447 of those notices and disclaimers.  In case of a disagreement between
30448 the translation and the original version of this License or a notice
30449 or disclaimer, the original version will prevail.
30451 If a section in the Document is Entitled "Acknowledgements",
30452 "Dedications", or "History", the requirement (section 4) to Preserve
30453 its Title (section 1) will typically require changing the actual
30454 title.
30456 @strong{9. TERMINATION}
30458 You may not copy, modify, sublicense, or distribute the Document
30459 except as expressly provided under this License.  Any attempt
30460 otherwise to copy, modify, sublicense, or distribute it is void, and
30461 will automatically terminate your rights under this License.
30463 However, if you cease all violation of this License, then your license
30464 from a particular copyright holder is reinstated (a) provisionally,
30465 unless and until the copyright holder explicitly and finally
30466 terminates your license, and (b) permanently, if the copyright holder
30467 fails to notify you of the violation by some reasonable means prior to
30468 60 days after the cessation.
30470 Moreover, your license from a particular copyright holder is
30471 reinstated permanently if the copyright holder notifies you of the
30472 violation by some reasonable means, this is the first time you have
30473 received notice of violation of this License (for any work) from that
30474 copyright holder, and you cure the violation prior to 30 days after
30475 your receipt of the notice.
30477 Termination of your rights under this section does not terminate the
30478 licenses of parties who have received copies or rights from you under
30479 this License.  If your rights have been terminated and not permanently
30480 reinstated, receipt of a copy of some or all of the same material does
30481 not give you any rights to use it.
30483 @strong{10. FUTURE REVISIONS OF THIS LICENSE}
30485 The Free Software Foundation may publish new, revised versions
30486 of the GNU Free Documentation License from time to time.  Such new
30487 versions will be similar in spirit to the present version, but may
30488 differ in detail to address new problems or concerns.  See
30489 @indicateurl{http://www.gnu.org/copyleft/}.
30491 Each version of the License is given a distinguishing version number.
30492 If the Document specifies that a particular numbered version of this
30493 License "or any later version" applies to it, you have the option of
30494 following the terms and conditions either of that specified version or
30495 of any later version that has been published (not as a draft) by the
30496 Free Software Foundation.  If the Document does not specify a version
30497 number of this License, you may choose any version ever published (not
30498 as a draft) by the Free Software Foundation.  If the Document
30499 specifies that a proxy can decide which future versions of this
30500 License can be used, that proxy's public statement of acceptance of a
30501 version permanently authorizes you to choose that version for the
30502 Document.
30504 @strong{11. RELICENSING}
30506 "Massive Multiauthor Collaboration Site" (or "MMC Site") means any
30507 World Wide Web server that publishes copyrightable works and also
30508 provides prominent facilities for anybody to edit those works.  A
30509 public wiki that anybody can edit is an example of such a server.  A
30510 "Massive Multiauthor Collaboration" (or "MMC") contained in the
30511 site means any set of copyrightable works thus published on the MMC
30512 site.
30514 "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0
30515 license published by Creative Commons Corporation, a not-for-profit
30516 corporation with a principal place of business in San Francisco,
30517 California, as well as future copyleft versions of that license
30518 published by that same organization.
30520 "Incorporate" means to publish or republish a Document, in whole or
30521 in part, as part of another Document.
30523 An MMC is "eligible for relicensing" if it is licensed under this
30524 License, and if all works that were first published under this License
30525 somewhere other than this MMC, and subsequently incorporated in whole
30526 or in part into the MMC, (1) had no cover texts or invariant sections,
30527 and (2) were thus incorporated prior to November 1, 2008.
30529 The operator of an MMC Site may republish an MMC contained in the site
30530 under CC-BY-SA on the same site at any time before August 1, 2009,
30531 provided the MMC is eligible for relicensing.
30533 @strong{ADDENDUM: How to use this License for your documents}
30535 To use this License in a document you have written, include a copy of
30536 the License in the document and put the following copyright and
30537 license notices just after the title page:
30539 @quotation
30541 Copyright © YEAR  YOUR NAME.
30542 Permission is granted to copy, distribute and/or modify this document
30543 under the terms of the GNU Free Documentation License, Version 1.3
30544 or any later version published by the Free Software Foundation;
30545 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
30546 A copy of the license is included in the section entitled "GNU
30547 Free Documentation License".
30548 @end quotation
30550 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
30551 replace the "with ... Texts." line with this:
30553 @quotation
30555 with the Invariant Sections being LIST THEIR TITLES, with the
30556 Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
30557 @end quotation
30559 If you have Invariant Sections without Cover Texts, or some other
30560 combination of the three, merge those two alternatives to suit the
30561 situation.
30563 If your document contains nontrivial examples of program code, we
30564 recommend releasing these examples in parallel under your choice of
30565 free software license, such as the GNU General Public License,
30566 to permit their use in free software.
30568 @node Index,,GNU Free Documentation License,Top
30569 @unnumbered Index
30572 @printindex ge
30574 @anchor{de}@w{                              }
30575 @anchor{gnat_ugn/gnat_utility_programs switches-related-to-project-files}@w{                              }
30577 @c %**end of body
30578 @bye