Simplify X / X, 0 / X and X % X
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blobdc9c1418953d5f1bef998083ddaa1a780594ba87
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.3b2.@*
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 , July 04, 2016
26 AdaCore
28 Copyright @copyright{} 2008-2016, 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 * Binding with gnatbind:: 
241 * Linking with gnatlink:: 
242 * Using the GNU make Utility:: 
244 Building with gnatmake
246 * Running gnatmake:: 
247 * Switches for gnatmake:: 
248 * Mode Switches for gnatmake:: 
249 * Notes on the Command Line:: 
250 * How gnatmake Works:: 
251 * Examples of gnatmake Usage:: 
253 Compiling with gcc
255 * Compiling Programs:: 
256 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
257 * Order of Compilation Issues:: 
258 * Examples:: 
260 Compiler Switches
262 * Alphabetical List of All Switches:: 
263 * Output and Error Message Control:: 
264 * Warning Message Control:: 
265 * Debugging and Assertion Control:: 
266 * Validity Checking:: 
267 * Style Checking:: 
268 * Run-Time Checks:: 
269 * Using gcc for Syntax Checking:: 
270 * Using gcc for Semantic Checking:: 
271 * Compiling Different Versions of Ada:: 
272 * Character Set Control:: 
273 * File Naming Control:: 
274 * Subprogram Inlining Control:: 
275 * Auxiliary Output Control:: 
276 * Debugging Control:: 
277 * Exception Handling Control:: 
278 * Units to Sources Mapping Files:: 
279 * Code Generation Control:: 
281 Binding with gnatbind
283 * Running gnatbind:: 
284 * Switches for gnatbind:: 
285 * Command-Line Access:: 
286 * Search Paths for gnatbind:: 
287 * Examples of gnatbind Usage:: 
289 Switches for gnatbind
291 * Consistency-Checking Modes:: 
292 * Binder Error Message Control:: 
293 * Elaboration Control:: 
294 * Output Control:: 
295 * Dynamic Allocation Control:: 
296 * Binding with Non-Ada Main Programs:: 
297 * Binding Programs with No Main Subprogram:: 
299 Linking with gnatlink
301 * Running gnatlink:: 
302 * Switches for gnatlink:: 
304 Using the GNU make Utility
306 * Using gnatmake in a Makefile:: 
307 * Automatically Creating a List of Directories:: 
308 * Generating the Command Line Switches:: 
309 * Overcoming Command Line Length Limits:: 
311 GNAT Utility Programs
313 * The File Cleanup Utility gnatclean:: 
314 * The GNAT Library Browser gnatls:: 
315 * The Cross-Referencing Tools gnatxref and gnatfind:: 
316 * The Ada to HTML Converter gnathtml:: 
318 The File Cleanup Utility gnatclean
320 * Running gnatclean:: 
321 * Switches for gnatclean:: 
323 The GNAT Library Browser gnatls
325 * Running gnatls:: 
326 * Switches for gnatls:: 
327 * Example of gnatls Usage:: 
329 The Cross-Referencing Tools gnatxref and gnatfind
331 * gnatxref Switches:: 
332 * gnatfind Switches:: 
333 * Project Files for gnatxref and gnatfind:: 
334 * Regular Expressions in gnatfind and gnatxref:: 
335 * Examples of gnatxref Usage:: 
336 * Examples of gnatfind Usage:: 
338 Examples of gnatxref Usage
340 * General Usage:: 
341 * Using gnatxref with vi:: 
343 The Ada to HTML Converter gnathtml
345 * Invoking gnathtml:: 
346 * Installing gnathtml:: 
348 GNAT and Program Execution
350 * Running and Debugging Ada Programs:: 
351 * Code Coverage and Profiling:: 
352 * Improving Performance:: 
353 * Overflow Check Handling in GNAT:: 
354 * Performing Dimensionality Analysis in GNAT:: 
355 * Stack Related Facilities:: 
356 * Memory Management Issues:: 
358 Running and Debugging Ada Programs
360 * The GNAT Debugger GDB:: 
361 * Running GDB:: 
362 * Introduction to GDB Commands:: 
363 * Using Ada Expressions:: 
364 * Calling User-Defined Subprograms:: 
365 * Using the next Command in a Function:: 
366 * Stopping When Ada Exceptions Are Raised:: 
367 * Ada Tasks:: 
368 * Debugging Generic Units:: 
369 * Remote Debugging with gdbserver:: 
370 * GNAT Abnormal Termination or Failure to Terminate:: 
371 * Naming Conventions for GNAT Source Files:: 
372 * Getting Internal Debugging Information:: 
373 * Stack Traceback:: 
375 Stack Traceback
377 * Non-Symbolic Traceback:: 
378 * Symbolic Traceback:: 
380 Code Coverage and Profiling
382 * Code Coverage of Ada Programs with gcov:: 
383 * Profiling an Ada Program with gprof:: 
385 Code Coverage of Ada Programs with gcov
387 * Quick startup guide:: 
388 * GNAT specifics:: 
390 Profiling an Ada Program with gprof
392 * Compilation for profiling:: 
393 * Program execution:: 
394 * Running gprof:: 
395 * Interpretation of profiling results:: 
397 Improving Performance
399 * Performance Considerations:: 
400 * Text_IO Suggestions:: 
401 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
403 Performance Considerations
405 * Controlling Run-Time Checks:: 
406 * Use of Restrictions:: 
407 * Optimization Levels:: 
408 * Debugging Optimized Code:: 
409 * Inlining of Subprograms:: 
410 * Floating_Point_Operations:: 
411 * Vectorization of loops:: 
412 * Other Optimization Switches:: 
413 * Optimization and Strict Aliasing:: 
414 * Aliased Variables and Optimization:: 
415 * Atomic Variables and Optimization:: 
416 * Passive Task Optimization:: 
418 Reducing Size of Executables with Unused Subprogram/Data Elimination
420 * About unused subprogram/data elimination:: 
421 * Compilation options:: 
422 * Example of unused subprogram/data elimination:: 
424 Overflow Check Handling in GNAT
426 * Background:: 
427 * Management of Overflows in GNAT:: 
428 * Specifying the Desired Mode:: 
429 * Default Settings:: 
430 * Implementation Notes:: 
432 Stack Related Facilities
434 * Stack Overflow Checking:: 
435 * Static Stack Usage Analysis:: 
436 * Dynamic Stack Usage Analysis:: 
438 Memory Management Issues
440 * Some Useful Memory Pools:: 
441 * The GNAT Debug Pool Facility:: 
443 Platform-Specific Information
445 * Run-Time Libraries:: 
446 * Specifying a Run-Time Library:: 
447 * Microsoft Windows Topics:: 
448 * Mac OS Topics:: 
450 Run-Time Libraries
452 * Summary of Run-Time Configurations:: 
454 Specifying a Run-Time Library
456 * Choosing the Scheduling Policy:: 
457 * Solaris-Specific Considerations:: 
458 * Solaris Threads Issues:: 
459 * AIX-Specific Considerations:: 
461 Microsoft Windows Topics
463 * Using GNAT on Windows:: 
464 * Using a network installation of GNAT:: 
465 * CONSOLE and WINDOWS subsystems:: 
466 * Temporary Files:: 
467 * Disabling Command Line Argument Expansion:: 
468 * Mixed-Language Programming on Windows:: 
469 * Windows Specific Add-Ons:: 
471 Mixed-Language Programming on Windows
473 * Windows Calling Conventions:: 
474 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
475 * Using DLLs with GNAT:: 
476 * Building DLLs with GNAT Project files:: 
477 * Building DLLs with GNAT:: 
478 * Building DLLs with gnatdll:: 
479 * Ada DLLs and Finalization:: 
480 * Creating a Spec for Ada DLLs:: 
481 * GNAT and Windows Resources:: 
482 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
483 * Debugging a DLL:: 
484 * Setting Stack Size from gnatlink:: 
485 * Setting Heap Size from gnatlink:: 
487 Windows Calling Conventions
489 * C Calling Convention:: 
490 * Stdcall Calling Convention:: 
491 * Win32 Calling Convention:: 
492 * DLL Calling Convention:: 
494 Using DLLs with GNAT
496 * Creating an Ada Spec for the DLL Services:: 
497 * Creating an Import Library:: 
499 Building DLLs with gnatdll
501 * Limitations When Using Ada DLLs from Ada:: 
502 * Exporting Ada Entities:: 
503 * Ada DLLs and Elaboration:: 
505 Creating a Spec for Ada DLLs
507 * Creating the Definition File:: 
508 * Using gnatdll:: 
510 GNAT and Windows Resources
512 * Building Resources:: 
513 * Compiling Resources:: 
514 * Using Resources:: 
516 Debugging a DLL
518 * Program and DLL Both Built with GCC/GNAT:: 
519 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
521 Windows Specific Add-Ons
523 * Win32Ada:: 
524 * wPOSIX:: 
526 Mac OS Topics
528 * Codesigning the Debugger:: 
530 Elaboration Order Handling in GNAT
532 * Elaboration Code:: 
533 * Checking the Elaboration Order:: 
534 * Controlling the Elaboration Order:: 
535 * Controlling Elaboration in GNAT - Internal Calls:: 
536 * Controlling Elaboration in GNAT - External Calls:: 
537 * Default Behavior in GNAT - Ensuring Safety:: 
538 * Treatment of Pragma Elaborate:: 
539 * Elaboration Issues for Library Tasks:: 
540 * Mixing Elaboration Models:: 
541 * What to Do If the Default Elaboration Behavior Fails:: 
542 * Elaboration for Indirect Calls:: 
543 * Summary of Procedures for Elaboration Control:: 
544 * Other Elaboration Order Considerations:: 
545 * Determining the Chosen Elaboration Order:: 
547 Inline Assembler
549 * Basic Assembler Syntax:: 
550 * A Simple Example of Inline Assembler:: 
551 * Output Variables in Inline Assembler:: 
552 * Input Variables in Inline Assembler:: 
553 * Inlining Inline Assembler Code:: 
554 * Other Asm Functionality:: 
556 Other Asm Functionality
558 * The Clobber Parameter:: 
559 * The Volatile Parameter:: 
561 @end detailmenu
562 @end menu
564 @node About This Guide,Getting Started with GNAT,Top,Top
565 @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}
566 @chapter About This Guide
570 This guide describes the use of GNAT,
571 a compiler and software development
572 toolset for the full Ada programming language.
573 It documents the features of the compiler and tools, and explains
574 how to use them to build Ada applications.
576 GNAT implements Ada 95, Ada 2005 and Ada 2012, and it may also be
577 invoked in Ada 83 compatibility mode.
578 By default, GNAT assumes Ada 2012, but you can override with a
579 compiler switch (@ref{6,,Compiling Different Versions of Ada})
580 to explicitly specify the language version.
581 Throughout this manual, references to 'Ada' without a year suffix
582 apply to all Ada 95/2005/2012 versions of the language.
584 @menu
585 * What This Guide Contains:: 
586 * What You Should Know before Reading This Guide:: 
587 * Related Information:: 
588 * A Note to Readers of Previous Versions of the Manual:: 
589 * Conventions:: 
591 @end menu
593 @node What This Guide Contains,What You Should Know before Reading This Guide,,About This Guide
594 @anchor{gnat_ugn/about_this_guide what-this-guide-contains}@anchor{7}
595 @section What This Guide Contains
598 This guide contains the following chapters:
601 @itemize *
603 @item 
604 @ref{8,,Getting Started with GNAT} describes how to get started compiling
605 and running Ada programs with the GNAT Ada programming environment.
607 @item 
608 @ref{9,,The GNAT Compilation Model} describes the compilation model used
609 by GNAT.
611 @item 
612 @ref{a,,Building Executable Programs with GNAT} describes how to use the
613 main GNAT tools to build executable programs, and it also gives examples of
614 using the GNU make utility with GNAT.
616 @item 
617 @ref{b,,GNAT Utility Programs} explains the various utility programs that
618 are included in the GNAT environment
620 @item 
621 @ref{c,,GNAT and Program Execution} covers a number of topics related to
622 running, debugging, and tuning the performace of programs developed
623 with GNAT
624 @end itemize
626 Appendices cover several additional topics:
629 @itemize *
631 @item 
632 @ref{d,,Platform-Specific Information} describes the different run-time
633 library implementations and also presents information on how to use
634 GNAT on several specific platforms
636 @item 
637 @ref{e,,Example of Binder Output File} shows the source code for the binder
638 output file for a sample program.
640 @item 
641 @ref{f,,Elaboration Order Handling in GNAT} describes how GNAT helps
642 you deal with elaboration order issues.
644 @item 
645 @ref{10,,Inline Assembler} shows how to use the inline assembly facility
646 in an Ada program.
647 @end itemize
649 @node What You Should Know before Reading This Guide,Related Information,What This Guide Contains,About This Guide
650 @anchor{gnat_ugn/about_this_guide what-you-should-know-before-reading-this-guide}@anchor{11}
651 @section What You Should Know before Reading This Guide
654 @geindex Ada 95 Language Reference Manual
656 @geindex Ada 2005 Language Reference Manual
658 This guide assumes a basic familiarity with the Ada 95 language, as
659 described in the International Standard ANSI/ISO/IEC-8652:1995, January
660 1995.
661 It does not require knowledge of the features introduced by Ada 2005
662 or Ada 2012.
663 Reference manuals for Ada 95, Ada 2005, and Ada 2012 are included in
664 the GNAT documentation package.
666 @node Related Information,A Note to Readers of Previous Versions of the Manual,What You Should Know before Reading This Guide,About This Guide
667 @anchor{gnat_ugn/about_this_guide related-information}@anchor{12}
668 @section Related Information
671 For further information about Ada and related tools, please refer to the
672 following documents:
675 @itemize *
677 @item 
678 @cite{Ada 95 Reference Manual}, @cite{Ada 2005 Reference Manual}, and
679 @cite{Ada 2012 Reference Manual}, which contain reference
680 material for the several revisions of the Ada language standard.
682 @item 
683 @cite{GNAT Reference_Manual}, which contains all reference material for the GNAT
684 implementation of Ada.
686 @item 
687 @cite{Using the GNAT Programming Studio}, which describes the GPS
688 Integrated Development Environment.
690 @item 
691 @cite{GNAT Programming Studio Tutorial}, which introduces the
692 main GPS features through examples.
694 @item 
695 @cite{Debugging with GDB},
696 for all details on the use of the GNU source-level debugger.
698 @item 
699 @cite{GNU Emacs Manual},
700 for full information on the extensible editor and programming
701 environment Emacs.
702 @end itemize
704 @node A Note to Readers of Previous Versions of the Manual,Conventions,Related Information,About This Guide
705 @anchor{gnat_ugn/about_this_guide a-note-to-readers-of-previous-versions-of-the-manual}@anchor{13}
706 @section A Note to Readers of Previous Versions of the Manual
709 In early 2015 the GNAT manuals were transitioned to the
710 reStructuredText (rst) / Sphinx documentation generator technology.
711 During that process the @cite{GNAT User's Guide} was reorganized
712 so that related topics would be described together in the same chapter
713 or appendix.  Here's a summary of the major changes realized in
714 the new document structure.
717 @itemize *
719 @item 
720 @ref{9,,The GNAT Compilation Model} has been extended so that it now covers
721 the following material:
724 @itemize -
726 @item 
727 The @cite{gnatname}, @cite{gnatkr}, and @cite{gnatchop} tools
729 @item 
730 @ref{14,,Configuration Pragmas}
732 @item 
733 @ref{15,,GNAT and Libraries}
735 @item 
736 @ref{16,,Conditional Compilation} including @ref{17,,Preprocessing with gnatprep}
737 and @ref{18,,Integrated Preprocessing}
739 @item 
740 @ref{19,,Generating Ada Bindings for C and C++ headers}
742 @item 
743 @ref{1a,,Using GNAT Files with External Tools}
744 @end itemize
746 @item 
747 @ref{a,,Building Executable Programs with GNAT} is a new chapter consolidating
748 the following content:
751 @itemize -
753 @item 
754 @ref{1b,,Building with gnatmake}
756 @item 
757 @ref{1c,,Compiling with gcc}
759 @item 
760 @ref{1d,,Binding with gnatbind}
762 @item 
763 @ref{1e,,Linking with gnatlink}
765 @item 
766 @ref{1f,,Using the GNU make Utility}
767 @end itemize
769 @item 
770 @ref{b,,GNAT Utility Programs} is a new chapter consolidating the information about several
771 GNAT tools:
775 @itemize -
777 @item 
778 @ref{20,,The File Cleanup Utility gnatclean}
780 @item 
781 @ref{21,,The GNAT Library Browser gnatls}
783 @item 
784 @ref{22,,The Cross-Referencing Tools gnatxref and gnatfind}
786 @item 
787 @ref{23,,The Ada to HTML Converter gnathtml}
788 @end itemize
790 @item 
791 @ref{c,,GNAT and Program Execution} is a new chapter consolidating the following:
794 @itemize -
796 @item 
797 @ref{24,,Running and Debugging Ada Programs}
799 @item 
800 @ref{25,,Code Coverage and Profiling}
802 @item 
803 @ref{26,,Improving Performance}
805 @item 
806 @ref{27,,Overflow Check Handling in GNAT}
808 @item 
809 @ref{28,,Performing Dimensionality Analysis in GNAT}
811 @item 
812 @ref{29,,Stack Related Facilities}
814 @item 
815 @ref{2a,,Memory Management Issues}
816 @end itemize
818 @item 
819 @ref{d,,Platform-Specific Information} is a new appendix consolidating the following:
822 @itemize -
824 @item 
825 @ref{2b,,Run-Time Libraries}
827 @item 
828 @ref{2c,,Microsoft Windows Topics}
830 @item 
831 @ref{2d,,Mac OS Topics}
832 @end itemize
834 @item 
835 The @cite{Compatibility and Porting Guide} appendix has been moved to the
836 @cite{GNAT Reference Manual}. It now includes a section
837 @cite{Writing Portable Fixed-Point Declarations} which was previously
838 a separate chapter in the @cite{GNAT User's Guide}.
839 @end itemize
841 @node Conventions,,A Note to Readers of Previous Versions of the Manual,About This Guide
842 @anchor{gnat_ugn/about_this_guide conventions}@anchor{2e}
843 @section Conventions
846 @geindex Conventions
847 @geindex typographical
849 @geindex Typographical conventions
851 Following are examples of the typographical and graphic conventions used
852 in this guide:
855 @itemize *
857 @item 
858 @cite{Functions}, @cite{utility program names}, @cite{standard names},
859 and @cite{classes}.
861 @item 
862 @cite{Option flags}
864 @item 
865 @code{File names}
867 @item 
868 @cite{Variables}
870 @item 
871 @emph{Emphasis}
873 @item 
874 [optional information or parameters]
876 @item 
877 Examples are described by text
879 @example
880 and then shown this way.
881 @end example
883 @item 
884 Commands that are entered by the user are shown as preceded by a prompt string
885 comprising the @code{$} character followed by a space.
887 @item 
888 Full file names are shown with the '/' character
889 as the directory separator; e.g., @code{parent-dir/subdir/myfile.adb}.
890 If you are using GNAT on a Windows platform, please note that
891 the '\' character should be used instead.
892 @end itemize
894 @node Getting Started with GNAT,The GNAT Compilation Model,About This Guide,Top
895 @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}
896 @chapter Getting Started with GNAT
899 This chapter describes how to use GNAT's command line interface to build
900 executable Ada programs.
901 On most platforms a visually oriented Integrated Development Environment
902 is also available, the GNAT Programming Studio (GPS).
903 GPS offers a graphical "look and feel", support for development in
904 other programming languages, comprehensive browsing features, and
905 many other capabilities.
906 For information on GPS please refer to
907 @cite{Using the GNAT Programming Studio}.
909 @menu
910 * Running GNAT:: 
911 * Running a Simple Ada Program:: 
912 * Running a Program with Multiple Units:: 
913 * Using the gnatmake Utility:: 
915 @end menu
917 @node Running GNAT,Running a Simple Ada Program,,Getting Started with GNAT
918 @anchor{gnat_ugn/getting_started_with_gnat running-gnat}@anchor{31}@anchor{gnat_ugn/getting_started_with_gnat id2}@anchor{32}
919 @section Running GNAT
922 Three steps are needed to create an executable file from an Ada source
923 file:
926 @itemize *
928 @item 
929 The source file(s) must be compiled.
931 @item 
932 The file(s) must be bound using the GNAT binder.
934 @item 
935 All appropriate object files must be linked to produce an executable.
936 @end itemize
938 All three steps are most commonly handled by using the @emph{gnatmake}
939 utility program that, given the name of the main program, automatically
940 performs the necessary compilation, binding and linking steps.
942 @node Running a Simple Ada Program,Running a Program with Multiple Units,Running GNAT,Getting Started with GNAT
943 @anchor{gnat_ugn/getting_started_with_gnat running-a-simple-ada-program}@anchor{33}@anchor{gnat_ugn/getting_started_with_gnat id3}@anchor{34}
944 @section Running a Simple Ada Program
947 Any text editor may be used to prepare an Ada program.
948 (If Emacs is used, the optional Ada mode may be helpful in laying out the
949 program.)
950 The program text is a normal text file. We will assume in our initial
951 example that you have used your editor to prepare the following
952 standard format text file:
954 @example
955 with Ada.Text_IO; use Ada.Text_IO;
956 procedure Hello is
957 begin
958    Put_Line ("Hello WORLD!");
959 end Hello;
960 @end example
962 This file should be named @code{hello.adb}.
963 With the normal default file naming conventions, GNAT requires
964 that each file
965 contain a single compilation unit whose file name is the
966 unit name,
967 with periods replaced by hyphens; the
968 extension is @code{ads} for a
969 spec and @code{adb} for a body.
970 You can override this default file naming convention by use of the
971 special pragma @cite{Source_File_Name} (for further information please
972 see @ref{35,,Using Other File Names}).
973 Alternatively, if you want to rename your files according to this default
974 convention, which is probably more convenient if you will be using GNAT
975 for all your compilations, then the @cite{gnatchop} utility
976 can be used to generate correctly-named source files
977 (see @ref{36,,Renaming Files with gnatchop}).
979 You can compile the program using the following command (@cite{$} is used
980 as the command prompt in the examples in this document):
982 @example
983 $ gcc -c hello.adb
984 @end example
986 @emph{gcc} is the command used to run the compiler. This compiler is
987 capable of compiling programs in several languages, including Ada and
988 C. It assumes that you have given it an Ada program if the file extension is
989 either @code{.ads} or @code{.adb}, and it will then call
990 the GNAT compiler to compile the specified file.
992 The @code{-c} switch is required. It tells @emph{gcc} to only do a
993 compilation. (For C programs, @emph{gcc} can also do linking, but this
994 capability is not used directly for Ada programs, so the @code{-c}
995 switch must always be present.)
997 This compile command generates a file
998 @code{hello.o}, which is the object
999 file corresponding to your Ada program. It also generates
1000 an 'Ada Library Information' file @code{hello.ali},
1001 which contains additional information used to check
1002 that an Ada program is consistent.
1003 To build an executable file,
1004 use @cite{gnatbind} to bind the program
1005 and @emph{gnatlink} to link it. The
1006 argument to both @cite{gnatbind} and @emph{gnatlink} is the name of the
1007 @code{ALI} file, but the default extension of @code{.ali} can
1008 be omitted. This means that in the most common case, the argument
1009 is simply the name of the main program:
1011 @example
1012 $ gnatbind hello
1013 $ gnatlink hello
1014 @end example
1016 A simpler method of carrying out these steps is to use @emph{gnatmake},
1017 a master program that invokes all the required
1018 compilation, binding and linking tools in the correct order. In particular,
1019 @emph{gnatmake} automatically recompiles any sources that have been
1020 modified since they were last compiled, or sources that depend
1021 on such modified sources, so that 'version skew' is avoided.
1023 @geindex Version skew (avoided by *gnatmake*)
1025 @example
1026 $ gnatmake hello.adb
1027 @end example
1029 The result is an executable program called @code{hello}, which can be
1030 run by entering:
1032 @example
1033 $ hello
1034 @end example
1036 assuming that the current directory is on the search path
1037 for executable programs.
1039 and, if all has gone well, you will see:
1041 @example
1042 Hello WORLD!
1043 @end example
1045 appear in response to this command.
1047 @node Running a Program with Multiple Units,Using the gnatmake Utility,Running a Simple Ada Program,Getting Started with GNAT
1048 @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}
1049 @section Running a Program with Multiple Units
1052 Consider a slightly more complicated example that has three files: a
1053 main program, and the spec and body of a package:
1055 @example
1056 package Greetings is
1057    procedure Hello;
1058    procedure Goodbye;
1059 end Greetings;
1061 with Ada.Text_IO; use Ada.Text_IO;
1062 package body Greetings is
1063    procedure Hello is
1064    begin
1065       Put_Line ("Hello WORLD!");
1066    end Hello;
1068    procedure Goodbye is
1069    begin
1070       Put_Line ("Goodbye WORLD!");
1071    end Goodbye;
1072 end Greetings;
1074 with Greetings;
1075 procedure Gmain is
1076 begin
1077    Greetings.Hello;
1078    Greetings.Goodbye;
1079 end Gmain;
1080 @end example
1082 Following the one-unit-per-file rule, place this program in the
1083 following three separate files:
1086 @table @asis
1088 @item @emph{greetings.ads}
1090 spec of package @cite{Greetings}
1092 @item @emph{greetings.adb}
1094 body of package @cite{Greetings}
1096 @item @emph{gmain.adb}
1098 body of main program
1099 @end table
1101 To build an executable version of
1102 this program, we could use four separate steps to compile, bind, and link
1103 the program, as follows:
1105 @example
1106 $ gcc -c gmain.adb
1107 $ gcc -c greetings.adb
1108 $ gnatbind gmain
1109 $ gnatlink gmain
1110 @end example
1112 Note that there is no required order of compilation when using GNAT.
1113 In particular it is perfectly fine to compile the main program first.
1114 Also, it is not necessary to compile package specs in the case where
1115 there is an accompanying body; you only need to compile the body. If you want
1116 to submit these files to the compiler for semantic checking and not code
1117 generation, then use the @code{-gnatc} switch:
1119 @example
1120 $ gcc -c greetings.ads -gnatc
1121 @end example
1123 Although the compilation can be done in separate steps as in the
1124 above example, in practice it is almost always more convenient
1125 to use the @emph{gnatmake} tool. All you need to know in this case
1126 is the name of the main program's source file. The effect of the above four
1127 commands can be achieved with a single one:
1129 @example
1130 $ gnatmake gmain.adb
1131 @end example
1133 In the next section we discuss the advantages of using @emph{gnatmake} in
1134 more detail.
1136 @node Using the gnatmake Utility,,Running a Program with Multiple Units,Getting Started with GNAT
1137 @anchor{gnat_ugn/getting_started_with_gnat using-the-gnatmake-utility}@anchor{39}@anchor{gnat_ugn/getting_started_with_gnat id5}@anchor{3a}
1138 @section Using the @emph{gnatmake} Utility
1141 If you work on a program by compiling single components at a time using
1142 @emph{gcc}, you typically keep track of the units you modify. In order to
1143 build a consistent system, you compile not only these units, but also any
1144 units that depend on the units you have modified.
1145 For example, in the preceding case,
1146 if you edit @code{gmain.adb}, you only need to recompile that file. But if
1147 you edit @code{greetings.ads}, you must recompile both
1148 @code{greetings.adb} and @code{gmain.adb}, because both files contain
1149 units that depend on @code{greetings.ads}.
1151 @emph{gnatbind} will warn you if you forget one of these compilation
1152 steps, so that it is impossible to generate an inconsistent program as a
1153 result of forgetting to do a compilation. Nevertheless it is tedious and
1154 error-prone to keep track of dependencies among units.
1155 One approach to handle the dependency-bookkeeping is to use a
1156 makefile. However, makefiles present maintenance problems of their own:
1157 if the dependencies change as you change the program, you must make
1158 sure that the makefile is kept up-to-date manually, which is also an
1159 error-prone process.
1161 The @emph{gnatmake} utility takes care of these details automatically.
1162 Invoke it using either one of the following forms:
1164 @example
1165 $ gnatmake gmain.adb
1166 $ gnatmake gmain
1167 @end example
1169 The argument is the name of the file containing the main program;
1170 you may omit the extension. @emph{gnatmake}
1171 examines the environment, automatically recompiles any files that need
1172 recompiling, and binds and links the resulting set of object files,
1173 generating the executable file, @code{gmain}.
1174 In a large program, it
1175 can be extremely helpful to use @emph{gnatmake}, because working out by hand
1176 what needs to be recompiled can be difficult.
1178 Note that @emph{gnatmake} takes into account all the Ada rules that
1179 establish dependencies among units. These include dependencies that result
1180 from inlining subprogram bodies, and from
1181 generic instantiation. Unlike some other
1182 Ada make tools, @emph{gnatmake} does not rely on the dependencies that were
1183 found by the compiler on a previous compilation, which may possibly
1184 be wrong when sources change. @emph{gnatmake} determines the exact set of
1185 dependencies from scratch each time it is run.
1187 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
1189 @node The GNAT Compilation Model,Building Executable Programs with GNAT,Getting Started with GNAT,Top
1190 @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}
1191 @chapter The GNAT Compilation Model
1194 @geindex GNAT compilation model
1196 @geindex Compilation model
1198 This chapter describes the compilation model used by GNAT. Although
1199 similar to that used by other languages such as C and C++, this model
1200 is substantially different from the traditional Ada compilation models,
1201 which are based on a centralized program library. The chapter covers
1202 the following material:
1205 @itemize *
1207 @item 
1208 Topics related to source file makeup and naming
1211 @itemize *
1213 @item 
1214 @ref{3d,,Source Representation}
1216 @item 
1217 @ref{3e,,Foreign Language Representation}
1219 @item 
1220 @ref{3f,,File Naming Topics and Utilities}
1221 @end itemize
1223 @item 
1224 @ref{14,,Configuration Pragmas}
1226 @item 
1227 @ref{40,,Generating Object Files}
1229 @item 
1230 @ref{41,,Source Dependencies}
1232 @item 
1233 @ref{42,,The Ada Library Information Files}
1235 @item 
1236 @ref{43,,Binding an Ada Program}
1238 @item 
1239 @ref{15,,GNAT and Libraries}
1241 @item 
1242 @ref{16,,Conditional Compilation}
1244 @item 
1245 @ref{44,,Mixed Language Programming}
1247 @item 
1248 @ref{45,,GNAT and Other Compilation Models}
1250 @item 
1251 @ref{1a,,Using GNAT Files with External Tools}
1252 @end itemize
1254 @menu
1255 * Source Representation:: 
1256 * Foreign Language Representation:: 
1257 * File Naming Topics and Utilities:: 
1258 * Configuration Pragmas:: 
1259 * Generating Object Files:: 
1260 * Source Dependencies:: 
1261 * The Ada Library Information Files:: 
1262 * Binding an Ada Program:: 
1263 * GNAT and Libraries:: 
1264 * Conditional Compilation:: 
1265 * Mixed Language Programming:: 
1266 * GNAT and Other Compilation Models:: 
1267 * Using GNAT Files with External Tools:: 
1269 @end menu
1271 @node Source Representation,Foreign Language Representation,,The GNAT Compilation Model
1272 @anchor{gnat_ugn/the_gnat_compilation_model source-representation}@anchor{3d}@anchor{gnat_ugn/the_gnat_compilation_model id2}@anchor{46}
1273 @section Source Representation
1276 @geindex Latin-1
1278 @geindex VT
1279 @geindex HT
1280 @geindex CR
1281 @geindex LF
1282 @geindex FF
1284 Ada source programs are represented in standard text files, using
1285 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1286 7-bit ASCII set, plus additional characters used for
1287 representing foreign languages (see @ref{3e,,Foreign Language Representation}
1288 for support of non-USA character sets). The format effector characters
1289 are represented using their standard ASCII encodings, as follows:
1291 @quotation
1294 @multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxx} 
1295 @item
1297 Character
1299 @tab
1301 Effect
1303 @tab
1305 Code
1307 @item
1309 @code{VT}
1311 @tab
1313 Vertical tab
1315 @tab
1317 @cite{16#0B#}
1319 @item
1321 @code{HT}
1323 @tab
1325 Horizontal tab
1327 @tab
1329 @cite{16#09#}
1331 @item
1333 @code{CR}
1335 @tab
1337 Carriage return
1339 @tab
1341 @cite{16#0D#}
1343 @item
1345 @code{LF}
1347 @tab
1349 Line feed
1351 @tab
1353 @cite{16#0A#}
1355 @item
1357 @code{FF}
1359 @tab
1361 Form feed
1363 @tab
1365 @cite{16#0C#}
1367 @end multitable
1369 @end quotation
1371 Source files are in standard text file format. In addition, GNAT will
1372 recognize a wide variety of stream formats, in which the end of
1373 physical lines is marked by any of the following sequences:
1374 @cite{LF}, @cite{CR}, @cite{CR-LF}, or @cite{LF-CR}. This is useful
1375 in accommodating files that are imported from other operating systems.
1377 @geindex End of source file; Source file@comma{} end
1379 @geindex SUB (control character)
1381 The end of a source file is normally represented by the physical end of
1382 file. However, the control character @cite{16#1A#} (@code{SUB}) is also
1383 recognized as signalling the end of the source file. Again, this is
1384 provided for compatibility with other operating systems where this
1385 code is used to represent the end of file.
1387 @geindex spec (definition)
1388 @geindex compilation (definition)
1390 Each file contains a single Ada compilation unit, including any pragmas
1391 associated with the unit. For example, this means you must place a
1392 package declaration (a package @cite{spec}) and the corresponding body in
1393 separate files. An Ada @cite{compilation} (which is a sequence of
1394 compilation units) is represented using a sequence of files. Similarly,
1395 you will place each subunit or child unit in a separate file.
1397 @node Foreign Language Representation,File Naming Topics and Utilities,Source Representation,The GNAT Compilation Model
1398 @anchor{gnat_ugn/the_gnat_compilation_model foreign-language-representation}@anchor{3e}@anchor{gnat_ugn/the_gnat_compilation_model id3}@anchor{47}
1399 @section Foreign Language Representation
1402 GNAT supports the standard character sets defined in Ada as well as
1403 several other non-standard character sets for use in localized versions
1404 of the compiler (@ref{48,,Character Set Control}).
1406 @menu
1407 * Latin-1:: 
1408 * Other 8-Bit Codes:: 
1409 * Wide_Character Encodings:: 
1410 * Wide_Wide_Character Encodings:: 
1412 @end menu
1414 @node Latin-1,Other 8-Bit Codes,,Foreign Language Representation
1415 @anchor{gnat_ugn/the_gnat_compilation_model id4}@anchor{49}@anchor{gnat_ugn/the_gnat_compilation_model latin-1}@anchor{4a}
1416 @subsection Latin-1
1419 @geindex Latin-1
1421 The basic character set is Latin-1. This character set is defined by ISO
1422 standard 8859, part 1. The lower half (character codes @cite{16#00#}
1423 ... @cite{16#7F#)} is identical to standard ASCII coding, but the upper
1424 half is used to represent additional characters. These include extended letters
1425 used by European languages, such as French accents, the vowels with umlauts
1426 used in German, and the extra letter A-ring used in Swedish.
1428 @geindex Ada.Characters.Latin_1
1430 For a complete list of Latin-1 codes and their encodings, see the source
1431 file of library unit @cite{Ada.Characters.Latin_1} in file
1432 @code{a-chlat1.ads}.
1433 You may use any of these extended characters freely in character or
1434 string literals. In addition, the extended characters that represent
1435 letters can be used in identifiers.
1437 @node Other 8-Bit Codes,Wide_Character Encodings,Latin-1,Foreign Language Representation
1438 @anchor{gnat_ugn/the_gnat_compilation_model other-8-bit-codes}@anchor{4b}@anchor{gnat_ugn/the_gnat_compilation_model id5}@anchor{4c}
1439 @subsection Other 8-Bit Codes
1442 GNAT also supports several other 8-bit coding schemes:
1444 @geindex Latin-2
1446 @geindex ISO 8859-2
1449 @table @asis
1451 @item @emph{ISO 8859-2 (Latin-2)}
1453 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1454 equivalence.
1455 @end table
1457 @geindex Latin-3
1459 @geindex ISO 8859-3
1462 @table @asis
1464 @item @emph{ISO 8859-3 (Latin-3)}
1466 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1467 equivalence.
1468 @end table
1470 @geindex Latin-4
1472 @geindex ISO 8859-4
1475 @table @asis
1477 @item @emph{ISO 8859-4 (Latin-4)}
1479 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1480 equivalence.
1481 @end table
1483 @geindex ISO 8859-5
1485 @geindex Cyrillic
1488 @table @asis
1490 @item @emph{ISO 8859-5 (Cyrillic)}
1492 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1493 lowercase equivalence.
1494 @end table
1496 @geindex ISO 8859-15
1498 @geindex Latin-9
1501 @table @asis
1503 @item @emph{ISO 8859-15 (Latin-9)}
1505 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1506 lowercase equivalence
1507 @end table
1509 @geindex code page 437 (IBM PC)
1512 @table @asis
1514 @item @emph{IBM PC (code page 437)}
1516 This code page is the normal default for PCs in the U.S. It corresponds
1517 to the original IBM PC character set. This set has some, but not all, of
1518 the extended Latin-1 letters, but these letters do not have the same
1519 encoding as Latin-1. In this mode, these letters are allowed in
1520 identifiers with uppercase and lowercase equivalence.
1521 @end table
1523 @geindex code page 850 (IBM PC)
1526 @table @asis
1528 @item @emph{IBM PC (code page 850)}
1530 This code page is a modification of 437 extended to include all the
1531 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1532 mode, all these letters are allowed in identifiers with uppercase and
1533 lowercase equivalence.
1535 @item @emph{Full Upper 8-bit}
1537 Any character in the range 80-FF allowed in identifiers, and all are
1538 considered distinct. In other words, there are no uppercase and lowercase
1539 equivalences in this range. This is useful in conjunction with
1540 certain encoding schemes used for some foreign character sets (e.g.,
1541 the typical method of representing Chinese characters on the PC).
1543 @item @emph{No Upper-Half}
1545 No upper-half characters in the range 80-FF are allowed in identifiers.
1546 This gives Ada 83 compatibility for identifier names.
1547 @end table
1549 For precise data on the encodings permitted, and the uppercase and lowercase
1550 equivalences that are recognized, see the file @code{csets.adb} in
1551 the GNAT compiler sources. You will need to obtain a full source release
1552 of GNAT to obtain this file.
1554 @node Wide_Character Encodings,Wide_Wide_Character Encodings,Other 8-Bit Codes,Foreign Language Representation
1555 @anchor{gnat_ugn/the_gnat_compilation_model id6}@anchor{4d}@anchor{gnat_ugn/the_gnat_compilation_model wide-character-encodings}@anchor{4e}
1556 @subsection Wide_Character Encodings
1559 GNAT allows wide character codes to appear in character and string
1560 literals, and also optionally in identifiers, by means of the following
1561 possible encoding schemes:
1564 @table @asis
1566 @item @emph{Hex Coding}
1568 In this encoding, a wide character is represented by the following five
1569 character sequence:
1571 @example
1572 ESC a b c d
1573 @end example
1575 where @cite{a}, @cite{b}, @cite{c}, @cite{d} are the four hexadecimal
1576 characters (using uppercase letters) of the wide character code. For
1577 example, ESC A345 is used to represent the wide character with code
1578 @cite{16#A345#}.
1579 This scheme is compatible with use of the full Wide_Character set.
1581 @item @emph{Upper-Half Coding}
1583 @geindex Upper-Half Coding
1585 The wide character with encoding @cite{16#abcd#} where the upper bit is on
1586 (in other words, 'a' is in the range 8-F) is represented as two bytes,
1587 @cite{16#ab#} and @cite{16#cd#}. The second byte cannot be a format control
1588 character, but is not required to be in the upper half. This method can
1589 be also used for shift-JIS or EUC, where the internal coding matches the
1590 external coding.
1592 @item @emph{Shift JIS Coding}
1594 @geindex Shift JIS Coding
1596 A wide character is represented by a two-character sequence,
1597 @cite{16#ab#} and
1598 @cite{16#cd#}, with the restrictions described for upper-half encoding as
1599 described above. The internal character code is the corresponding JIS
1600 character according to the standard algorithm for Shift-JIS
1601 conversion. Only characters defined in the JIS code set table can be
1602 used with this encoding method.
1604 @item @emph{EUC Coding}
1606 @geindex EUC Coding
1608 A wide character is represented by a two-character sequence
1609 @cite{16#ab#} and
1610 @cite{16#cd#}, with both characters being in the upper half. The internal
1611 character code is the corresponding JIS character according to the EUC
1612 encoding algorithm. Only characters defined in the JIS code set table
1613 can be used with this encoding method.
1615 @item @emph{UTF-8 Coding}
1617 A wide character is represented using
1618 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1619 10646-1/Am.2. Depending on the character value, the representation
1620 is a one, two, or three byte sequence:
1622 @example
1623 16#0000#-16#007f#: 2#0`xxxxxxx`#
1624 16#0080#-16#07ff#: 2#110`xxxxx`# 2#10`xxxxxx`#
1625 16#0800#-16#ffff#: 2#1110`xxxx`# 2#10`xxxxxx`# 2#10`xxxxxx`#
1626 @end example
1628 where the @cite{xxx} bits correspond to the left-padded bits of the
1629 16-bit character value. Note that all lower half ASCII characters
1630 are represented as ASCII bytes and all upper half characters and
1631 other wide characters are represented as sequences of upper-half
1632 (The full UTF-8 scheme allows for encoding 31-bit characters as
1633 6-byte sequences, and in the following section on wide wide
1634 characters, the use of these sequences is documented).
1636 @item @emph{Brackets Coding}
1638 In this encoding, a wide character is represented by the following eight
1639 character sequence:
1641 @example
1642 [ " a b c d " ]
1643 @end example
1645 where @cite{a}, @cite{b}, @cite{c}, @cite{d} are the four hexadecimal
1646 characters (using uppercase letters) of the wide character code. For
1647 example, ['A345'] is used to represent the wide character with code
1648 @cite{16#A345#}. It is also possible (though not required) to use the
1649 Brackets coding for upper half characters. For example, the code
1650 @cite{16#A3#} can be represented as @cite{['A3']}.
1652 This scheme is compatible with use of the full Wide_Character set,
1653 and is also the method used for wide character encoding in some standard
1654 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1655 @end table
1657 @cartouche
1658 @quotation Note 
1659 Some of these coding schemes do not permit the full use of the
1660 Ada character set. For example, neither Shift JIS nor EUC allow the
1661 use of the upper half of the Latin-1 set.
1662 @end quotation
1663 @end cartouche
1665 @node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1666 @anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{4f}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{50}
1667 @subsection Wide_Wide_Character Encodings
1670 GNAT allows wide wide character codes to appear in character and string
1671 literals, and also optionally in identifiers, by means of the following
1672 possible encoding schemes:
1675 @table @asis
1677 @item @emph{UTF-8 Coding}
1679 A wide character is represented using
1680 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1681 10646-1/Am.2. Depending on the character value, the representation
1682 of character codes with values greater than 16#FFFF# is a
1683 is a four, five, or six byte sequence:
1685 @example
1686 16#01_0000#-16#10_FFFF#:     11110xxx 10xxxxxx 10xxxxxx
1687                              10xxxxxx
1688 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1689                              10xxxxxx 10xxxxxx
1690 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1691                              10xxxxxx 10xxxxxx 10xxxxxx
1692 @end example
1694 where the @cite{xxx} bits correspond to the left-padded bits of the
1695 32-bit character value.
1697 @item @emph{Brackets Coding}
1699 In this encoding, a wide wide character is represented by the following ten or
1700 twelve byte character sequence:
1702 @example
1703 [ " a b c d e f " ]
1704 [ " a b c d e f g h " ]
1705 @end example
1707 where @cite{a-h} are the six or eight hexadecimal
1708 characters (using uppercase letters) of the wide wide character code. For
1709 example, ["1F4567"] is used to represent the wide wide character with code
1710 @cite{16#001F_4567#}.
1712 This scheme is compatible with use of the full Wide_Wide_Character set,
1713 and is also the method used for wide wide character encoding in some standard
1714 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1715 @end table
1717 @node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1718 @anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{3f}
1719 @section File Naming Topics and Utilities
1722 GNAT has a default file naming scheme and also provides the user with
1723 a high degree of control over how the names and extensions of the
1724 source files correspond to the Ada compilation units that they contain.
1726 @menu
1727 * File Naming Rules:: 
1728 * Using Other File Names:: 
1729 * Alternative File Naming Schemes:: 
1730 * Handling Arbitrary File Naming Conventions with gnatname:: 
1731 * File Name Krunching with gnatkr:: 
1732 * Renaming Files with gnatchop:: 
1734 @end menu
1736 @node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1737 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{52}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{53}
1738 @subsection File Naming Rules
1741 The default file name is determined by the name of the unit that the
1742 file contains. The name is formed by taking the full expanded name of
1743 the unit and replacing the separating dots with hyphens and using
1744 lowercase for all letters.
1746 An exception arises if the file name generated by the above rules starts
1747 with one of the characters
1748 @cite{a}, @cite{g}, @cite{i}, or @cite{s}, and the second character is a
1749 minus. In this case, the character tilde is used in place
1750 of the minus. The reason for this special rule is to avoid clashes with
1751 the standard names for child units of the packages System, Ada,
1752 Interfaces, and GNAT, which use the prefixes
1753 @cite{s-}, @cite{a-}, @cite{i-}, and @cite{g-},
1754 respectively.
1756 The file extension is @code{.ads} for a spec and
1757 @code{.adb} for a body. The following table shows some
1758 examples of these rules.
1760 @quotation
1763 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
1764 @item
1766 Source File
1768 @tab
1770 Ada Compilation Unit
1772 @item
1774 @code{main.ads}
1776 @tab
1778 Main (spec)
1780 @item
1782 @code{main.adb}
1784 @tab
1786 Main (body)
1788 @item
1790 @code{arith_functions.ads}
1792 @tab
1794 Arith_Functions (package spec)
1796 @item
1798 @code{arith_functions.adb}
1800 @tab
1802 Arith_Functions (package body)
1804 @item
1806 @code{func-spec.ads}
1808 @tab
1810 Func.Spec (child package spec)
1812 @item
1814 @code{func-spec.adb}
1816 @tab
1818 Func.Spec (child package body)
1820 @item
1822 @code{main-sub.adb}
1824 @tab
1826 Sub (subunit of Main)
1828 @item
1830 @code{a~bad.adb}
1832 @tab
1834 A.Bad (child package body)
1836 @end multitable
1838 @end quotation
1840 Following these rules can result in excessively long
1841 file names if corresponding
1842 unit names are long (for example, if child units or subunits are
1843 heavily nested). An option is available to shorten such long file names
1844 (called file name 'krunching'). This may be particularly useful when
1845 programs being developed with GNAT are to be used on operating systems
1846 with limited file name lengths. @ref{54,,Using gnatkr}.
1848 Of course, no file shortening algorithm can guarantee uniqueness over
1849 all possible unit names; if file name krunching is used, it is your
1850 responsibility to ensure no name clashes occur. Alternatively you
1851 can specify the exact file names that you want used, as described
1852 in the next section. Finally, if your Ada programs are migrating from a
1853 compiler with a different naming convention, you can use the gnatchop
1854 utility to produce source files that follow the GNAT naming conventions.
1855 (For details see @ref{36,,Renaming Files with gnatchop}.)
1857 Note: in the case of Windows or Mac OS operating systems, case is not
1858 significant. So for example on @cite{Windows} if the canonical name is
1859 @cite{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1860 However, case is significant for other operating systems, so for example,
1861 if you want to use other than canonically cased file names on a Unix system,
1862 you need to follow the procedures described in the next section.
1864 @node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1865 @anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{55}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{35}
1866 @subsection Using Other File Names
1869 @geindex File names
1871 In the previous section, we have described the default rules used by
1872 GNAT to determine the file name in which a given unit resides. It is
1873 often convenient to follow these default rules, and if you follow them,
1874 the compiler knows without being explicitly told where to find all
1875 the files it needs.
1877 @geindex Source_File_Name pragma
1879 However, in some cases, particularly when a program is imported from
1880 another Ada compiler environment, it may be more convenient for the
1881 programmer to specify which file names contain which units. GNAT allows
1882 arbitrary file names to be used by means of the Source_File_Name pragma.
1883 The form of this pragma is as shown in the following examples:
1885 @example
1886 pragma Source_File_Name (My_Utilities.Stacks,
1887   Spec_File_Name => "myutilst_a.ada");
1888 pragma Source_File_name (My_Utilities.Stacks,
1889   Body_File_Name => "myutilst.ada");
1890 @end example
1892 As shown in this example, the first argument for the pragma is the unit
1893 name (in this example a child unit). The second argument has the form
1894 of a named association. The identifier
1895 indicates whether the file name is for a spec or a body;
1896 the file name itself is given by a string literal.
1898 The source file name pragma is a configuration pragma, which means that
1899 normally it will be placed in the @code{gnat.adc}
1900 file used to hold configuration
1901 pragmas that apply to a complete compilation environment.
1902 For more details on how the @code{gnat.adc} file is created and used
1903 see @ref{56,,Handling of Configuration Pragmas}.
1905 @geindex gnat.adc
1907 GNAT allows completely arbitrary file names to be specified using the
1908 source file name pragma. However, if the file name specified has an
1909 extension other than @code{.ads} or @code{.adb} it is necessary to use
1910 a special syntax when compiling the file. The name in this case must be
1911 preceded by the special sequence @emph{-x} followed by a space and the name
1912 of the language, here @cite{ada}, as in:
1914 @example
1915 $ gcc -c -x ada peculiar_file_name.sim
1916 @end example
1918 @cite{gnatmake} handles non-standard file names in the usual manner (the
1919 non-standard file name for the main program is simply used as the
1920 argument to gnatmake). Note that if the extension is also non-standard,
1921 then it must be included in the @cite{gnatmake} command, it may not
1922 be omitted.
1924 @node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
1925 @anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{57}@anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{58}
1926 @subsection Alternative File Naming Schemes
1929 @geindex File naming schemes
1930 @geindex alternative
1932 @geindex File names
1934 The previous section described the use of the @cite{Source_File_Name}
1935 pragma to allow arbitrary names to be assigned to individual source files.
1936 However, this approach requires one pragma for each file, and especially in
1937 large systems can result in very long @code{gnat.adc} files, and also create
1938 a maintenance problem.
1940 @geindex Source_File_Name pragma
1942 GNAT also provides a facility for specifying systematic file naming schemes
1943 other than the standard default naming scheme previously described. An
1944 alternative scheme for naming is specified by the use of
1945 @cite{Source_File_Name} pragmas having the following format:
1947 @example
1948 pragma Source_File_Name (
1949    Spec_File_Name  => FILE_NAME_PATTERN
1950  [ , Casing          => CASING_SPEC]
1951  [ , Dot_Replacement => STRING_LITERAL ] );
1953 pragma Source_File_Name (
1954    Body_File_Name  => FILE_NAME_PATTERN
1955  [ , Casing          => CASING_SPEC ]
1956  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1958 pragma Source_File_Name (
1959    Subunit_File_Name  => FILE_NAME_PATTERN
1960  [ , Casing          => CASING_SPEC ]
1961  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1963 FILE_NAME_PATTERN ::= STRING_LITERAL
1964 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1965 @end example
1967 The @cite{FILE_NAME_PATTERN} string shows how the file name is constructed.
1968 It contains a single asterisk character, and the unit name is substituted
1969 systematically for this asterisk. The optional parameter
1970 @cite{Casing} indicates
1971 whether the unit name is to be all upper-case letters, all lower-case letters,
1972 or mixed-case. If no
1973 @cite{Casing} parameter is used, then the default is all
1974 lower-case.
1976 The optional @cite{Dot_Replacement} string is used to replace any periods
1977 that occur in subunit or child unit names. If no @cite{Dot_Replacement}
1978 argument is used then separating dots appear unchanged in the resulting
1979 file name.
1980 Although the above syntax indicates that the
1981 @cite{Casing} argument must appear
1982 before the @cite{Dot_Replacement} argument, but it
1983 is also permissible to write these arguments in the opposite order.
1985 As indicated, it is possible to specify different naming schemes for
1986 bodies, specs, and subunits. Quite often the rule for subunits is the
1987 same as the rule for bodies, in which case, there is no need to give
1988 a separate @cite{Subunit_File_Name} rule, and in this case the
1989 @cite{Body_File_name} rule is used for subunits as well.
1991 The separate rule for subunits can also be used to implement the rather
1992 unusual case of a compilation environment (e.g., a single directory) which
1993 contains a subunit and a child unit with the same unit name. Although
1994 both units cannot appear in the same partition, the Ada Reference Manual
1995 allows (but does not require) the possibility of the two units coexisting
1996 in the same environment.
1998 The file name translation works in the following steps:
2001 @itemize *
2003 @item 
2004 If there is a specific @cite{Source_File_Name} pragma for the given unit,
2005 then this is always used, and any general pattern rules are ignored.
2007 @item 
2008 If there is a pattern type @cite{Source_File_Name} pragma that applies to
2009 the unit, then the resulting file name will be used if the file exists. If
2010 more than one pattern matches, the latest one will be tried first, and the
2011 first attempt resulting in a reference to a file that exists will be used.
2013 @item 
2014 If no pattern type @cite{Source_File_Name} pragma that applies to the unit
2015 for which the corresponding file exists, then the standard GNAT default
2016 naming rules are used.
2017 @end itemize
2019 As an example of the use of this mechanism, consider a commonly used scheme
2020 in which file names are all lower case, with separating periods copied
2021 unchanged to the resulting file name, and specs end with @code{.1.ada}, and
2022 bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
2023 two pragmas appear:
2025 @example
2026 pragma Source_File_Name
2027   (Spec_File_Name => ".1.ada");
2028 pragma Source_File_Name
2029   (Body_File_Name => ".2.ada");
2030 @end example
2032 The default GNAT scheme is actually implemented by providing the following
2033 default pragmas internally:
2035 @example
2036 pragma Source_File_Name
2037   (Spec_File_Name => ".ads", Dot_Replacement => "-");
2038 pragma Source_File_Name
2039   (Body_File_Name => ".adb", Dot_Replacement => "-");
2040 @end example
2042 Our final example implements a scheme typically used with one of the
2043 Ada 83 compilers, where the separator character for subunits was '__'
2044 (two underscores), specs were identified by adding @code{_.ADA}, bodies
2045 by adding @code{.ADA}, and subunits by
2046 adding @code{.SEP}. All file names were
2047 upper case. Child units were not present of course since this was an
2048 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2049 the same double underscore separator for child units.
2051 @example
2052 pragma Source_File_Name
2053   (Spec_File_Name => "_.ADA",
2054    Dot_Replacement => "__",
2055    Casing = Uppercase);
2056 pragma Source_File_Name
2057   (Body_File_Name => ".ADA",
2058    Dot_Replacement => "__",
2059    Casing = Uppercase);
2060 pragma Source_File_Name
2061   (Subunit_File_Name => ".SEP",
2062    Dot_Replacement => "__",
2063    Casing = Uppercase);
2064 @end example
2066 @geindex gnatname
2068 @node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
2069 @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}
2070 @subsection Handling Arbitrary File Naming Conventions with @cite{gnatname}
2073 @geindex File Naming Conventions
2075 @menu
2076 * Arbitrary File Naming Conventions:: 
2077 * Running gnatname:: 
2078 * Switches for gnatname:: 
2079 * Examples of gnatname Usage:: 
2081 @end menu
2083 @node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
2084 @anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{5b}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{5c}
2085 @subsubsection Arbitrary File Naming Conventions
2088 The GNAT compiler must be able to know the source file name of a compilation
2089 unit.  When using the standard GNAT default file naming conventions
2090 (@cite{.ads} for specs, @cite{.adb} for bodies), the GNAT compiler
2091 does not need additional information.
2093 When the source file names do not follow the standard GNAT default file naming
2094 conventions, the GNAT compiler must be given additional information through
2095 a configuration pragmas file (@ref{14,,Configuration Pragmas})
2096 or a project file.
2097 When the non-standard file naming conventions are well-defined,
2098 a small number of pragmas @cite{Source_File_Name} specifying a naming pattern
2099 (@ref{58,,Alternative File Naming Schemes}) may be sufficient. However,
2100 if the file naming conventions are irregular or arbitrary, a number
2101 of pragma @cite{Source_File_Name} for individual compilation units
2102 must be defined.
2103 To help maintain the correspondence between compilation unit names and
2104 source file names within the compiler,
2105 GNAT provides a tool @cite{gnatname} to generate the required pragmas for a
2106 set of files.
2108 @node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
2109 @anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{5d}@anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{5e}
2110 @subsubsection Running @cite{gnatname}
2113 The usual form of the @cite{gnatname} command is:
2115 @example
2116 $ gnatname [`switches`] `naming_pattern` [`naming_patterns`]
2117     [--and [`switches`] `naming_pattern` [`naming_patterns`]]
2118 @end example
2120 All of the arguments are optional. If invoked without any argument,
2121 @cite{gnatname} will display its usage.
2123 When used with at least one naming pattern, @cite{gnatname} will attempt to
2124 find all the compilation units in files that follow at least one of the
2125 naming patterns. To find these compilation units,
2126 @cite{gnatname} will use the GNAT compiler in syntax-check-only mode on all
2127 regular files.
2129 One or several Naming Patterns may be given as arguments to @cite{gnatname}.
2130 Each Naming Pattern is enclosed between double quotes (or single
2131 quotes on Windows).
2132 A Naming Pattern is a regular expression similar to the wildcard patterns
2133 used in file names by the Unix shells or the DOS prompt.
2135 @cite{gnatname} may be called with several sections of directories/patterns.
2136 Sections are separated by switch @cite{--and}. In each section, there must be
2137 at least one pattern. If no directory is specified in a section, the current
2138 directory (or the project directory is @cite{-P} is used) is implied.
2139 The options other that the directory switches and the patterns apply globally
2140 even if they are in different sections.
2142 Examples of Naming Patterns are:
2144 @example
2145 "*.[12].ada"
2146 "*.ad[sb]*"
2147 "body_*"    "spec_*"
2148 @end example
2150 For a more complete description of the syntax of Naming Patterns,
2151 see the second kind of regular expressions described in @code{g-regexp.ads}
2152 (the 'Glob' regular expressions).
2154 When invoked with no switch @cite{-P}, @cite{gnatname} will create a
2155 configuration pragmas file @code{gnat.adc} in the current working directory,
2156 with pragmas @cite{Source_File_Name} for each file that contains a valid Ada
2157 unit.
2159 @node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
2160 @anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{5f}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{60}
2161 @subsubsection Switches for @cite{gnatname}
2164 Switches for @cite{gnatname} must precede any specified Naming Pattern.
2166 You may specify any of the following switches to @cite{gnatname}:
2168 @geindex --version (gnatname)
2171 @table @asis
2173 @item @code{--version}
2175 Display Copyright and version, then exit disregarding all other options.
2176 @end table
2178 @geindex --help (gnatname)
2181 @table @asis
2183 @item @code{--help}
2185 If @emph{--version} was not used, display usage, then exit disregarding
2186 all other options.
2188 @item @code{--subdirs=@emph{dir}}
2190 Real object, library or exec directories are subdirectories <dir> of the
2191 specified ones.
2193 @item @code{--no-backup}
2195 Do not create a backup copy of an existing project file.
2197 @item @code{--and}
2199 Start another section of directories/patterns.
2200 @end table
2202 @geindex -c (gnatname)
2205 @table @asis
2207 @item @code{-c@emph{filename}}
2209 Create a configuration pragmas file @code{filename} (instead of the default
2210 @code{gnat.adc}).
2211 There may be zero, one or more space between @emph{-c} and
2212 @code{filename}.
2213 @code{filename} may include directory information. @code{filename} must be
2214 writable. There may be only one switch @emph{-c}.
2215 When a switch @emph{-c} is
2216 specified, no switch @emph{-P} may be specified (see below).
2217 @end table
2219 @geindex -d (gnatname)
2222 @table @asis
2224 @item @code{-d@emph{dir}}
2226 Look for source files in directory @code{dir}. There may be zero, one or more
2227 spaces between @emph{-d} and @code{dir}.
2228 @code{dir} may end with @cite{/**}, that is it may be of the form
2229 @cite{root_dir/**}. In this case, the directory @cite{root_dir} and all of its
2230 subdirectories, recursively, have to be searched for sources.
2231 When a switch @emph{-d}
2232 is specified, the current working directory will not be searched for source
2233 files, unless it is explicitly specified with a @emph{-d}
2234 or @emph{-D} switch.
2235 Several switches @emph{-d} may be specified.
2236 If @code{dir} is a relative path, it is relative to the directory of
2237 the configuration pragmas file specified with switch
2238 @emph{-c},
2239 or to the directory of the project file specified with switch
2240 @emph{-P} or,
2241 if neither switch @emph{-c}
2242 nor switch @emph{-P} are specified, it is relative to the
2243 current working directory. The directory
2244 specified with switch @emph{-d} must exist and be readable.
2245 @end table
2247 @geindex -D (gnatname)
2250 @table @asis
2252 @item @code{-D@emph{filename}}
2254 Look for source files in all directories listed in text file @code{filename}.
2255 There may be zero, one or more spaces between @emph{-D}
2256 and @code{filename}.
2257 @code{filename} must be an existing, readable text file.
2258 Each nonempty line in @code{filename} must be a directory.
2259 Specifying switch @emph{-D} is equivalent to specifying as many
2260 switches @emph{-d} as there are nonempty lines in
2261 @code{file}.
2263 @item @code{-eL}
2265 Follow symbolic links when processing project files.
2267 @geindex -f (gnatname)
2269 @item @code{-f@emph{pattern}}
2271 Foreign patterns. Using this switch, it is possible to add sources of languages
2272 other than Ada to the list of sources of a project file.
2273 It is only useful if a -P switch is used.
2274 For example,
2276 @example
2277 gnatname -Pprj -f"*.c" "*.ada"
2278 @end example
2280 will look for Ada units in all files with the @code{.ada} extension,
2281 and will add to the list of file for project @code{prj.gpr} the C files
2282 with extension @code{.c}.
2284 @geindex -h (gnatname)
2286 @item @code{-h}
2288 Output usage (help) information. The output is written to @code{stdout}.
2290 @geindex -P (gnatname)
2292 @item @code{-P@emph{proj}}
2294 Create or update project file @code{proj}. There may be zero, one or more space
2295 between @emph{-P} and @code{proj}. @code{proj} may include directory
2296 information. @code{proj} must be writable.
2297 There may be only one switch @emph{-P}.
2298 When a switch @emph{-P} is specified,
2299 no switch @emph{-c} may be specified.
2300 On all platforms, except on VMS, when @cite{gnatname} is invoked for an
2301 existing project file <proj>.gpr, a backup copy of the project file is created
2302 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
2303 non negative number that makes this backup copy a new file.
2305 @geindex -v (gnatname)
2307 @item @code{-v}
2309 Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2310 This includes name of the file written, the name of the directories to search
2311 and, for each file in those directories whose name matches at least one of
2312 the Naming Patterns, an indication of whether the file contains a unit,
2313 and if so the name of the unit.
2314 @end table
2316 @geindex -v -v (gnatname)
2319 @table @asis
2321 @item @code{-v -v}
2323 Very Verbose mode. In addition to the output produced in verbose mode,
2324 for each file in the searched directories whose name matches none of
2325 the Naming Patterns, an indication is given that there is no match.
2327 @geindex -x (gnatname)
2329 @item @code{-x@emph{pattern}}
2331 Excluded patterns. Using this switch, it is possible to exclude some files
2332 that would match the name patterns. For example,
2334 @example
2335 gnatname -x "*_nt.ada" "*.ada"
2336 @end example
2338 will look for Ada units in all files with the @code{.ada} extension,
2339 except those whose names end with @code{_nt.ada}.
2340 @end table
2342 @node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2343 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{61}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{62}
2344 @subsubsection Examples of @cite{gnatname} Usage
2347 @example
2348 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2349 @end example
2351 In this example, the directory @code{/home/me} must already exist
2352 and be writable. In addition, the directory
2353 @code{/home/me/sources} (specified by
2354 @emph{-d sources}) must exist and be readable.
2356 Note the optional spaces after @emph{-c} and @emph{-d}.
2358 @example
2359 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
2360 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2361 @end example
2363 Note that several switches @emph{-d} may be used,
2364 even in conjunction with one or several switches
2365 @emph{-D}. Several Naming Patterns and one excluded pattern
2366 are used in this example.
2368 @node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2369 @anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{63}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{64}
2370 @subsection File Name Krunching with @cite{gnatkr}
2373 @geindex gnatkr
2375 This section discusses the method used by the compiler to shorten
2376 the default file names chosen for Ada units so that they do not
2377 exceed the maximum length permitted. It also describes the
2378 @cite{gnatkr} utility that can be used to determine the result of
2379 applying this shortening.
2381 @menu
2382 * About gnatkr:: 
2383 * Using gnatkr:: 
2384 * Krunching Method:: 
2385 * Examples of gnatkr Usage:: 
2387 @end menu
2389 @node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2390 @anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{66}
2391 @subsubsection About @cite{gnatkr}
2394 The default file naming rule in GNAT
2395 is that the file name must be derived from
2396 the unit name. The exact default rule is as follows:
2399 @itemize *
2401 @item 
2402 Take the unit name and replace all dots by hyphens.
2404 @item 
2405 If such a replacement occurs in the
2406 second character position of a name, and the first character is
2407 @code{a}, @code{g}, @code{s}, or @code{i},
2408 then replace the dot by the character
2409 @code{~} (tilde)
2410 instead of a minus.
2412 The reason for this exception is to avoid clashes
2413 with the standard names for children of System, Ada, Interfaces,
2414 and GNAT, which use the prefixes
2415 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
2416 respectively.
2417 @end itemize
2419 The @code{-gnatk@emph{nn}}
2420 switch of the compiler activates a 'krunching'
2421 circuit that limits file names to nn characters (where nn is a decimal
2422 integer).
2424 The @cite{gnatkr} utility can be used to determine the krunched name for
2425 a given file, when krunched to a specified maximum length.
2427 @node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2428 @anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{67}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{54}
2429 @subsubsection Using @cite{gnatkr}
2432 The @cite{gnatkr} command has the form:
2434 @example
2435 $ gnatkr `name` [`length`]
2436 @end example
2438 @cite{name} is the uncrunched file name, derived from the name of the unit
2439 in the standard manner described in the previous section (i.e., in particular
2440 all dots are replaced by hyphens). The file name may or may not have an
2441 extension (defined as a suffix of the form period followed by arbitrary
2442 characters other than period). If an extension is present then it will
2443 be preserved in the output. For example, when krunching @code{hellofile.ads}
2444 to eight characters, the result will be hellofil.ads.
2446 Note: for compatibility with previous versions of @cite{gnatkr} dots may
2447 appear in the name instead of hyphens, but the last dot will always be
2448 taken as the start of an extension. So if @cite{gnatkr} is given an argument
2449 such as @code{Hello.World.adb} it will be treated exactly as if the first
2450 period had been a hyphen, and for example krunching to eight characters
2451 gives the result @code{hellworl.adb}.
2453 Note that the result is always all lower case.
2454 Characters of the other case are folded as required.
2456 @cite{length} represents the length of the krunched name. The default
2457 when no argument is given is 8 characters. A length of zero stands for
2458 unlimited, in other words do not chop except for system files where the
2459 implied crunching length is always eight characters.
2461 The output is the krunched name. The output has an extension only if the
2462 original argument was a file name with an extension.
2464 @node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2465 @anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{68}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{69}
2466 @subsubsection Krunching Method
2469 The initial file name is determined by the name of the unit that the file
2470 contains. The name is formed by taking the full expanded name of the
2471 unit and replacing the separating dots with hyphens and
2472 using lowercase
2473 for all letters, except that a hyphen in the second character position is
2474 replaced by a tilde if the first character is
2475 @code{a}, @code{i}, @code{g}, or @code{s}.
2476 The extension is @cite{.ads} for a
2477 spec and @cite{.adb} for a body.
2478 Krunching does not affect the extension, but the file name is shortened to
2479 the specified length by following these rules:
2482 @itemize *
2484 @item 
2485 The name is divided into segments separated by hyphens, tildes or
2486 underscores and all hyphens, tildes, and underscores are
2487 eliminated. If this leaves the name short enough, we are done.
2489 @item 
2490 If the name is too long, the longest segment is located (left-most
2491 if there are two of equal length), and shortened by dropping
2492 its last character. This is repeated until the name is short enough.
2494 As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2495 to fit the name into 8 characters as required by some operating systems:
2497 @example
2498 our-strings-wide_fixed 22
2499 our strings wide fixed 19
2500 our string  wide fixed 18
2501 our strin   wide fixed 17
2502 our stri    wide fixed 16
2503 our stri    wide fixe  15
2504 our str     wide fixe  14
2505 our str     wid  fixe  13
2506 our str     wid  fix   12
2507 ou  str     wid  fix   11
2508 ou  st      wid  fix   10
2509 ou  st      wi   fix   9
2510 ou  st      wi   fi    8
2511 Final file name: oustwifi.adb
2512 @end example
2514 @item 
2515 The file names for all predefined units are always krunched to eight
2516 characters. The krunching of these predefined units uses the following
2517 special prefix replacements:
2520 @multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} 
2521 @item
2523 Prefix
2525 @tab
2527 Replacement
2529 @item
2531 @code{ada-}
2533 @tab
2535 @code{a-}
2537 @item
2539 @code{gnat-}
2541 @tab
2543 @code{g-}
2545 @item
2547 @code{interfac es-}
2549 @tab
2551 @code{i-}
2553 @item
2555 @code{system-}
2557 @tab
2559 @code{s-}
2561 @end multitable
2564 These system files have a hyphen in the second character position. That
2565 is why normal user files replace such a character with a
2566 tilde, to avoid confusion with system file names.
2568 As an example of this special rule, consider
2569 @code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2571 @example
2572 ada-strings-wide_fixed 22
2573 a-  strings wide fixed 18
2574 a-  string  wide fixed 17
2575 a-  strin   wide fixed 16
2576 a-  stri    wide fixed 15
2577 a-  stri    wide fixe  14
2578 a-  str     wide fixe  13
2579 a-  str     wid  fixe  12
2580 a-  str     wid  fix   11
2581 a-  st      wid  fix   10
2582 a-  st      wi   fix   9
2583 a-  st      wi   fi    8
2584 Final file name: a-stwifi.adb
2585 @end example
2586 @end itemize
2588 Of course no file shortening algorithm can guarantee uniqueness over all
2589 possible unit names, and if file name krunching is used then it is your
2590 responsibility to ensure that no name clashes occur. The utility
2591 program @cite{gnatkr} is supplied for conveniently determining the
2592 krunched name of a file.
2594 @node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2595 @anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{6a}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{6b}
2596 @subsubsection Examples of @cite{gnatkr} Usage
2599 @example
2600 $ gnatkr very_long_unit_name.ads      --> velounna.ads
2601 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
2602 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2603 $ gnatkr grandparent-parent-child     --> grparchi
2604 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2605 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2606 @end example
2608 @node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2609 @anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{36}
2610 @subsection Renaming Files with @cite{gnatchop}
2613 @geindex gnatchop
2615 This section discusses how to handle files with multiple units by using
2616 the @cite{gnatchop} utility. This utility is also useful in renaming
2617 files to meet the standard GNAT default file naming conventions.
2619 @menu
2620 * Handling Files with Multiple Units:: 
2621 * Operating gnatchop in Compilation Mode:: 
2622 * Command Line for gnatchop:: 
2623 * Switches for gnatchop:: 
2624 * Examples of gnatchop Usage:: 
2626 @end menu
2628 @node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2629 @anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{6d}@anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{6e}
2630 @subsubsection Handling Files with Multiple Units
2633 The basic compilation model of GNAT requires that a file submitted to the
2634 compiler have only one unit and there be a strict correspondence
2635 between the file name and the unit name.
2637 The @cite{gnatchop} utility allows both of these rules to be relaxed,
2638 allowing GNAT to process files which contain multiple compilation units
2639 and files with arbitrary file names. @cite{gnatchop}
2640 reads the specified file and generates one or more output files,
2641 containing one unit per file. The unit and the file name correspond,
2642 as required by GNAT.
2644 If you want to permanently restructure a set of 'foreign' files so that
2645 they match the GNAT rules, and do the remaining development using the
2646 GNAT structure, you can simply use @emph{gnatchop} once, generate the
2647 new set of files and work with them from that point on.
2649 Alternatively, if you want to keep your files in the 'foreign' format,
2650 perhaps to maintain compatibility with some other Ada compilation
2651 system, you can set up a procedure where you use @emph{gnatchop} each
2652 time you compile, regarding the source files that it writes as temporary
2653 files that you throw away.
2655 Note that if your file containing multiple units starts with a byte order
2656 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2657 will each start with a copy of this BOM, meaning that they can be compiled
2658 automatically in UTF-8 mode without needing to specify an explicit encoding.
2660 @node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2661 @anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{6f}@anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{70}
2662 @subsubsection Operating gnatchop in Compilation Mode
2665 The basic function of @cite{gnatchop} is to take a file with multiple units
2666 and split it into separate files. The boundary between files is reasonably
2667 clear, except for the issue of comments and pragmas. In default mode, the
2668 rule is that any pragmas between units belong to the previous unit, except
2669 that configuration pragmas always belong to the following unit. Any comments
2670 belong to the following unit. These rules
2671 almost always result in the right choice of
2672 the split point without needing to mark it explicitly and most users will
2673 find this default to be what they want. In this default mode it is incorrect to
2674 submit a file containing only configuration pragmas, or one that ends in
2675 configuration pragmas, to @cite{gnatchop}.
2677 However, using a special option to activate 'compilation mode',
2678 @cite{gnatchop}
2679 can perform another function, which is to provide exactly the semantics
2680 required by the RM for handling of configuration pragmas in a compilation.
2681 In the absence of configuration pragmas (at the main file level), this
2682 option has no effect, but it causes such configuration pragmas to be handled
2683 in a quite different manner.
2685 First, in compilation mode, if @cite{gnatchop} is given a file that consists of
2686 only configuration pragmas, then this file is appended to the
2687 @code{gnat.adc} file in the current directory. This behavior provides
2688 the required behavior described in the RM for the actions to be taken
2689 on submitting such a file to the compiler, namely that these pragmas
2690 should apply to all subsequent compilations in the same compilation
2691 environment. Using GNAT, the current directory, possibly containing a
2692 @code{gnat.adc} file is the representation
2693 of a compilation environment. For more information on the
2694 @code{gnat.adc} file, see @ref{56,,Handling of Configuration Pragmas}.
2696 Second, in compilation mode, if @cite{gnatchop}
2697 is given a file that starts with
2698 configuration pragmas, and contains one or more units, then these
2699 configuration pragmas are prepended to each of the chopped files. This
2700 behavior provides the required behavior described in the RM for the
2701 actions to be taken on compiling such a file, namely that the pragmas
2702 apply to all units in the compilation, but not to subsequently compiled
2703 units.
2705 Finally, if configuration pragmas appear between units, they are appended
2706 to the previous unit. This results in the previous unit being illegal,
2707 since the compiler does not accept configuration pragmas that follow
2708 a unit. This provides the required RM behavior that forbids configuration
2709 pragmas other than those preceding the first compilation unit of a
2710 compilation.
2712 For most purposes, @cite{gnatchop} will be used in default mode. The
2713 compilation mode described above is used only if you need exactly
2714 accurate behavior with respect to compilations, and you have files
2715 that contain multiple units and configuration pragmas. In this
2716 circumstance the use of @cite{gnatchop} with the compilation mode
2717 switch provides the required behavior, and is for example the mode
2718 in which GNAT processes the ACVC tests.
2720 @node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2721 @anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{72}
2722 @subsubsection Command Line for @cite{gnatchop}
2725 The @cite{gnatchop} command has the form:
2727 @example
2728 $ gnatchop switches file_name [file_name ...]
2729       [directory]
2730 @end example
2732 The only required argument is the file name of the file to be chopped.
2733 There are no restrictions on the form of this file name. The file itself
2734 contains one or more Ada units, in normal GNAT format, concatenated
2735 together. As shown, more than one file may be presented to be chopped.
2737 When run in default mode, @cite{gnatchop} generates one output file in
2738 the current directory for each unit in each of the files.
2740 @cite{directory}, if specified, gives the name of the directory to which
2741 the output files will be written. If it is not specified, all files are
2742 written to the current directory.
2744 For example, given a
2745 file called @code{hellofiles} containing
2747 @example
2748 procedure Hello;
2750 with Ada.Text_IO; use Ada.Text_IO;
2751 procedure Hello is
2752 begin
2753    Put_Line ("Hello");
2754 end Hello;
2755 @end example
2757 the command
2759 @example
2760 $ gnatchop hellofiles
2761 @end example
2763 generates two files in the current directory, one called
2764 @code{hello.ads} containing the single line that is the procedure spec,
2765 and the other called @code{hello.adb} containing the remaining text. The
2766 original file is not affected. The generated files can be compiled in
2767 the normal manner.
2769 When gnatchop is invoked on a file that is empty or that contains only empty
2770 lines and/or comments, gnatchop will not fail, but will not produce any
2771 new sources.
2773 For example, given a
2774 file called @code{toto.txt} containing
2776 @example
2777 --  Just a comment
2778 @end example
2780 the command
2782 @example
2783 $ gnatchop toto.txt
2784 @end example
2786 will not produce any new file and will result in the following warnings:
2788 @example
2789 toto.txt:1:01: warning: empty file, contains no compilation units
2790 no compilation units found
2791 no source files written
2792 @end example
2794 @node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2795 @anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{73}@anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{74}
2796 @subsubsection Switches for @cite{gnatchop}
2799 @emph{gnatchop} recognizes the following switches:
2801 @geindex --version (gnatchop)
2804 @table @asis
2806 @item @code{--version}
2808 Display Copyright and version, then exit disregarding all other options.
2809 @end table
2811 @geindex --help (gnatchop)
2814 @table @asis
2816 @item @code{--help}
2818 If @emph{--version} was not used, display usage, then exit disregarding
2819 all other options.
2820 @end table
2822 @geindex -c (gnatchop)
2825 @table @asis
2827 @item @code{-c}
2829 Causes @cite{gnatchop} to operate in compilation mode, in which
2830 configuration pragmas are handled according to strict RM rules. See
2831 previous section for a full description of this mode.
2833 @item @code{-gnat@emph{xxx}}
2835 This passes the given @emph{-gnat`xxx*` switch to `gnat` which is
2836 used to parse the given file. Not all `xxx` options make sense,
2837 but for example, the use of *-gnati2} allows @cite{gnatchop} to
2838 process a source file that uses Latin-2 coding for identifiers.
2840 @item @code{-h}
2842 Causes @cite{gnatchop} to generate a brief help summary to the standard
2843 output file showing usage information.
2844 @end table
2846 @geindex -k (gnatchop)
2849 @table @asis
2851 @item @code{-k@emph{mm}}
2853 Limit generated file names to the specified number @cite{mm}
2854 of characters.
2855 This is useful if the
2856 resulting set of files is required to be interoperable with systems
2857 which limit the length of file names.
2858 No space is allowed between the @emph{-k} and the numeric value. The numeric
2859 value may be omitted in which case a default of @emph{-k8},
2860 suitable for use
2861 with DOS-like file systems, is used. If no @emph{-k} switch
2862 is present then
2863 there is no limit on the length of file names.
2864 @end table
2866 @geindex -p (gnatchop)
2869 @table @asis
2871 @item @code{-p}
2873 Causes the file modification time stamp of the input file to be
2874 preserved and used for the time stamp of the output file(s). This may be
2875 useful for preserving coherency of time stamps in an environment where
2876 @cite{gnatchop} is used as part of a standard build process.
2877 @end table
2879 @geindex -q (gnatchop)
2882 @table @asis
2884 @item @code{-q}
2886 Causes output of informational messages indicating the set of generated
2887 files to be suppressed. Warnings and error messages are unaffected.
2888 @end table
2890 @geindex -r (gnatchop)
2892 @geindex Source_Reference pragmas
2895 @table @asis
2897 @item @code{-r}
2899 Generate @cite{Source_Reference} pragmas. Use this switch if the output
2900 files are regarded as temporary and development is to be done in terms
2901 of the original unchopped file. This switch causes
2902 @cite{Source_Reference} pragmas to be inserted into each of the
2903 generated files to refers back to the original file name and line number.
2904 The result is that all error messages refer back to the original
2905 unchopped file.
2906 In addition, the debugging information placed into the object file (when
2907 the @emph{-g} switch of @emph{gcc} or @emph{gnatmake} is
2908 specified)
2909 also refers back to this original file so that tools like profilers and
2910 debuggers will give information in terms of the original unchopped file.
2912 If the original file to be chopped itself contains
2913 a @cite{Source_Reference}
2914 pragma referencing a third file, then gnatchop respects
2915 this pragma, and the generated @cite{Source_Reference} pragmas
2916 in the chopped file refer to the original file, with appropriate
2917 line numbers. This is particularly useful when @cite{gnatchop}
2918 is used in conjunction with @cite{gnatprep} to compile files that
2919 contain preprocessing statements and multiple units.
2920 @end table
2922 @geindex -v (gnatchop)
2925 @table @asis
2927 @item @code{-v}
2929 Causes @cite{gnatchop} to operate in verbose mode. The version
2930 number and copyright notice are output, as well as exact copies of
2931 the gnat1 commands spawned to obtain the chop control information.
2932 @end table
2934 @geindex -w (gnatchop)
2937 @table @asis
2939 @item @code{-w}
2941 Overwrite existing file names. Normally @cite{gnatchop} regards it as a
2942 fatal error if there is already a file with the same name as a
2943 file it would otherwise output, in other words if the files to be
2944 chopped contain duplicated units. This switch bypasses this
2945 check, and causes all but the last instance of such duplicated
2946 units to be skipped.
2947 @end table
2949 @geindex --GCC= (gnatchop)
2952 @table @asis
2954 @item @code{--GCC=@emph{xxxx}}
2956 Specify the path of the GNAT parser to be used. When this switch is used,
2957 no attempt is made to add the prefix to the GNAT parser executable.
2958 @end table
2960 @node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
2961 @anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{75}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{76}
2962 @subsubsection Examples of @cite{gnatchop} Usage
2965 @example
2966 $ gnatchop -w hello_s.ada prerelease/files
2967 @end example
2969 Chops the source file @code{hello_s.ada}. The output files will be
2970 placed in the directory @code{prerelease/files},
2971 overwriting any
2972 files with matching names in that directory (no files in the current
2973 directory are modified).
2975 @example
2976 $ gnatchop archive
2977 @end example
2979 Chops the source file @code{archive}
2980 into the current directory. One
2981 useful application of @cite{gnatchop} is in sending sets of sources
2982 around, for example in email messages. The required sources are simply
2983 concatenated (for example, using a Unix @cite{cat}
2984 command), and then
2985 @emph{gnatchop} is used at the other end to reconstitute the original
2986 file names.
2988 @example
2989 $ gnatchop file1 file2 file3 direc
2990 @end example
2992 Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
2993 the resulting files in the directory @code{direc}. Note that if any units
2994 occur more than once anywhere within this set of files, an error message
2995 is generated, and no files are written. To override this check, use the
2996 @emph{-w} switch,
2997 in which case the last occurrence in the last file will
2998 be the one that is output, and earlier duplicate occurrences for a given
2999 unit will be skipped.
3001 @node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
3002 @anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{14}
3003 @section Configuration Pragmas
3006 @geindex Configuration pragmas
3008 @geindex Pragmas
3009 @geindex configuration
3011 Configuration pragmas include those pragmas described as
3012 such in the Ada Reference Manual, as well as
3013 implementation-dependent pragmas that are configuration pragmas.
3014 See the @cite{Implementation_Defined_Pragmas} chapter in the
3015 @cite{GNAT_Reference_Manual} for details on these
3016 additional GNAT-specific configuration pragmas.
3017 Most notably, the pragma @cite{Source_File_Name}, which allows
3018 specifying non-default names for source files, is a configuration
3019 pragma. The following is a complete list of configuration pragmas
3020 recognized by GNAT:
3022 @example
3023 Ada_83
3024 Ada_95
3025 Ada_05
3026 Ada_2005
3027 Ada_12
3028 Ada_2012
3029 Allow_Integer_Address
3030 Annotate
3031 Assertion_Policy
3032 Assume_No_Invalid_Values
3033 C_Pass_By_Copy
3034 Check_Name
3035 Check_Policy
3036 Compile_Time_Error
3037 Compile_Time_Warning
3038 Compiler_Unit
3039 Component_Alignment
3040 Convention_Identifier
3041 Debug_Policy
3042 Detect_Blocking
3043 Default_Storage_Pool
3044 Discard_Names
3045 Elaboration_Checks
3046 Eliminate
3047 Extend_System
3048 Extensions_Allowed
3049 External_Name_Casing
3050 Fast_Math
3051 Favor_Top_Level
3052 Float_Representation
3053 Implicit_Packing
3054 Initialize_Scalars
3055 Interrupt_State
3056 License
3057 Locking_Policy
3058 Long_Float
3059 No_Run_Time
3060 No_Strict_Aliasing
3061 Normalize_Scalars
3062 Optimize_Alignment
3063 Persistent_BSS
3064 Polling
3065 Priority_Specific_Dispatching
3066 Profile
3067 Profile_Warnings
3068 Propagate_Exceptions
3069 Queuing_Policy
3070 Ravenscar
3071 Restricted_Run_Time
3072 Restrictions
3073 Restrictions_Warnings
3074 Reviewable
3075 Short_Circuit_And_Or
3076 Source_File_Name
3077 Source_File_Name_Project
3078 SPARK_Mode
3079 Style_Checks
3080 Suppress
3081 Suppress_Exception_Locations
3082 Task_Dispatching_Policy
3083 Universal_Data
3084 Unsuppress
3085 Use_VADS_Size
3086 Validity_Checks
3087 Warnings
3088 Wide_Character_Encoding
3089 @end example
3091 @menu
3092 * Handling of Configuration Pragmas:: 
3093 * The Configuration Pragmas Files:: 
3095 @end menu
3097 @node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
3098 @anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{78}@anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{56}
3099 @subsection Handling of Configuration Pragmas
3102 Configuration pragmas may either appear at the start of a compilation
3103 unit, or they can appear in a configuration pragma file to apply to
3104 all compilations performed in a given compilation environment.
3106 GNAT also provides the @cite{gnatchop} utility to provide an automatic
3107 way to handle configuration pragmas following the semantics for
3108 compilations (that is, files with multiple units), described in the RM.
3109 See @ref{6f,,Operating gnatchop in Compilation Mode} for details.
3110 However, for most purposes, it will be more convenient to edit the
3111 @code{gnat.adc} file that contains configuration pragmas directly,
3112 as described in the following section.
3114 In the case of @cite{Restrictions} pragmas appearing as configuration
3115 pragmas in individual compilation units, the exact handling depends on
3116 the type of restriction.
3118 Restrictions that require partition-wide consistency (like
3119 @cite{No_Tasking}) are
3120 recognized wherever they appear
3121 and can be freely inherited, e.g. from a @emph{with}ed unit to the @emph{with}ing
3122 unit. This makes sense since the binder will in any case insist on seeing
3123 consistent use, so any unit not conforming to any restrictions that are
3124 anywhere in the partition will be rejected, and you might as well find
3125 that out at compile time rather than at bind time.
3127 For restrictions that do not require partition-wide consistency, e.g.
3128 SPARK or No_Implementation_Attributes, in general the restriction applies
3129 only to the unit in which the pragma appears, and not to any other units.
3131 The exception is No_Elaboration_Code which always applies to the entire
3132 object file from a compilation, i.e. to the body, spec, and all subunits.
3133 This restriction can be specified in a configuration pragma file, or it
3134 can be on the body and/or the spec (in eithe case it applies to all the
3135 relevant units). It can appear on a subunit only if it has previously
3136 appeared in the body of spec.
3138 @node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
3139 @anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{79}@anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{7a}
3140 @subsection The Configuration Pragmas Files
3143 @geindex gnat.adc
3145 In GNAT a compilation environment is defined by the current
3146 directory at the time that a compile command is given. This current
3147 directory is searched for a file whose name is @code{gnat.adc}. If
3148 this file is present, it is expected to contain one or more
3149 configuration pragmas that will be applied to the current compilation.
3150 However, if the switch @emph{-gnatA} is used, @code{gnat.adc} is not
3151 considered. When taken into account, @code{gnat.adc} is added to the
3152 dependencies, so that if @code{gnat.adc} is modified later, an invocation of
3153 @emph{gnatmake} will recompile the source.
3155 Configuration pragmas may be entered into the @code{gnat.adc} file
3156 either by running @cite{gnatchop} on a source file that consists only of
3157 configuration pragmas, or more conveniently by direct editing of the
3158 @code{gnat.adc} file, which is a standard format source file.
3160 Besides @code{gnat.adc}, additional files containing configuration
3161 pragmas may be applied to the current compilation using the switch
3162 @code{-gnatec=@emph{path}} where @cite{path} must designate an existing file that
3163 contains only configuration pragmas. These configuration pragmas are
3164 in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
3165 is present and switch @emph{-gnatA} is not used).
3167 It is allowable to specify several switches @emph{-gnatec=}, all of which
3168 will be taken into account.
3170 Files containing configuration pragmas specified with switches
3171 @emph{-gnatec=} are added to the dependencies, unless they are
3172 temporary files. A file is considered temporary if its name ends in
3173 @code{.tmp} or @code{.TMP}. Certain tools follow this naming
3174 convention because they pass information to @emph{gcc} via
3175 temporary files that are immediately deleted; it doesn't make sense to
3176 depend on a file that no longer exists. Such tools include
3177 @emph{gprbuild}, @emph{gnatmake}, and @emph{gnatcheck}.
3179 If you are using project file, a separate mechanism is provided using
3180 project attributes.
3182 @c --Comment:
3183 @c See :ref:`Specifying_Configuration_Pragmas` for more details.
3185 @node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
3186 @anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{7b}
3187 @section Generating Object Files
3190 An Ada program consists of a set of source files, and the first step in
3191 compiling the program is to generate the corresponding object files.
3192 These are generated by compiling a subset of these source files.
3193 The files you need to compile are the following:
3196 @itemize *
3198 @item 
3199 If a package spec has no body, compile the package spec to produce the
3200 object file for the package.
3202 @item 
3203 If a package has both a spec and a body, compile the body to produce the
3204 object file for the package. The source file for the package spec need
3205 not be compiled in this case because there is only one object file, which
3206 contains the code for both the spec and body of the package.
3208 @item 
3209 For a subprogram, compile the subprogram body to produce the object file
3210 for the subprogram. The spec, if one is present, is as usual in a
3211 separate file, and need not be compiled.
3212 @end itemize
3214 @geindex Subunits
3217 @itemize *
3219 @item 
3220 In the case of subunits, only compile the parent unit. A single object
3221 file is generated for the entire subunit tree, which includes all the
3222 subunits.
3224 @item 
3225 Compile child units independently of their parent units
3226 (though, of course, the spec of all the ancestor unit must be present in order
3227 to compile a child unit).
3229 @geindex Generics
3231 @item 
3232 Compile generic units in the same manner as any other units. The object
3233 files in this case are small dummy files that contain at most the
3234 flag used for elaboration checking. This is because GNAT always handles generic
3235 instantiation by means of macro expansion. However, it is still necessary to
3236 compile generic units, for dependency checking and elaboration purposes.
3237 @end itemize
3239 The preceding rules describe the set of files that must be compiled to
3240 generate the object files for a program. Each object file has the same
3241 name as the corresponding source file, except that the extension is
3242 @code{.o} as usual.
3244 You may wish to compile other files for the purpose of checking their
3245 syntactic and semantic correctness. For example, in the case where a
3246 package has a separate spec and body, you would not normally compile the
3247 spec. However, it is convenient in practice to compile the spec to make
3248 sure it is error-free before compiling clients of this spec, because such
3249 compilations will fail if there is an error in the spec.
3251 GNAT provides an option for compiling such files purely for the
3252 purposes of checking correctness; such compilations are not required as
3253 part of the process of building a program. To compile a file in this
3254 checking mode, use the @emph{-gnatc} switch.
3256 @node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3257 @anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{7c}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{41}
3258 @section Source Dependencies
3261 A given object file clearly depends on the source file which is compiled
3262 to produce it. Here we are using "depends" in the sense of a typical
3263 @cite{make} utility; in other words, an object file depends on a source
3264 file if changes to the source file require the object file to be
3265 recompiled.
3266 In addition to this basic dependency, a given object may depend on
3267 additional source files as follows:
3270 @itemize *
3272 @item 
3273 If a file being compiled @emph{with}s a unit @cite{X}, the object file
3274 depends on the file containing the spec of unit @cite{X}. This includes
3275 files that are @emph{with}ed implicitly either because they are parents
3276 of @emph{with}ed child units or they are run-time units required by the
3277 language constructs used in a particular unit.
3279 @item 
3280 If a file being compiled instantiates a library level generic unit, the
3281 object file depends on both the spec and body files for this generic
3282 unit.
3284 @item 
3285 If a file being compiled instantiates a generic unit defined within a
3286 package, the object file depends on the body file for the package as
3287 well as the spec file.
3288 @end itemize
3290 @geindex Inline
3292 @geindex -gnatn switch
3295 @itemize *
3297 @item 
3298 If a file being compiled contains a call to a subprogram for which
3299 pragma @cite{Inline} applies and inlining is activated with the
3300 @emph{-gnatn} switch, the object file depends on the file containing the
3301 body of this subprogram as well as on the file containing the spec. Note
3302 that for inlining to actually occur as a result of the use of this switch,
3303 it is necessary to compile in optimizing mode.
3305 @geindex -gnatN switch
3307 The use of @emph{-gnatN} activates  inlining optimization
3308 that is performed by the front end of the compiler. This inlining does
3309 not require that the code generation be optimized. Like @emph{-gnatn},
3310 the use of this switch generates additional dependencies.
3312 When using a gcc-based back end (in practice this means using any version
3313 of GNAT other than for the JVM, .NET or GNAAMP platforms), then the use of
3314 @emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
3315 Historically front end inlining was more extensive than the gcc back end
3316 inlining, but that is no longer the case.
3318 @item 
3319 If an object file @code{O} depends on the proper body of a subunit through
3320 inlining or instantiation, it depends on the parent unit of the subunit.
3321 This means that any modification of the parent unit or one of its subunits
3322 affects the compilation of @code{O}.
3324 @item 
3325 The object file for a parent unit depends on all its subunit body files.
3327 @item 
3328 The previous two rules meant that for purposes of computing dependencies and
3329 recompilation, a body and all its subunits are treated as an indivisible whole.
3331 These rules are applied transitively: if unit @cite{A} @emph{with}s
3332 unit @cite{B}, whose elaboration calls an inlined procedure in package
3333 @cite{C}, the object file for unit @cite{A} will depend on the body of
3334 @cite{C}, in file @code{c.adb}.
3336 The set of dependent files described by these rules includes all the
3337 files on which the unit is semantically dependent, as dictated by the
3338 Ada language standard. However, it is a superset of what the
3339 standard describes, because it includes generic, inline, and subunit
3340 dependencies.
3342 An object file must be recreated by recompiling the corresponding source
3343 file if any of the source files on which it depends are modified. For
3344 example, if the @cite{make} utility is used to control compilation,
3345 the rule for an Ada object file must mention all the source files on
3346 which the object file depends, according to the above definition.
3347 The determination of the necessary
3348 recompilations is done automatically when one uses @emph{gnatmake}.
3349 @end itemize
3351 @node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3352 @anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{7d}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{42}
3353 @section The Ada Library Information Files
3356 @geindex Ada Library Information files
3358 @geindex ALI files
3360 Each compilation actually generates two output files. The first of these
3361 is the normal object file that has a @code{.o} extension. The second is a
3362 text file containing full dependency information. It has the same
3363 name as the source file, but an @code{.ali} extension.
3364 This file is known as the Ada Library Information (@code{ALI}) file.
3365 The following information is contained in the @code{ALI} file.
3368 @itemize *
3370 @item 
3371 Version information (indicates which version of GNAT was used to compile
3372 the unit(s) in question)
3374 @item 
3375 Main program information (including priority and time slice settings,
3376 as well as the wide character encoding used during compilation).
3378 @item 
3379 List of arguments used in the @emph{gcc} command for the compilation
3381 @item 
3382 Attributes of the unit, including configuration pragmas used, an indication
3383 of whether the compilation was successful, exception model used etc.
3385 @item 
3386 A list of relevant restrictions applying to the unit (used for consistency)
3387 checking.
3389 @item 
3390 Categorization information (e.g., use of pragma @cite{Pure}).
3392 @item 
3393 Information on all @emph{with}ed units, including presence of
3394 Elaborate` or @cite{Elaborate_All} pragmas.
3396 @item 
3397 Information from any @cite{Linker_Options} pragmas used in the unit
3399 @item 
3400 Information on the use of @cite{Body_Version} or @cite{Version}
3401 attributes in the unit.
3403 @item 
3404 Dependency information. This is a list of files, together with
3405 time stamp and checksum information. These are files on which
3406 the unit depends in the sense that recompilation is required
3407 if any of these units are modified.
3409 @item 
3410 Cross-reference data. Contains information on all entities referenced
3411 in the unit. Used by tools like @cite{gnatxref} and @cite{gnatfind} to
3412 provide cross-reference information.
3413 @end itemize
3415 For a full detailed description of the format of the @code{ALI} file,
3416 see the source of the body of unit @cite{Lib.Writ}, contained in file
3417 @code{lib-writ.adb} in the GNAT compiler sources.
3419 @node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3420 @anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{7e}@anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{43}
3421 @section Binding an Ada Program
3424 When using languages such as C and C++, once the source files have been
3425 compiled the only remaining step in building an executable program
3426 is linking the object modules together. This means that it is possible to
3427 link an inconsistent version of a program, in which two units have
3428 included different versions of the same header.
3430 The rules of Ada do not permit such an inconsistent program to be built.
3431 For example, if two clients have different versions of the same package,
3432 it is illegal to build a program containing these two clients.
3433 These rules are enforced by the GNAT binder, which also determines an
3434 elaboration order consistent with the Ada rules.
3436 The GNAT binder is run after all the object files for a program have
3437 been created. It is given the name of the main program unit, and from
3438 this it determines the set of units required by the program, by reading the
3439 corresponding ALI files. It generates error messages if the program is
3440 inconsistent or if no valid order of elaboration exists.
3442 If no errors are detected, the binder produces a main program, in Ada by
3443 default, that contains calls to the elaboration procedures of those
3444 compilation unit that require them, followed by
3445 a call to the main program. This Ada program is compiled to generate the
3446 object file for the main program. The name of
3447 the Ada file is @code{b~xxx}.adb` (with the corresponding spec
3448 @code{b~xxx}.ads`) where @cite{xxx} is the name of the
3449 main program unit.
3451 Finally, the linker is used to build the resulting executable program,
3452 using the object from the main program from the bind step as well as the
3453 object files for the Ada units of the program.
3455 @node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3456 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{15}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{7f}
3457 @section GNAT and Libraries
3460 @geindex Library building and using
3462 This section describes how to build and use libraries with GNAT, and also shows
3463 how to recompile the GNAT run-time library. You should be familiar with the
3464 Project Manager facility (see the @emph{GNAT_Project_Manager} chapter of the
3465 @emph{GPRbuild User's Guide}) before reading this chapter.
3467 @menu
3468 * Introduction to Libraries in GNAT:: 
3469 * General Ada Libraries:: 
3470 * Stand-alone Ada Libraries:: 
3471 * Rebuilding the GNAT Run-Time Library:: 
3473 @end menu
3475 @node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3476 @anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{80}@anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{81}
3477 @subsection Introduction to Libraries in GNAT
3480 A library is, conceptually, a collection of objects which does not have its
3481 own main thread of execution, but rather provides certain services to the
3482 applications that use it. A library can be either statically linked with the
3483 application, in which case its code is directly included in the application,
3484 or, on platforms that support it, be dynamically linked, in which case
3485 its code is shared by all applications making use of this library.
3487 GNAT supports both types of libraries.
3488 In the static case, the compiled code can be provided in different ways. The
3489 simplest approach is to provide directly the set of objects resulting from
3490 compilation of the library source files. Alternatively, you can group the
3491 objects into an archive using whatever commands are provided by the operating
3492 system. For the latter case, the objects are grouped into a shared library.
3494 In the GNAT environment, a library has three types of components:
3497 @itemize *
3499 @item 
3500 Source files,
3502 @item 
3503 @code{ALI} files (see @ref{42,,The Ada Library Information Files}), and
3505 @item 
3506 Object files, an archive or a shared library.
3507 @end itemize
3509 A GNAT library may expose all its source files, which is useful for
3510 documentation purposes. Alternatively, it may expose only the units needed by
3511 an external user to make use of the library. That is to say, the specs
3512 reflecting the library services along with all the units needed to compile
3513 those specs, which can include generic bodies or any body implementing an
3514 inlined routine. In the case of @emph{stand-alone libraries} those exposed
3515 units are called @emph{interface units} (@ref{82,,Stand-alone Ada Libraries}).
3517 All compilation units comprising an application, including those in a library,
3518 need to be elaborated in an order partially defined by Ada's semantics. GNAT
3519 computes the elaboration order from the @code{ALI} files and this is why they
3520 constitute a mandatory part of GNAT libraries.
3521 @emph{Stand-alone libraries} are the exception to this rule because a specific
3522 library elaboration routine is produced independently of the application(s)
3523 using the library.
3525 @node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3526 @anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{83}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{84}
3527 @subsection General Ada Libraries
3530 @menu
3531 * Building a library:: 
3532 * Installing a library:: 
3533 * Using a library:: 
3535 @end menu
3537 @node Building a library,Installing a library,,General Ada Libraries
3538 @anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{85}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{86}
3539 @subsubsection Building a library
3542 The easiest way to build a library is to use the Project Manager,
3543 which supports a special type of project called a @emph{Library Project}
3544 (see the @emph{Library Projects} section in the @emph{GNAT Project Manager}
3545 chapter of the @emph{GPRbuild User's Guide}).
3547 A project is considered a library project, when two project-level attributes
3548 are defined in it: @cite{Library_Name} and @cite{Library_Dir}. In order to
3549 control different aspects of library configuration, additional optional
3550 project-level attributes can be specified:
3553 @itemize *
3555 @item 
3557 @table @asis
3559 @item @emph{Library_Kind}
3561 This attribute controls whether the library is to be static or dynamic
3562 @end table
3564 @item 
3566 @table @asis
3568 @item @emph{Library_Version}
3570 This attribute specifies the library version; this value is used
3571 during dynamic linking of shared libraries to determine if the currently
3572 installed versions of the binaries are compatible.
3573 @end table
3575 @item 
3576 @emph{Library_Options}
3578 @item 
3580 @table @asis
3582 @item @emph{Library_GCC}
3584 These attributes specify additional low-level options to be used during
3585 library generation, and redefine the actual application used to generate
3586 library.
3587 @end table
3588 @end itemize
3590 The GNAT Project Manager takes full care of the library maintenance task,
3591 including recompilation of the source files for which objects do not exist
3592 or are not up to date, assembly of the library archive, and installation of
3593 the library (i.e., copying associated source, object and @code{ALI} files
3594 to the specified location).
3596 Here is a simple library project file:
3598 @example
3599 project My_Lib is
3600   for Source_Dirs use ("src1", "src2");
3601   for Object_Dir use "obj";
3602   for Library_Name use "mylib";
3603   for Library_Dir use "lib";
3604   for Library_Kind use "dynamic";
3605 end My_lib;
3606 @end example
3608 and the compilation command to build and install the library:
3610 @example
3611 $ gnatmake -Pmy_lib
3612 @end example
3614 It is not entirely trivial to perform manually all the steps required to
3615 produce a library. We recommend that you use the GNAT Project Manager
3616 for this task. In special cases where this is not desired, the necessary
3617 steps are discussed below.
3619 There are various possibilities for compiling the units that make up the
3620 library: for example with a Makefile (@ref{1f,,Using the GNU make Utility}) or
3621 with a conventional script. For simple libraries, it is also possible to create
3622 a dummy main program which depends upon all the packages that comprise the
3623 interface of the library. This dummy main program can then be given to
3624 @emph{gnatmake}, which will ensure that all necessary objects are built.
3626 After this task is accomplished, you should follow the standard procedure
3627 of the underlying operating system to produce the static or shared library.
3629 Here is an example of such a dummy program:
3631 @example
3632 with My_Lib.Service1;
3633 with My_Lib.Service2;
3634 with My_Lib.Service3;
3635 procedure My_Lib_Dummy is
3636 begin
3637    null;
3638 end;
3639 @end example
3641 Here are the generic commands that will build an archive or a shared library.
3643 @example
3644 # compiling the library
3645 $ gnatmake -c my_lib_dummy.adb
3647 # we don't need the dummy object itself
3648 $ rm my_lib_dummy.o my_lib_dummy.ali
3650 # create an archive with the remaining objects
3651 $ ar rc libmy_lib.a *.o
3652 # some systems may require "ranlib" to be run as well
3654 # or create a shared library
3655 $ gcc -shared -o libmy_lib.so *.o
3656 # some systems may require the code to have been compiled with -fPIC
3658 # remove the object files that are now in the library
3659 $ rm *.o
3661 # Make the ALI files read-only so that gnatmake will not try to
3662 # regenerate the objects that are in the library
3663 $ chmod -w *.ali
3664 @end example
3666 Please note that the library must have a name of the form @code{lib@emph{xxx}.a}
3667 or @code{lib@emph{xxx}.so} (or @code{lib@emph{xxx}.dll} on Windows) in order to
3668 be accessed by the directive @code{-l@emph{xxx}} at link time.
3670 @node Installing a library,Using a library,Building a library,General Ada Libraries
3671 @anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{87}@anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{88}
3672 @subsubsection Installing a library
3675 @geindex ADA_PROJECT_PATH
3677 @geindex GPR_PROJECT_PATH
3679 If you use project files, library installation is part of the library build
3680 process (see the @emph{Installing a Library with Project Files} section of the
3681 @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}).
3683 When project files are not an option, it is also possible, but not recommended,
3684 to install the library so that the sources needed to use the library are on the
3685 Ada source path and the ALI files & libraries be on the Ada Object path (see
3686 @ref{89,,Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
3687 administrator can place general-purpose libraries in the default compiler
3688 paths, by specifying the libraries' location in the configuration files
3689 @code{ada_source_path} and @code{ada_object_path}. These configuration files
3690 must be located in the GNAT installation tree at the same place as the gcc spec
3691 file. The location of the gcc spec file can be determined as follows:
3693 @example
3694 $ gcc -v
3695 @end example
3697 The configuration files mentioned above have a simple format: each line
3698 must contain one unique directory name.
3699 Those names are added to the corresponding path
3700 in their order of appearance in the file. The names can be either absolute
3701 or relative; in the latter case, they are relative to where theses files
3702 are located.
3704 The files @code{ada_source_path} and @code{ada_object_path} might not be
3705 present in a
3706 GNAT installation, in which case, GNAT will look for its run-time library in
3707 the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3708 objects and @code{ALI} files). When the files exist, the compiler does not
3709 look in @code{adainclude} and @code{adalib}, and thus the
3710 @code{ada_source_path} file
3711 must contain the location for the GNAT run-time sources (which can simply
3712 be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3713 contain the location for the GNAT run-time objects (which can simply
3714 be @code{adalib}).
3716 You can also specify a new default path to the run-time library at compilation
3717 time with the switch @emph{--RTS=rts-path}. You can thus choose / change
3718 the run-time library you want your program to be compiled with. This switch is
3719 recognized by @emph{gcc}, @emph{gnatmake}, @emph{gnatbind},
3720 @emph{gnatls}, @emph{gnatfind} and @emph{gnatxref}.
3722 It is possible to install a library before or after the standard GNAT
3723 library, by reordering the lines in the configuration files. In general, a
3724 library must be installed before the GNAT library if it redefines
3725 any part of it.
3727 @node Using a library,,Installing a library,General Ada Libraries
3728 @anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{8a}@anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{8b}
3729 @subsubsection Using a library
3732 Once again, the project facility greatly simplifies the use of
3733 libraries. In this context, using a library is just a matter of adding a
3734 @emph{with} clause in the user project. For instance, to make use of the
3735 library @cite{My_Lib} shown in examples in earlier sections, you can
3736 write:
3738 @example
3739 with "my_lib";
3740 project My_Proj is
3741   ...
3742 end My_Proj;
3743 @end example
3745 Even if you have a third-party, non-Ada library, you can still use GNAT's
3746 Project Manager facility to provide a wrapper for it. For example, the
3747 following project, when @emph{with}ed by your main project, will link with the
3748 third-party library @code{liba.a}:
3750 @example
3751 project Liba is
3752    for Externally_Built use "true";
3753    for Source_Files use ();
3754    for Library_Dir use "lib";
3755    for Library_Name use "a";
3756    for Library_Kind use "static";
3757 end Liba;
3758 @end example
3760 This is an alternative to the use of @cite{pragma Linker_Options}. It is
3761 especially interesting in the context of systems with several interdependent
3762 static libraries where finding a proper linker order is not easy and best be
3763 left to the tools having visibility over project dependence information.
3765 In order to use an Ada library manually, you need to make sure that this
3766 library is on both your source and object path
3767 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}
3768 and @ref{8c,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3769 in an archive or a shared library, you need to specify the desired
3770 library at link time.
3772 For example, you can use the library @code{mylib} installed in
3773 @code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3775 @example
3776 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3777   -largs -lmy_lib
3778 @end example
3780 This can be expressed more simply:
3782 @example
3783 $ gnatmake my_appl
3784 @end example
3786 when the following conditions are met:
3789 @itemize *
3791 @item 
3792 @code{/dir/my_lib_src} has been added by the user to the environment
3793 variable 
3794 @geindex ADA_INCLUDE_PATH
3795 @geindex environment variable; ADA_INCLUDE_PATH
3796 @code{ADA_INCLUDE_PATH}, or by the administrator to the file
3797 @code{ada_source_path}
3799 @item 
3800 @code{/dir/my_lib_obj} has been added by the user to the environment
3801 variable 
3802 @geindex ADA_OBJECTS_PATH
3803 @geindex environment variable; ADA_OBJECTS_PATH
3804 @code{ADA_OBJECTS_PATH}, or by the administrator to the file
3805 @code{ada_object_path}
3807 @item 
3808 a pragma @cite{Linker_Options} has been added to one of the sources.
3809 For example:
3811 @example
3812 pragma Linker_Options ("-lmy_lib");
3813 @end example
3814 @end itemize
3816 Note that you may also load a library dynamically at
3817 run time given its filename, as illustrated in the GNAT @code{plugins} example
3818 in the directory @code{share/examples/gnat/plugins} within the GNAT
3819 install area.
3821 @node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3822 @anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{82}@anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{8d}
3823 @subsection Stand-alone Ada Libraries
3826 @geindex Stand-alone libraries
3828 @menu
3829 * Introduction to Stand-alone Libraries:: 
3830 * Building a Stand-alone Library:: 
3831 * Creating a Stand-alone Library to be used in a non-Ada context:: 
3832 * Restrictions in Stand-alone Libraries:: 
3834 @end menu
3836 @node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3837 @anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{8e}@anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{8f}
3838 @subsubsection Introduction to Stand-alone Libraries
3841 A Stand-alone Library (abbreviated 'SAL') is a library that contains the
3842 necessary code to
3843 elaborate the Ada units that are included in the library. In contrast with
3844 an ordinary library, which consists of all sources, objects and @code{ALI}
3845 files of the
3846 library, a SAL may specify a restricted subset of compilation units
3847 to serve as a library interface. In this case, the fully
3848 self-sufficient set of files will normally consist of an objects
3849 archive, the sources of interface units' specs, and the @code{ALI}
3850 files of interface units.
3851 If an interface spec contains a generic unit or an inlined subprogram,
3852 the body's
3853 source must also be provided; if the units that must be provided in the source
3854 form depend on other units, the source and @code{ALI} files of those must
3855 also be provided.
3857 The main purpose of a SAL is to minimize the recompilation overhead of client
3858 applications when a new version of the library is installed. Specifically,
3859 if the interface sources have not changed, client applications do not need to
3860 be recompiled. If, furthermore, a SAL is provided in the shared form and its
3861 version, controlled by @cite{Library_Version} attribute, is not changed,
3862 then the clients do not need to be relinked.
3864 SALs also allow the library providers to minimize the amount of library source
3865 text exposed to the clients.  Such 'information hiding' might be useful or
3866 necessary for various reasons.
3868 Stand-alone libraries are also well suited to be used in an executable whose
3869 main routine is not written in Ada.
3871 @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
3872 @anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{90}@anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{91}
3873 @subsubsection Building a Stand-alone Library
3876 GNAT's Project facility provides a simple way of building and installing
3877 stand-alone libraries; see the @emph{Stand-alone Library Projects} section
3878 in the @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}.
3879 To be a Stand-alone Library Project, in addition to the two attributes
3880 that make a project a Library Project (@cite{Library_Name} and
3881 @cite{Library_Dir}; see the @emph{Library Projects} section in the
3882 @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}),
3883 the attribute @cite{Library_Interface} must be defined.  For example:
3885 @example
3886 for Library_Dir use "lib_dir";
3887 for Library_Name use "dummy";
3888 for Library_Interface use ("int1", "int1.child");
3889 @end example
3891 Attribute @cite{Library_Interface} has a non-empty string list value,
3892 each string in the list designating a unit contained in an immediate source
3893 of the project file.
3895 When a Stand-alone Library is built, first the binder is invoked to build
3896 a package whose name depends on the library name
3897 (@code{b~dummy.ads/b} in the example above).
3898 This binder-generated package includes initialization and
3899 finalization procedures whose
3900 names depend on the library name (@cite{dummyinit} and @cite{dummyfinal}
3901 in the example
3902 above). The object corresponding to this package is included in the library.
3904 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
3905 calling of these procedures if a static SAL is built, or if a shared SAL
3906 is built
3907 with the project-level attribute @cite{Library_Auto_Init} set to
3908 @cite{"false"}.
3910 For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
3911 (those that are listed in attribute @cite{Library_Interface}) are copied to
3912 the Library Directory. As a consequence, only the Interface Units may be
3913 imported from Ada units outside of the library. If other units are imported,
3914 the binding phase will fail.
3916 It is also possible to build an encapsulated library where not only
3917 the code to elaborate and finalize the library is embedded but also
3918 ensuring that the library is linked only against static
3919 libraries. So an encapsulated library only depends on system
3920 libraries, all other code, including the GNAT runtime, is embedded. To
3921 build an encapsulated library the attribute
3922 @cite{Library_Standalone} must be set to @cite{encapsulated}:
3924 @example
3925 for Library_Dir use "lib_dir";
3926 for Library_Name use "dummy";
3927 for Library_Kind use "dynamic";
3928 for Library_Interface use ("int1", "int1.child");
3929 for Library_Standalone use "encapsulated";
3930 @end example
3932 The default value for this attribute is @cite{standard} in which case
3933 a stand-alone library is built.
3935 The attribute @cite{Library_Src_Dir} may be specified for a
3936 Stand-Alone Library. @cite{Library_Src_Dir} is a simple attribute that has a
3937 single string value. Its value must be the path (absolute or relative to the
3938 project directory) of an existing directory. This directory cannot be the
3939 object directory or one of the source directories, but it can be the same as
3940 the library directory. The sources of the Interface
3941 Units of the library that are needed by an Ada client of the library will be
3942 copied to the designated directory, called the Interface Copy directory.
3943 These sources include the specs of the Interface Units, but they may also
3944 include bodies and subunits, when pragmas @cite{Inline} or @cite{Inline_Always}
3945 are used, or when there is a generic unit in the spec. Before the sources
3946 are copied to the Interface Copy directory, an attempt is made to delete all
3947 files in the Interface Copy directory.
3949 Building stand-alone libraries by hand is somewhat tedious, but for those
3950 occasions when it is necessary here are the steps that you need to perform:
3953 @itemize *
3955 @item 
3956 Compile all library sources.
3958 @item 
3959 Invoke the binder with the switch @emph{-n} (No Ada main program),
3960 with all the @code{ALI} files of the interfaces, and
3961 with the switch @emph{-L} to give specific names to the @cite{init}
3962 and @cite{final} procedures.  For example:
3964 @example
3965 $ gnatbind -n int1.ali int2.ali -Lsal1
3966 @end example
3968 @item 
3969 Compile the binder generated file:
3971 @example
3972 $ gcc -c b~int2.adb
3973 @end example
3975 @item 
3976 Link the dynamic library with all the necessary object files,
3977 indicating to the linker the names of the @cite{init} (and possibly
3978 @cite{final}) procedures for automatic initialization (and finalization).
3979 The built library should be placed in a directory different from
3980 the object directory.
3982 @item 
3983 Copy the @cite{ALI} files of the interface to the library directory,
3984 add in this copy an indication that it is an interface to a SAL
3985 (i.e., add a word @emph{SL} on the line in the @code{ALI} file that starts
3986 with letter 'P') and make the modified copy of the @code{ALI} file
3987 read-only.
3988 @end itemize
3990 Using SALs is not different from using other libraries
3991 (see @ref{8a,,Using a library}).
3993 @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
3994 @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}
3995 @subsubsection Creating a Stand-alone Library to be used in a non-Ada context
3998 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
3999 a non-Ada context.
4001 The only extra step required is to ensure that library interface subprograms
4002 are compatible with the main program, by means of @cite{pragma Export}
4003 or @cite{pragma Convention}.
4005 Here is an example of simple library interface for use with C main program:
4007 @example
4008 package My_Package is
4010    procedure Do_Something;
4011    pragma Export (C, Do_Something, "do_something");
4013    procedure Do_Something_Else;
4014    pragma Export (C, Do_Something_Else, "do_something_else");
4016 end My_Package;
4017 @end example
4019 On the foreign language side, you must provide a 'foreign' view of the
4020 library interface; remember that it should contain elaboration routines in
4021 addition to interface subprograms.
4023 The example below shows the content of @cite{mylib_interface.h} (note
4024 that there is no rule for the naming of this file, any name can be used)
4026 @example
4027 /* the library elaboration procedure */
4028 extern void mylibinit (void);
4030 /* the library finalization procedure */
4031 extern void mylibfinal (void);
4033 /* the interface exported by the library */
4034 extern void do_something (void);
4035 extern void do_something_else (void);
4036 @end example
4038 Libraries built as explained above can be used from any program, provided
4039 that the elaboration procedures (named @cite{mylibinit} in the previous
4040 example) are called before the library services are used. Any number of
4041 libraries can be used simultaneously, as long as the elaboration
4042 procedure of each library is called.
4044 Below is an example of a C program that uses the @cite{mylib} library.
4046 @example
4047 #include "mylib_interface.h"
4050 main (void)
4052    /* First, elaborate the library before using it */
4053    mylibinit ();
4055    /* Main program, using the library exported entities */
4056    do_something ();
4057    do_something_else ();
4059    /* Library finalization at the end of the program */
4060    mylibfinal ();
4061    return 0;
4063 @end example
4065 Note that invoking any library finalization procedure generated by
4066 @cite{gnatbind} shuts down the Ada run-time environment.
4067 Consequently, the
4068 finalization of all Ada libraries must be performed at the end of the program.
4069 No call to these libraries or to the Ada run-time library should be made
4070 after the finalization phase.
4072 Note also that special care must be taken with multi-tasks
4073 applications. The initialization and finalization routines are not
4074 protected against concurrent access. If such requirement is needed it
4075 must be ensured at the application level using a specific operating
4076 system services like a mutex or a critical-section.
4078 @node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
4079 @anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{94}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{95}
4080 @subsubsection Restrictions in Stand-alone Libraries
4083 The pragmas listed below should be used with caution inside libraries,
4084 as they can create incompatibilities with other Ada libraries:
4087 @itemize *
4089 @item 
4090 pragma @cite{Locking_Policy}
4092 @item 
4093 pragma @cite{Partition_Elaboration_Policy}
4095 @item 
4096 pragma @cite{Queuing_Policy}
4098 @item 
4099 pragma @cite{Task_Dispatching_Policy}
4101 @item 
4102 pragma @cite{Unreserve_All_Interrupts}
4103 @end itemize
4105 When using a library that contains such pragmas, the user must make sure
4106 that all libraries use the same pragmas with the same values. Otherwise,
4107 @cite{Program_Error} will
4108 be raised during the elaboration of the conflicting
4109 libraries. The usage of these pragmas and its consequences for the user
4110 should therefore be well documented.
4112 Similarly, the traceback in the exception occurrence mechanism should be
4113 enabled or disabled in a consistent manner across all libraries.
4114 Otherwise, Program_Error will be raised during the elaboration of the
4115 conflicting libraries.
4117 If the @cite{Version} or @cite{Body_Version}
4118 attributes are used inside a library, then you need to
4119 perform a @cite{gnatbind} step that specifies all @code{ALI} files in all
4120 libraries, so that version identifiers can be properly computed.
4121 In practice these attributes are rarely used, so this is unlikely
4122 to be a consideration.
4124 @node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
4125 @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}
4126 @subsection Rebuilding the GNAT Run-Time Library
4129 @geindex GNAT Run-Time Library
4130 @geindex rebuilding
4132 @geindex Building the GNAT Run-Time Library
4134 @geindex Rebuilding the GNAT Run-Time Library
4136 @geindex Run-Time Library
4137 @geindex rebuilding
4139 It may be useful to recompile the GNAT library in various contexts, the
4140 most important one being the use of partition-wide configuration pragmas
4141 such as @cite{Normalize_Scalars}. A special Makefile called
4142 @cite{Makefile.adalib} is provided to that effect and can be found in
4143 the directory containing the GNAT library. The location of this
4144 directory depends on the way the GNAT environment has been installed and can
4145 be determined by means of the command:
4147 @example
4148 $ gnatls -v
4149 @end example
4151 The last entry in the object search path usually contains the
4152 gnat library. This Makefile contains its own documentation and in
4153 particular the set of instructions needed to rebuild a new library and
4154 to use it.
4156 @geindex Conditional compilation
4158 @node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
4159 @anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{98}@anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{16}
4160 @section Conditional Compilation
4163 This section presents some guidelines for modeling conditional compilation in Ada and describes the
4164 gnatprep preprocessor utility.
4166 @geindex Conditional compilation
4168 @menu
4169 * Modeling Conditional Compilation in Ada:: 
4170 * Preprocessing with gnatprep:: 
4171 * Integrated Preprocessing:: 
4173 @end menu
4175 @node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
4176 @anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{99}@anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{9a}
4177 @subsection Modeling Conditional Compilation in Ada
4180 It is often necessary to arrange for a single source program
4181 to serve multiple purposes, where it is compiled in different
4182 ways to achieve these different goals. Some examples of the
4183 need for this feature are
4186 @itemize *
4188 @item 
4189 Adapting a program to a different hardware environment
4191 @item 
4192 Adapting a program to a different target architecture
4194 @item 
4195 Turning debugging features on and off
4197 @item 
4198 Arranging for a program to compile with different compilers
4199 @end itemize
4201 In C, or C++, the typical approach would be to use the preprocessor
4202 that is defined as part of the language. The Ada language does not
4203 contain such a feature. This is not an oversight, but rather a very
4204 deliberate design decision, based on the experience that overuse of
4205 the preprocessing features in C and C++ can result in programs that
4206 are extremely difficult to maintain. For example, if we have ten
4207 switches that can be on or off, this means that there are a thousand
4208 separate programs, any one of which might not even be syntactically
4209 correct, and even if syntactically correct, the resulting program
4210 might not work correctly. Testing all combinations can quickly become
4211 impossible.
4213 Nevertheless, the need to tailor programs certainly exists, and in
4214 this section we will discuss how this can
4215 be achieved using Ada in general, and GNAT in particular.
4217 @menu
4218 * Use of Boolean Constants:: 
4219 * Debugging - A Special Case:: 
4220 * Conditionalizing Declarations:: 
4221 * Use of Alternative Implementations:: 
4222 * Preprocessing:: 
4224 @end menu
4226 @node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4227 @anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{9b}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{9c}
4228 @subsubsection Use of Boolean Constants
4231 In the case where the difference is simply which code
4232 sequence is executed, the cleanest solution is to use Boolean
4233 constants to control which code is executed.
4235 @example
4236 FP_Initialize_Required : constant Boolean := True;
4238 if FP_Initialize_Required then
4240 end if;
4241 @end example
4243 Not only will the code inside the @cite{if} statement not be executed if
4244 the constant Boolean is @cite{False}, but it will also be completely
4245 deleted from the program.
4246 However, the code is only deleted after the @cite{if} statement
4247 has been checked for syntactic and semantic correctness.
4248 (In contrast, with preprocessors the code is deleted before the
4249 compiler ever gets to see it, so it is not checked until the switch
4250 is turned on.)
4252 @geindex Preprocessors (contrasted with conditional compilation)
4254 Typically the Boolean constants will be in a separate package,
4255 something like:
4257 @example
4258 package Config is
4259    FP_Initialize_Required : constant Boolean := True;
4260    Reset_Available        : constant Boolean := False;
4261    ...
4262 end Config;
4263 @end example
4265 The @cite{Config} package exists in multiple forms for the various targets,
4266 with an appropriate script selecting the version of @cite{Config} needed.
4267 Then any other unit requiring conditional compilation can do a @emph{with}
4268 of @cite{Config} to make the constants visible.
4270 @node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4271 @anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{9d}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{9e}
4272 @subsubsection Debugging - A Special Case
4275 A common use of conditional code is to execute statements (for example
4276 dynamic checks, or output of intermediate results) under control of a
4277 debug switch, so that the debugging behavior can be turned on and off.
4278 This can be done using a Boolean constant to control whether the code
4279 is active:
4281 @example
4282 if Debugging then
4283    Put_Line ("got to the first stage!");
4284 end if;
4285 @end example
4289 @example
4290 if Debugging and then Temperature > 999.0 then
4291    raise Temperature_Crazy;
4292 end if;
4293 @end example
4295 @geindex pragma Assert
4297 Since this is a common case, there are special features to deal with
4298 this in a convenient manner. For the case of tests, Ada 2005 has added
4299 a pragma @cite{Assert} that can be used for such tests. This pragma is modeled
4300 on the @cite{Assert} pragma that has always been available in GNAT, so this
4301 feature may be used with GNAT even if you are not using Ada 2005 features.
4302 The use of pragma @cite{Assert} is described in the
4303 @cite{GNAT_Reference_Manual}, but as an
4304 example, the last test could be written:
4306 @example
4307 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4308 @end example
4310 or simply
4312 @example
4313 pragma Assert (Temperature <= 999.0);
4314 @end example
4316 In both cases, if assertions are active and the temperature is excessive,
4317 the exception @cite{Assert_Failure} will be raised, with the given string in
4318 the first case or a string indicating the location of the pragma in the second
4319 case used as the exception message.
4321 @geindex pragma Assertion_Policy
4323 You can turn assertions on and off by using the @cite{Assertion_Policy}
4324 pragma.
4326 @geindex -gnata switch
4328 This is an Ada 2005 pragma which is implemented in all modes by
4329 GNAT. Alternatively, you can use the @emph{-gnata} switch
4330 to enable assertions from the command line, which applies to
4331 all versions of Ada.
4333 @geindex pragma Debug
4335 For the example above with the @cite{Put_Line}, the GNAT-specific pragma
4336 @cite{Debug} can be used:
4338 @example
4339 pragma Debug (Put_Line ("got to the first stage!"));
4340 @end example
4342 If debug pragmas are enabled, the argument, which must be of the form of
4343 a procedure call, is executed (in this case, @cite{Put_Line} will be called).
4344 Only one call can be present, but of course a special debugging procedure
4345 containing any code you like can be included in the program and then
4346 called in a pragma @cite{Debug} argument as needed.
4348 One advantage of pragma @cite{Debug} over the @cite{if Debugging then}
4349 construct is that pragma @cite{Debug} can appear in declarative contexts,
4350 such as at the very beginning of a procedure, before local declarations have
4351 been elaborated.
4353 @geindex pragma Debug_Policy
4355 Debug pragmas are enabled using either the @emph{-gnata} switch that also
4356 controls assertions, or with a separate Debug_Policy pragma.
4358 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4359 in Ada 95 and Ada 83 programs as well), and is analogous to
4360 pragma @cite{Assertion_Policy} to control assertions.
4362 @cite{Assertion_Policy} and @cite{Debug_Policy} are configuration pragmas,
4363 and thus they can appear in @code{gnat.adc} if you are not using a
4364 project file, or in the file designated to contain configuration pragmas
4365 in a project file.
4366 They then apply to all subsequent compilations. In practice the use of
4367 the @emph{-gnata} switch is often the most convenient method of controlling
4368 the status of these pragmas.
4370 Note that a pragma is not a statement, so in contexts where a statement
4371 sequence is required, you can't just write a pragma on its own. You have
4372 to add a @cite{null} statement.
4374 @example
4375 if ... then
4376    ... -- some statements
4377 else
4378    pragma Assert (Num_Cases < 10);
4379    null;
4380 end if;
4381 @end example
4383 @node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4384 @anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{9f}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{a0}
4385 @subsubsection Conditionalizing Declarations
4388 In some cases it may be necessary to conditionalize declarations to meet
4389 different requirements. For example we might want a bit string whose length
4390 is set to meet some hardware message requirement.
4392 This may be possible using declare blocks controlled
4393 by conditional constants:
4395 @example
4396 if Small_Machine then
4397    declare
4398       X : Bit_String (1 .. 10);
4399    begin
4400       ...
4401    end;
4402 else
4403    declare
4404       X : Large_Bit_String (1 .. 1000);
4405    begin
4406       ...
4407    end;
4408 end if;
4409 @end example
4411 Note that in this approach, both declarations are analyzed by the
4412 compiler so this can only be used where both declarations are legal,
4413 even though one of them will not be used.
4415 Another approach is to define integer constants, e.g., @cite{Bits_Per_Word},
4416 or Boolean constants, e.g., @cite{Little_Endian}, and then write declarations
4417 that are parameterized by these constants. For example
4419 @example
4420 for Rec use
4421   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4422 end record;
4423 @end example
4425 If @cite{Bits_Per_Word} is set to 32, this generates either
4427 @example
4428 for Rec use
4429   Field1 at 0 range 0 .. 32;
4430 end record;
4431 @end example
4433 for the big endian case, or
4435 @example
4436 for Rec use record
4437     Field1 at 0 range 10 .. 32;
4438 end record;
4439 @end example
4441 for the little endian case. Since a powerful subset of Ada expression
4442 notation is usable for creating static constants, clever use of this
4443 feature can often solve quite difficult problems in conditionalizing
4444 compilation (note incidentally that in Ada 95, the little endian
4445 constant was introduced as @cite{System.Default_Bit_Order}, so you do not
4446 need to define this one yourself).
4448 @node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4449 @anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{a2}
4450 @subsubsection Use of Alternative Implementations
4453 In some cases, none of the approaches described above are adequate. This
4454 can occur for example if the set of declarations required is radically
4455 different for two different configurations.
4457 In this situation, the official Ada way of dealing with conditionalizing
4458 such code is to write separate units for the different cases. As long as
4459 this does not result in excessive duplication of code, this can be done
4460 without creating maintenance problems. The approach is to share common
4461 code as far as possible, and then isolate the code and declarations
4462 that are different. Subunits are often a convenient method for breaking
4463 out a piece of a unit that is to be conditionalized, with separate files
4464 for different versions of the subunit for different targets, where the
4465 build script selects the right one to give to the compiler.
4467 @geindex Subunits (and conditional compilation)
4469 As an example, consider a situation where a new feature in Ada 2005
4470 allows something to be done in a really nice way. But your code must be able
4471 to compile with an Ada 95 compiler. Conceptually you want to say:
4473 @example
4474 if Ada_2005 then
4475    ... neat Ada 2005 code
4476 else
4477    ... not quite as neat Ada 95 code
4478 end if;
4479 @end example
4481 where @cite{Ada_2005} is a Boolean constant.
4483 But this won't work when @cite{Ada_2005} is set to @cite{False},
4484 since the @cite{then} clause will be illegal for an Ada 95 compiler.
4485 (Recall that although such unreachable code would eventually be deleted
4486 by the compiler, it still needs to be legal.  If it uses features
4487 introduced in Ada 2005, it will be illegal in Ada 95.)
4489 So instead we write
4491 @example
4492 procedure Insert is separate;
4493 @end example
4495 Then we have two files for the subunit @cite{Insert}, with the two sets of
4496 code.
4497 If the package containing this is called @cite{File_Queries}, then we might
4498 have two files
4501 @itemize *
4503 @item 
4504 @code{file_queries-insert-2005.adb}
4506 @item 
4507 @code{file_queries-insert-95.adb}
4508 @end itemize
4510 and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4512 This can also be done with project files' naming schemes. For example:
4514 @example
4515 for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4516 @end example
4518 Note also that with project files it is desirable to use a different extension
4519 than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4520 conflict may arise through another commonly used feature: to declare as part
4521 of the project a set of directories containing all the sources obeying the
4522 default naming scheme.
4524 The use of alternative units is certainly feasible in all situations,
4525 and for example the Ada part of the GNAT run-time is conditionalized
4526 based on the target architecture using this approach. As a specific example,
4527 consider the implementation of the AST feature in VMS. There is one
4528 spec: @code{s-asthan.ads} which is the same for all architectures, and three
4529 bodies:
4532 @itemize *
4534 @item 
4536 @table @asis
4538 @item @code{s-asthan.adb}
4540 used for all non-VMS operating systems
4541 @end table
4543 @item 
4545 @table @asis
4547 @item @code{s-asthan-vms-alpha.adb}
4549 used for VMS on the Alpha
4550 @end table
4552 @item 
4554 @table @asis
4556 @item @code{s-asthan-vms-ia64.adb}
4558 used for VMS on the ia64
4559 @end table
4560 @end itemize
4562 The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4563 this operating system feature is not available, and the two remaining
4564 versions interface with the corresponding versions of VMS to provide
4565 VMS-compatible AST handling. The GNAT build script knows the architecture
4566 and operating system, and automatically selects the right version,
4567 renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4569 Another style for arranging alternative implementations is through Ada's
4570 access-to-subprogram facility.
4571 In case some functionality is to be conditionally included,
4572 you can declare an access-to-procedure variable @cite{Ref} that is initialized
4573 to designate a 'do nothing' procedure, and then invoke @cite{Ref.all}
4574 when appropriate.
4575 In some library package, set @cite{Ref} to @cite{Proc'Access} for some
4576 procedure @cite{Proc} that performs the relevant processing.
4577 The initialization only occurs if the library package is included in the
4578 program.
4579 The same idea can also be implemented using tagged types and dispatching
4580 calls.
4582 @node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4583 @anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{a3}@anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{a4}
4584 @subsubsection Preprocessing
4587 @geindex Preprocessing
4589 Although it is quite possible to conditionalize code without the use of
4590 C-style preprocessing, as described earlier in this section, it is
4591 nevertheless convenient in some cases to use the C approach. Moreover,
4592 older Ada compilers have often provided some preprocessing capability,
4593 so legacy code may depend on this approach, even though it is not
4594 standard.
4596 To accommodate such use, GNAT provides a preprocessor (modeled to a large
4597 extent on the various preprocessors that have been used
4598 with legacy code on other compilers, to enable easier transition).
4600 @geindex gnatprep
4602 The preprocessor may be used in two separate modes. It can be used quite
4603 separately from the compiler, to generate a separate output source file
4604 that is then fed to the compiler as a separate step. This is the
4605 @cite{gnatprep} utility, whose use is fully described in
4606 @ref{17,,Preprocessing with gnatprep}.
4608 The preprocessing language allows such constructs as
4610 @example
4611 #if DEBUG or else (PRIORITY > 4) then
4612    bunch of declarations
4613 #else
4614    completely different bunch of declarations
4615 #end if;
4616 @end example
4618 The values of the symbols @cite{DEBUG} and @cite{PRIORITY} can be
4619 defined either on the command line or in a separate file.
4621 The other way of running the preprocessor is even closer to the C style and
4622 often more convenient. In this approach the preprocessing is integrated into
4623 the compilation process. The compiler is fed the preprocessor input which
4624 includes @cite{#if} lines etc, and then the compiler carries out the
4625 preprocessing internally and processes the resulting output.
4626 For more details on this approach, see @ref{18,,Integrated Preprocessing}.
4628 @node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4629 @anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{17}
4630 @subsection Preprocessing with @cite{gnatprep}
4633 @geindex gnatprep
4635 @geindex Preprocessing (gnatprep)
4637 This section discusses how to use GNAT's @cite{gnatprep} utility for simple
4638 preprocessing.
4639 Although designed for use with GNAT, @cite{gnatprep} does not depend on any
4640 special GNAT features.
4641 For further discussion of conditional compilation in general, see
4642 @ref{16,,Conditional Compilation}.
4644 @menu
4645 * Preprocessing Symbols:: 
4646 * Using gnatprep:: 
4647 * Switches for gnatprep:: 
4648 * Form of Definitions File:: 
4649 * Form of Input Text for gnatprep:: 
4651 @end menu
4653 @node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4654 @anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{a6}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{a7}
4655 @subsubsection Preprocessing Symbols
4658 Preprocessing symbols are defined in definition files and referred to in
4659 sources to be preprocessed. A Preprocessing symbol is an identifier, following
4660 normal Ada (case-insensitive) rules for its syntax, with the restriction that
4661 all characters need to be in the ASCII set (no accented letters).
4663 @node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4664 @anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{a8}@anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{a9}
4665 @subsubsection Using @cite{gnatprep}
4668 To call @cite{gnatprep} use:
4670 @example
4671 $ gnatprep [`switches`] `infile` `outfile` [`deffile`]
4672 @end example
4674 where
4677 @itemize *
4679 @item 
4681 @table @asis
4683 @item @emph{switches}
4685 is an optional sequence of switches as described in the next section.
4686 @end table
4688 @item 
4690 @table @asis
4692 @item @emph{infile}
4694 is the full name of the input file, which is an Ada source
4695 file containing preprocessor directives.
4696 @end table
4698 @item 
4700 @table @asis
4702 @item @emph{outfile}
4704 is the full name of the output file, which is an Ada source
4705 in standard Ada form. When used with GNAT, this file name will
4706 normally have an ads or adb suffix.
4707 @end table
4709 @item 
4711 @table @asis
4713 @item @emph{deffile}
4715 is the full name of a text file containing definitions of
4716 preprocessing symbols to be referenced by the preprocessor. This argument is
4717 optional, and can be replaced by the use of the @emph{-D} switch.
4718 @end table
4719 @end itemize
4721 @node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4722 @anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{aa}@anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{ab}
4723 @subsubsection Switches for @cite{gnatprep}
4726 @geindex --version (gnatprep)
4729 @table @asis
4731 @item @code{--version}
4733 Display Copyright and version, then exit disregarding all other options.
4734 @end table
4736 @geindex --help (gnatprep)
4739 @table @asis
4741 @item @code{--help}
4743 If @emph{--version} was not used, display usage, then exit disregarding
4744 all other options.
4745 @end table
4747 @geindex -b (gnatprep)
4750 @table @asis
4752 @item @code{-b}
4754 Causes both preprocessor lines and the lines deleted by
4755 preprocessing to be replaced by blank lines in the output source file,
4756 preserving line numbers in the output file.
4757 @end table
4759 @geindex -c (gnatprep)
4762 @table @asis
4764 @item @code{-c}
4766 Causes both preprocessor lines and the lines deleted
4767 by preprocessing to be retained in the output source as comments marked
4768 with the special string @cite{"--! "}. This option will result in line numbers
4769 being preserved in the output file.
4770 @end table
4772 @geindex -C (gnatprep)
4775 @table @asis
4777 @item @code{-C}
4779 Causes comments to be scanned. Normally comments are ignored by gnatprep.
4780 If this option is specified, then comments are scanned and any $symbol
4781 substitutions performed as in program text. This is particularly useful
4782 when structured comments are used (e.g., when writing programs in the
4783 SPARK dialect of Ada). Note that this switch is not available when
4784 doing integrated preprocessing (it would be useless in this context
4785 since comments are ignored by the compiler in any case).
4786 @end table
4788 @geindex -D (gnatprep)
4791 @table @asis
4793 @item @code{-D@emph{symbol}=@emph{value}}
4795 Defines a new preprocessing symbol, associated with value. If no value is given
4796 on the command line, then symbol is considered to be @cite{True}. This switch
4797 can be used in place of a definition file.
4798 @end table
4800 @geindex -r (gnatprep)
4803 @table @asis
4805 @item @code{-r}
4807 Causes a @cite{Source_Reference} pragma to be generated that
4808 references the original input file, so that error messages will use
4809 the file name of this original file. The use of this switch implies
4810 that preprocessor lines are not to be removed from the file, so its
4811 use will force @emph{-b} mode if @emph{-c}
4812 has not been specified explicitly.
4814 Note that if the file to be preprocessed contains multiple units, then
4815 it will be necessary to @cite{gnatchop} the output file from
4816 @cite{gnatprep}. If a @cite{Source_Reference} pragma is present
4817 in the preprocessed file, it will be respected by
4818 @cite{gnatchop -r}
4819 so that the final chopped files will correctly refer to the original
4820 input source file for @cite{gnatprep}.
4821 @end table
4823 @geindex -s (gnatprep)
4826 @table @asis
4828 @item @code{-s}
4830 Causes a sorted list of symbol names and values to be
4831 listed on the standard output file.
4832 @end table
4834 @geindex -T (gnatprep)
4837 @table @asis
4839 @item @code{-T}
4841 Use LF as line terminators when writing files. By default the line terminator
4842 of the host (LF under unix, CR/LF under Windows) is used.
4843 @end table
4845 @geindex -u (gnatprep)
4848 @table @asis
4850 @item @code{-u}
4852 Causes undefined symbols to be treated as having the value FALSE in the context
4853 of a preprocessor test. In the absence of this option, an undefined symbol in
4854 a @cite{#if} or @cite{#elsif} test will be treated as an error.
4855 @end table
4857 @geindex -v (gnatprep)
4860 @table @asis
4862 @item @code{-v}
4864 Verbose mode: generates more output about work done.
4865 @end table
4867 Note: if neither @emph{-b} nor @emph{-c} is present,
4868 then preprocessor lines and
4869 deleted lines are completely removed from the output, unless -r is
4870 specified, in which case -b is assumed.
4872 @node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4873 @anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{ad}
4874 @subsubsection Form of Definitions File
4877 The definitions file contains lines of the form:
4879 @example
4880 symbol := value
4881 @end example
4883 where @cite{symbol} is a preprocessing symbol, and @cite{value} is one of the following:
4886 @itemize *
4888 @item 
4889 Empty, corresponding to a null substitution,
4891 @item 
4892 A string literal using normal Ada syntax, or
4894 @item 
4895 Any sequence of characters from the set @{letters, digits, period, underline@}.
4896 @end itemize
4898 Comment lines may also appear in the definitions file, starting with
4899 the usual @code{--},
4900 and comments may be added to the definitions lines.
4902 @node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4903 @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}
4904 @subsubsection Form of Input Text for @cite{gnatprep}
4907 The input text may contain preprocessor conditional inclusion lines,
4908 as well as general symbol substitution sequences.
4910 The preprocessor conditional inclusion commands have the form:
4912 @example
4913 #if <expression> [then]
4914    lines
4915 #elsif <expression> [then]
4916    lines
4917 #elsif <expression> [then]
4918    lines
4920 #else
4921    lines
4922 #end if;
4923 @end example
4925 In this example, <expression> is defined by the following grammar:
4927 @example
4928 <expression> ::=  <symbol>
4929 <expression> ::=  <symbol> = "<value>"
4930 <expression> ::=  <symbol> = <symbol>
4931 <expression> ::=  <symbol> = <integer>
4932 <expression> ::=  <symbol> > <integer>
4933 <expression> ::=  <symbol> >= <integer>
4934 <expression> ::=  <symbol> < <integer>
4935 <expression> ::=  <symbol> <= <integer>
4936 <expression> ::=  <symbol> 'Defined
4937 <expression> ::=  not <expression>
4938 <expression> ::=  <expression> and <expression>
4939 <expression> ::=  <expression> or <expression>
4940 <expression> ::=  <expression> and then <expression>
4941 <expression> ::=  <expression> or else <expression>
4942 <expression> ::=  ( <expression> )
4943 @end example
4945 Note the following restriction: it is not allowed to have "and" or "or"
4946 following "not" in the same expression without parentheses. For example, this
4947 is not allowed:
4949 @example
4950 not X or Y
4951 @end example
4953 This can be expressed instead as one of the following forms:
4955 @example
4956 (not X) or Y
4957 not (X or Y)
4958 @end example
4960 For the first test (<expression> ::= <symbol>) the symbol must have
4961 either the value true or false, that is to say the right-hand of the
4962 symbol definition must be one of the (case-insensitive) literals
4963 @cite{True} or @cite{False}. If the value is true, then the
4964 corresponding lines are included, and if the value is false, they are
4965 excluded.
4967 When comparing a symbol to an integer, the integer is any non negative
4968 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
4969 2#11#. The symbol value must also be a non negative integer. Integer values
4970 in the range 0 .. 2**31-1 are supported.
4972 The test (<expression> ::= <symbol>'Defined) is true only if
4973 the symbol has been defined in the definition file or by a @emph{-D}
4974 switch on the command line. Otherwise, the test is false.
4976 The equality tests are case insensitive, as are all the preprocessor lines.
4978 If the symbol referenced is not defined in the symbol definitions file,
4979 then the effect depends on whether or not switch @emph{-u}
4980 is specified. If so, then the symbol is treated as if it had the value
4981 false and the test fails. If this switch is not specified, then
4982 it is an error to reference an undefined symbol. It is also an error to
4983 reference a symbol that is defined with a value other than @cite{True}
4984 or @cite{False}.
4986 The use of the @cite{not} operator inverts the sense of this logical test.
4987 The @cite{not} operator cannot be combined with the @cite{or} or @cite{and}
4988 operators, without parentheses. For example, "if not X or Y then" is not
4989 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
4991 The @cite{then} keyword is optional as shown
4993 The @cite{#} must be the first non-blank character on a line, but
4994 otherwise the format is free form. Spaces or tabs may appear between
4995 the @cite{#} and the keyword. The keywords and the symbols are case
4996 insensitive as in normal Ada code. Comments may be used on a
4997 preprocessor line, but other than that, no other tokens may appear on a
4998 preprocessor line. Any number of @cite{elsif} clauses can be present,
4999 including none at all. The @cite{else} is optional, as in Ada.
5001 The @cite{#} marking the start of a preprocessor line must be the first
5002 non-blank character on the line, i.e., it must be preceded only by
5003 spaces or horizontal tabs.
5005 Symbol substitution outside of preprocessor lines is obtained by using
5006 the sequence:
5008 @example
5009 $symbol
5010 @end example
5012 anywhere within a source line, except in a comment or within a
5013 string literal. The identifier
5014 following the @cite{$} must match one of the symbols defined in the symbol
5015 definition file, and the result is to substitute the value of the
5016 symbol in place of @cite{$symbol} in the output file.
5018 Note that although the substitution of strings within a string literal
5019 is not possible, it is possible to have a symbol whose defined value is
5020 a string literal. So instead of setting XYZ to @cite{hello} and writing:
5022 @example
5023 Header : String := "$XYZ";
5024 @end example
5026 you should set XYZ to @cite{"hello"} and write:
5028 @example
5029 Header : String := $XYZ;
5030 @end example
5032 and then the substitution will occur as desired.
5034 @node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
5035 @anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{b0}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{18}
5036 @subsection Integrated Preprocessing
5039 GNAT sources may be preprocessed immediately before compilation.
5040 In this case, the actual
5041 text of the source is not the text of the source file, but is derived from it
5042 through a process called preprocessing. Integrated preprocessing is specified
5043 through switches @emph{-gnatep} and/or @emph{-gnateD}. @emph{-gnatep}
5044 indicates, through a text file, the preprocessing data to be used.
5045 @code{-gnateD} specifies or modifies the values of preprocessing symbol.
5046 Note that integrated preprocessing applies only to Ada source files, it is
5047 not available for configuration pragma files.
5049 Note that when integrated preprocessing is used, the output from the
5050 preprocessor is not written to any external file. Instead it is passed
5051 internally to the compiler. If you need to preserve the result of
5052 preprocessing in a file, then you should use @emph{gnatprep}
5053 to perform the desired preprocessing in stand-alone mode.
5055 It is recommended that @emph{gnatmake} switch -s should be
5056 used when Integrated Preprocessing is used. The reason is that preprocessing
5057 with another Preprocessing Data file without changing the sources will
5058 not trigger recompilation without this switch.
5060 Note that @emph{gnatmake} switch -m will almost
5061 always trigger recompilation for sources that are preprocessed,
5062 because @emph{gnatmake} cannot compute the checksum of the source after
5063 preprocessing.
5065 The actual preprocessing function is described in detail in section
5066 @ref{17,,Preprocessing with gnatprep}. This section only describes how integrated
5067 preprocessing is triggered and parameterized.
5069 @geindex -gnatep (gcc)
5072 @table @asis
5074 @item @code{-gnatep=@emph{file}}
5076 This switch indicates to the compiler the file name (without directory
5077 information) of the preprocessor data file to use. The preprocessor data file
5078 should be found in the source directories. Alternatively when using project
5079 files, you can reference to the project file's directory via the
5080 @code{project name'Project_Dir} project attribute, e.g:
5082 @example
5083 project Prj is
5084    package Compiler is
5085       for Switches ("Ada") use
5086         ("-gnatep=" & Prj'Project_Dir & "prep.def");
5087    end Compiler;
5088 end Prj;
5089 @end example
5091 A preprocessing data file is a text file with significant lines indicating
5092 how should be preprocessed either a specific source or all sources not
5093 mentioned in other lines. A significant line is a nonempty, non-comment line.
5094 Comments are similar to Ada comments.
5096 Each significant line starts with either a literal string or the character '*'.
5097 A literal string is the file name (without directory information) of the source
5098 to preprocess. A character '*' indicates the preprocessing for all the sources
5099 that are not specified explicitly on other lines (order of the lines is not
5100 significant). It is an error to have two lines with the same file name or two
5101 lines starting with the character '*'.
5103 After the file name or the character '*', another optional literal string
5104 indicating the file name of the definition file to be used for preprocessing
5105 (@ref{ac,,Form of Definitions File}). The definition files are found by the
5106 compiler in one of the source directories. In some cases, when compiling
5107 a source in a directory other than the current directory, if the definition
5108 file is in the current directory, it may be necessary to add the current
5109 directory as a source directory through switch -I., otherwise
5110 the compiler would not find the definition file.
5112 Then, optionally, switches similar to those of @cite{gnatprep} may
5113 be found. Those switches are:
5116 @table @asis
5118 @item @code{-b}
5120 Causes both preprocessor lines and the lines deleted by
5121 preprocessing to be replaced by blank lines, preserving the line number.
5122 This switch is always implied; however, if specified after @emph{-c}
5123 it cancels the effect of @emph{-c}.
5125 @item @code{-c}
5127 Causes both preprocessor lines and the lines deleted
5128 by preprocessing to be retained as comments marked
5129 with the special string '@cite{--!}'.
5131 @item @code{-Dsymbol=@emph{value}}
5133 Define or redefine a symbol, associated with value. A symbol is an Ada
5134 identifier, or an Ada reserved word, with the exception of @cite{if},
5135 @cite{else}, @cite{elsif}, @cite{end}, @cite{and}, @cite{or} and @cite{then}.
5136 @cite{value} is either a literal string, an Ada identifier or any Ada reserved
5137 word. A symbol declared with this switch replaces a symbol with the
5138 same name defined in a definition file.
5140 @item @code{-s}
5142 Causes a sorted list of symbol names and values to be
5143 listed on the standard output file.
5145 @item @code{-u}
5147 Causes undefined symbols to be treated as having the value @cite{FALSE}
5148 in the context
5149 of a preprocessor test. In the absence of this option, an undefined symbol in
5150 a @cite{#if} or @cite{#elsif} test will be treated as an error.
5151 @end table
5153 Examples of valid lines in a preprocessor data file:
5155 @example
5156 "toto.adb"  "prep.def" -u
5157 --  preprocess "toto.adb", using definition file "prep.def",
5158 --  undefined symbol are False.
5160 * -c -DVERSION=V101
5161 --  preprocess all other sources without a definition file;
5162 --  suppressed lined are commented; symbol VERSION has the value V101.
5164 "titi.adb" "prep2.def" -s
5165 --  preprocess "titi.adb", using definition file "prep2.def";
5166 --  list all symbols with their values.
5167 @end example
5168 @end table
5170 @geindex -gnateD (gcc)
5173 @table @asis
5175 @item @code{-gnateDsymbol[=value]}
5177 Define or redefine a preprocessing symbol, associated with value. If no value
5178 is given on the command line, then the value of the symbol is @cite{True}.
5179 A symbol is an identifier, following normal Ada (case-insensitive)
5180 rules for its syntax, and value is either an arbitrary string between double
5181 quotes or any sequence (including an empty sequence) of characters from the
5182 set (letters, digits, period, underline).
5183 Ada reserved words may be used as symbols, with the exceptions of @cite{if},
5184 @cite{else}, @cite{elsif}, @cite{end}, @cite{and}, @cite{or} and @cite{then}.
5186 Examples:
5188 @example
5189 -gnateDToto=Titi
5190 -gnateDFoo
5191 -gnateDFoo=\"Foo-Bar\"
5192 @end example
5194 A symbol declared with this switch on the command line replaces a
5195 symbol with the same name either in a definition file or specified with a
5196 switch -D in the preprocessor data file.
5198 This switch is similar to switch @emph{-D} of @cite{gnatprep}.
5200 @item @code{-gnateG}
5202 When integrated preprocessing is performed and the preprocessor modifies
5203 the source text, write the result of this preprocessing into a file
5204 <source>.prep.
5205 @end table
5207 @node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5208 @anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{44}@anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{b1}
5209 @section Mixed Language Programming
5212 @geindex Mixed Language Programming
5214 This section describes how to develop a mixed-language program,
5215 with a focus on combining Ada with C or C++.
5217 @menu
5218 * Interfacing to C:: 
5219 * Calling Conventions:: 
5220 * Building Mixed Ada and C++ Programs:: 
5221 * Generating Ada Bindings for C and C++ headers:: 
5222 * Generating C Headers for Ada Specifications:: 
5224 @end menu
5226 @node Interfacing to C,Calling Conventions,,Mixed Language Programming
5227 @anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{b2}@anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{b3}
5228 @subsection Interfacing to C
5231 Interfacing Ada with a foreign language such as C involves using
5232 compiler directives to import and/or export entity definitions in each
5233 language -- using @cite{extern} statements in C, for instance, and the
5234 @cite{Import}, @cite{Export}, and @cite{Convention} pragmas in Ada.
5235 A full treatment of these topics is provided in Appendix B, section 1
5236 of the Ada Reference Manual.
5238 There are two ways to build a program using GNAT that contains some Ada
5239 sources and some foreign language sources, depending on whether or not
5240 the main subprogram is written in Ada.  Here is a source example with
5241 the main subprogram in Ada:
5243 @example
5244 /* file1.c */
5245 #include <stdio.h>
5247 void print_num (int num)
5249   printf ("num is %d.\\n", num);
5250   return;
5252 @end example
5254 @example
5255 /* file2.c */
5257 /* num_from_Ada is declared in my_main.adb */
5258 extern int num_from_Ada;
5260 int get_num (void)
5262   return num_from_Ada;
5264 @end example
5266 @example
5267 --  my_main.adb
5268 procedure My_Main is
5270    --  Declare then export an Integer entity called num_from_Ada
5271    My_Num : Integer := 10;
5272    pragma Export (C, My_Num, "num_from_Ada");
5274    --  Declare an Ada function spec for Get_Num, then use
5275    --  C function get_num for the implementation.
5276    function Get_Num return Integer;
5277    pragma Import (C, Get_Num, "get_num");
5279    --  Declare an Ada procedure spec for Print_Num, then use
5280    --  C function print_num for the implementation.
5281    procedure Print_Num (Num : Integer);
5282    pragma Import (C, Print_Num, "print_num";
5284 begin
5285    Print_Num (Get_Num);
5286 end My_Main;
5287 @end example
5289 To build this example:
5292 @itemize *
5294 @item 
5295 First compile the foreign language files to
5296 generate object files:
5298 @example
5299 $ gcc -c file1.c
5300 $ gcc -c file2.c
5301 @end example
5303 @item 
5304 Then, compile the Ada units to produce a set of object files and ALI
5305 files:
5307 @example
5308 $ gnatmake -c my_main.adb
5309 @end example
5311 @item 
5312 Run the Ada binder on the Ada main program:
5314 @example
5315 $ gnatbind my_main.ali
5316 @end example
5318 @item 
5319 Link the Ada main program, the Ada objects and the other language
5320 objects:
5322 @example
5323 $ gnatlink my_main.ali file1.o file2.o
5324 @end example
5325 @end itemize
5327 The last three steps can be grouped in a single command:
5329 @example
5330 $ gnatmake my_main.adb -largs file1.o file2.o
5331 @end example
5333 @geindex Binder output file
5335 If the main program is in a language other than Ada, then you may have
5336 more than one entry point into the Ada subsystem. You must use a special
5337 binder option to generate callable routines that initialize and
5338 finalize the Ada units (@ref{b4,,Binding with Non-Ada Main Programs}).
5339 Calls to the initialization and finalization routines must be inserted
5340 in the main program, or some other appropriate point in the code. The
5341 call to initialize the Ada units must occur before the first Ada
5342 subprogram is called, and the call to finalize the Ada units must occur
5343 after the last Ada subprogram returns. The binder will place the
5344 initialization and finalization subprograms into the
5345 @code{b~xxx.adb} file where they can be accessed by your C
5346 sources.  To illustrate, we have the following example:
5348 @example
5349 /* main.c */
5350 extern void adainit (void);
5351 extern void adafinal (void);
5352 extern int add (int, int);
5353 extern int sub (int, int);
5355 int main (int argc, char *argv[])
5357    int a = 21, b = 7;
5359    adainit();
5361    /* Should print "21 + 7 = 28" */
5362    printf ("%d + %d = %d\\n", a, b, add (a, b));
5364    /* Should print "21 - 7 = 14" */
5365    printf ("%d - %d = %d\\n", a, b, sub (a, b));
5367    adafinal();
5369 @end example
5371 @example
5372 --  unit1.ads
5373 package Unit1 is
5374    function Add (A, B : Integer) return Integer;
5375    pragma Export (C, Add, "add");
5376 end Unit1;
5377 @end example
5379 @example
5380 --  unit1.adb
5381 package body Unit1 is
5382    function Add (A, B : Integer) return Integer is
5383    begin
5384       return A + B;
5385    end Add;
5386 end Unit1;
5387 @end example
5389 @example
5390 --  unit2.ads
5391 package Unit2 is
5392    function Sub (A, B : Integer) return Integer;
5393    pragma Export (C, Sub, "sub");
5394 end Unit2;
5395 @end example
5397 @example
5398 --  unit2.adb
5399 package body Unit2 is
5400    function Sub (A, B : Integer) return Integer is
5401    begin
5402       return A - B;
5403    end Sub;
5404 end Unit2;
5405 @end example
5407 The build procedure for this application is similar to the last
5408 example's:
5411 @itemize *
5413 @item 
5414 First, compile the foreign language files to generate object files:
5416 @example
5417 $ gcc -c main.c
5418 @end example
5420 @item 
5421 Next, compile the Ada units to produce a set of object files and ALI
5422 files:
5424 @example
5425 $ gnatmake -c unit1.adb
5426 $ gnatmake -c unit2.adb
5427 @end example
5429 @item 
5430 Run the Ada binder on every generated ALI file.  Make sure to use the
5431 @code{-n} option to specify a foreign main program:
5433 @example
5434 $ gnatbind -n unit1.ali unit2.ali
5435 @end example
5437 @item 
5438 Link the Ada main program, the Ada objects and the foreign language
5439 objects. You need only list the last ALI file here:
5441 @example
5442 $ gnatlink unit2.ali main.o -o exec_file
5443 @end example
5445 This procedure yields a binary executable called @code{exec_file}.
5446 @end itemize
5448 Depending on the circumstances (for example when your non-Ada main object
5449 does not provide symbol @cite{main}), you may also need to instruct the
5450 GNAT linker not to include the standard startup objects by passing the
5451 @code{-nostartfiles} switch to @cite{gnatlink}.
5453 @node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5454 @anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{b5}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{b6}
5455 @subsection Calling Conventions
5458 @geindex Foreign Languages
5460 @geindex Calling Conventions
5462 GNAT follows standard calling sequence conventions and will thus interface
5463 to any other language that also follows these conventions. The following
5464 Convention identifiers are recognized by GNAT:
5466 @geindex Interfacing to Ada
5468 @geindex Other Ada compilers
5470 @geindex Convention Ada
5473 @table @asis
5475 @item @emph{Ada}
5477 This indicates that the standard Ada calling sequence will be
5478 used and all Ada data items may be passed without any limitations in the
5479 case where GNAT is used to generate both the caller and callee. It is also
5480 possible to mix GNAT generated code and code generated by another Ada
5481 compiler. In this case, the data types should be restricted to simple
5482 cases, including primitive types. Whether complex data types can be passed
5483 depends on the situation. Probably it is safe to pass simple arrays, such
5484 as arrays of integers or floats. Records may or may not work, depending
5485 on whether both compilers lay them out identically. Complex structures
5486 involving variant records, access parameters, tasks, or protected types,
5487 are unlikely to be able to be passed.
5489 Note that in the case of GNAT running
5490 on a platform that supports HP Ada 83, a higher degree of compatibility
5491 can be guaranteed, and in particular records are laid out in an identical
5492 manner in the two compilers. Note also that if output from two different
5493 compilers is mixed, the program is responsible for dealing with elaboration
5494 issues. Probably the safest approach is to write the main program in the
5495 version of Ada other than GNAT, so that it takes care of its own elaboration
5496 requirements, and then call the GNAT-generated adainit procedure to ensure
5497 elaboration of the GNAT components. Consult the documentation of the other
5498 Ada compiler for further details on elaboration.
5500 However, it is not possible to mix the tasking run time of GNAT and
5501 HP Ada 83, All the tasking operations must either be entirely within
5502 GNAT compiled sections of the program, or entirely within HP Ada 83
5503 compiled sections of the program.
5504 @end table
5506 @geindex Interfacing to Assembly
5508 @geindex Convention Assembler
5511 @table @asis
5513 @item @emph{Assembler}
5515 Specifies assembler as the convention. In practice this has the
5516 same effect as convention Ada (but is not equivalent in the sense of being
5517 considered the same convention).
5518 @end table
5520 @geindex Convention Asm
5522 @geindex Asm
5525 @table @asis
5527 @item @emph{Asm}
5529 Equivalent to Assembler.
5531 @geindex Interfacing to COBOL
5533 @geindex Convention COBOL
5534 @end table
5536 @geindex COBOL
5539 @table @asis
5541 @item @emph{COBOL}
5543 Data will be passed according to the conventions described
5544 in section B.4 of the Ada Reference Manual.
5545 @end table
5547 @geindex C
5549 @geindex Interfacing to C
5551 @geindex Convention C
5554 @table @asis
5556 @item @emph{C}
5558 Data will be passed according to the conventions described
5559 in section B.3 of the Ada Reference Manual.
5561 A note on interfacing to a C 'varargs' function:
5563 @quotation
5565 @geindex C varargs function
5567 @geindex Interfacing to C varargs function
5569 @geindex varargs function interfaces
5571 In C, @cite{varargs} allows a function to take a variable number of
5572 arguments. There is no direct equivalent in this to Ada. One
5573 approach that can be used is to create a C wrapper for each
5574 different profile and then interface to this C wrapper. For
5575 example, to print an @cite{int} value using @cite{printf},
5576 create a C function @cite{printfi} that takes two arguments, a
5577 pointer to a string and an int, and calls @cite{printf}.
5578 Then in the Ada program, use pragma @cite{Import} to
5579 interface to @cite{printfi}.
5581 It may work on some platforms to directly interface to
5582 a @cite{varargs} function by providing a specific Ada profile
5583 for a particular call. However, this does not work on
5584 all platforms, since there is no guarantee that the
5585 calling sequence for a two argument normal C function
5586 is the same as for calling a @cite{varargs} C function with
5587 the same two arguments.
5588 @end quotation
5589 @end table
5591 @geindex Convention Default
5593 @geindex Default
5596 @table @asis
5598 @item @emph{Default}
5600 Equivalent to C.
5601 @end table
5603 @geindex Convention External
5605 @geindex External
5608 @table @asis
5610 @item @emph{External}
5612 Equivalent to C.
5613 @end table
5615 @geindex C++
5617 @geindex Interfacing to C++
5619 @geindex Convention C++
5622 @table @asis
5624 @item @emph{C_Plus_Plus (or CPP)}
5626 This stands for C++. For most purposes this is identical to C.
5627 See the separate description of the specialized GNAT pragmas relating to
5628 C++ interfacing for further details.
5629 @end table
5631 @geindex Fortran
5633 @geindex Interfacing to Fortran
5635 @geindex Convention Fortran
5638 @table @asis
5640 @item @emph{Fortran}
5642 Data will be passed according to the conventions described
5643 in section B.5 of the Ada Reference Manual.
5645 @item @emph{Intrinsic}
5647 This applies to an intrinsic operation, as defined in the Ada
5648 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5649 this means that the body of the subprogram is provided by the compiler itself,
5650 usually by means of an efficient code sequence, and that the user does not
5651 supply an explicit body for it. In an application program, the pragma may
5652 be applied to the following sets of names:
5655 @itemize *
5657 @item 
5658 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5659 The corresponding subprogram declaration must have
5660 two formal parameters. The
5661 first one must be a signed integer type or a modular type with a binary
5662 modulus, and the second parameter must be of type Natural.
5663 The return type must be the same as the type of the first argument. The size
5664 of this type can only be 8, 16, 32, or 64.
5666 @item 
5667 Binary arithmetic operators: '+', '-', '*', '/'.
5668 The corresponding operator declaration must have parameters and result type
5669 that have the same root numeric type (for example, all three are long_float
5670 types). This simplifies the definition of operations that use type checking
5671 to perform dimensional checks:
5672 @end itemize
5674 @example
5675   type Distance is new Long_Float;
5676   type Time     is new Long_Float;
5677   type Velocity is new Long_Float;
5678   function "/" (D : Distance; T : Time)
5679     return Velocity;
5680   pragma Import (Intrinsic, "/");
5682 This common idiom is often programmed with a generic definition and an
5683 explicit body. The pragma makes it simpler to introduce such declarations.
5684 It incurs no overhead in compilation time or code size, because it is
5685 implemented as a single machine instruction.
5686 @end example
5689 @itemize *
5691 @item 
5692 General subprogram entities. This is used  to bind an Ada subprogram
5693 declaration to
5694 a compiler builtin by name with back-ends where such interfaces are
5695 available. A typical example is the set of @cite{__builtin} functions
5696 exposed by the GCC back-end, as in the following example:
5698 @example
5699 function builtin_sqrt (F : Float) return Float;
5700 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5701 @end example
5703 Most of the GCC builtins are accessible this way, and as for other
5704 import conventions (e.g. C), it is the user's responsibility to ensure
5705 that the Ada subprogram profile matches the underlying builtin
5706 expectations.
5707 @end itemize
5708 @end table
5710 @geindex Stdcall
5712 @geindex Convention Stdcall
5715 @table @asis
5717 @item @emph{Stdcall}
5719 This is relevant only to Windows implementations of GNAT,
5720 and specifies that the @cite{Stdcall} calling sequence will be used,
5721 as defined by the NT API. Nevertheless, to ease building
5722 cross-platform bindings this convention will be handled as a @cite{C} calling
5723 convention on non-Windows platforms.
5724 @end table
5726 @geindex DLL
5728 @geindex Convention DLL
5731 @table @asis
5733 @item @emph{DLL}
5735 This is equivalent to @cite{Stdcall}.
5736 @end table
5738 @geindex Win32
5740 @geindex Convention Win32
5743 @table @asis
5745 @item @emph{Win32}
5747 This is equivalent to @cite{Stdcall}.
5748 @end table
5750 @geindex Stubbed
5752 @geindex Convention Stubbed
5755 @table @asis
5757 @item @emph{Stubbed}
5759 This is a special convention that indicates that the compiler
5760 should provide a stub body that raises @cite{Program_Error}.
5761 @end table
5763 GNAT additionally provides a useful pragma @cite{Convention_Identifier}
5764 that can be used to parameterize conventions and allow additional synonyms
5765 to be specified. For example if you have legacy code in which the convention
5766 identifier Fortran77 was used for Fortran, you can use the configuration
5767 pragma:
5769 @example
5770 pragma Convention_Identifier (Fortran77, Fortran);
5771 @end example
5773 And from now on the identifier Fortran77 may be used as a convention
5774 identifier (for example in an @cite{Import} pragma) with the same
5775 meaning as Fortran.
5777 @node Building Mixed Ada and C++ Programs,Generating Ada Bindings for C and C++ headers,Calling Conventions,Mixed Language Programming
5778 @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}
5779 @subsection Building Mixed Ada and C++ Programs
5782 A programmer inexperienced with mixed-language development may find that
5783 building an application containing both Ada and C++ code can be a
5784 challenge.  This section gives a few hints that should make this task easier.
5786 @menu
5787 * Interfacing to C++:: 
5788 * Linking a Mixed C++ & Ada Program:: 
5789 * A Simple Example:: 
5790 * Interfacing with C++ constructors:: 
5791 * Interfacing with C++ at the Class Level:: 
5793 @end menu
5795 @node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5796 @anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{b9}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{ba}
5797 @subsubsection Interfacing to C++
5800 GNAT supports interfacing with the G++ compiler (or any C++ compiler
5801 generating code that is compatible with the G++ Application Binary
5802 Interface ---see @indicateurl{http://www.codesourcery.com/archives/cxx-abi}).
5804 Interfacing can be done at 3 levels: simple data, subprograms, and
5805 classes. In the first two cases, GNAT offers a specific @cite{Convention C_Plus_Plus}
5806 (or @cite{CPP}) that behaves exactly like @cite{Convention C}.
5807 Usually, C++ mangles the names of subprograms. To generate proper mangled
5808 names automatically, see @ref{19,,Generating Ada Bindings for C and C++ headers}).
5809 This problem can also be addressed manually in two ways:
5812 @itemize *
5814 @item 
5815 by modifying the C++ code in order to force a C convention using
5816 the @cite{extern "C"} syntax.
5818 @item 
5819 by figuring out the mangled name (using e.g. @emph{nm}) and using it as the
5820 Link_Name argument of the pragma import.
5821 @end itemize
5823 Interfacing at the class level can be achieved by using the GNAT specific
5824 pragmas such as @cite{CPP_Constructor}.  See the @cite{GNAT_Reference_Manual} for additional information.
5826 @node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5827 @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}
5828 @subsubsection Linking a Mixed C++ & Ada Program
5831 Usually the linker of the C++ development system must be used to link
5832 mixed applications because most C++ systems will resolve elaboration
5833 issues (such as calling constructors on global class instances)
5834 transparently during the link phase. GNAT has been adapted to ease the
5835 use of a foreign linker for the last phase. Three cases can be
5836 considered:
5839 @itemize *
5841 @item 
5842 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5843 The C++ linker can simply be called by using the C++ specific driver
5844 called @cite{g++}.
5846 Note that if the C++ code uses inline functions, you will need to
5847 compile your C++ code with the @cite{-fkeep-inline-functions} switch in
5848 order to provide an existing function implementation that the Ada code can
5849 link with.
5851 @example
5852 $ g++ -c -fkeep-inline-functions file1.C
5853 $ g++ -c -fkeep-inline-functions file2.C
5854 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5855 @end example
5857 @item 
5858 Using GNAT and G++ from two different GCC installations: If both
5859 compilers are on the :envvar`PATH`, the previous method may be used. It is
5860 important to note that environment variables such as
5861 @geindex C_INCLUDE_PATH
5862 @geindex environment variable; C_INCLUDE_PATH
5863 @code{C_INCLUDE_PATH}, 
5864 @geindex GCC_EXEC_PREFIX
5865 @geindex environment variable; GCC_EXEC_PREFIX
5866 @code{GCC_EXEC_PREFIX},
5867 @geindex BINUTILS_ROOT
5868 @geindex environment variable; BINUTILS_ROOT
5869 @code{BINUTILS_ROOT}, and
5870 @geindex GCC_ROOT
5871 @geindex environment variable; GCC_ROOT
5872 @code{GCC_ROOT} will affect both compilers
5873 at the same time and may make one of the two compilers operate
5874 improperly if set during invocation of the wrong compiler.  It is also
5875 very important that the linker uses the proper @code{libgcc.a} GCC
5876 library -- that is, the one from the C++ compiler installation. The
5877 implicit link command as suggested in the @cite{gnatmake} command
5878 from the former example can be replaced by an explicit link command with
5879 the full-verbosity option in order to verify which library is used:
5881 @example
5882 $ gnatbind ada_unit
5883 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5884 @end example
5886 If there is a problem due to interfering environment variables, it can
5887 be worked around by using an intermediate script. The following example
5888 shows the proper script to use when GNAT has not been installed at its
5889 default location and g++ has been installed at its default location:
5891 @example
5892 $ cat ./my_script
5893 #!/bin/sh
5894 unset BINUTILS_ROOT
5895 unset GCC_ROOT
5896 c++ $*
5897 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5898 @end example
5900 @item 
5901 Using a non-GNU C++ compiler: The commands previously described can be
5902 used to insure that the C++ linker is used. Nonetheless, you need to add
5903 a few more parameters to the link command line, depending on the exception
5904 mechanism used.
5906 If the @cite{setjmp/longjmp} exception mechanism is used, only the paths
5907 to the libgcc libraries are required:
5909 @example
5910 $ cat ./my_script
5911 #!/bin/sh
5912 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
5913 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5914 @end example
5916 where CC is the name of the non-GNU C++ compiler.
5918 If the @cite{zero cost} exception mechanism is used, and the platform
5919 supports automatic registration of exception tables (e.g., Solaris),
5920 paths to more objects are required:
5922 @example
5923 $ cat ./my_script
5924 #!/bin/sh
5925 CC `gcc -print-file-name=crtbegin.o` $* \\
5926 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \\
5927 `gcc -print-file-name=crtend.o`
5928 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5929 @end example
5931 If the "zero cost exception" mechanism is used, and the platform
5932 doesn't support automatic registration of exception tables (e.g., HP-UX
5933 or AIX), the simple approach described above will not work and
5934 a pre-linking phase using GNAT will be necessary.
5935 @end itemize
5937 Another alternative is to use the @code{gprbuild} multi-language builder
5938 which has a large knowledge base and knows how to link Ada and C++ code
5939 together automatically in most cases.
5941 @node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
5942 @anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{bd}@anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{be}
5943 @subsubsection A Simple Example
5946 The following example, provided as part of the GNAT examples, shows how
5947 to achieve procedural interfacing between Ada and C++ in both
5948 directions. The C++ class A has two methods. The first method is exported
5949 to Ada by the means of an extern C wrapper function. The second method
5950 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
5951 a limited record with a layout comparable to the C++ class. The Ada
5952 subprogram, in turn, calls the C++ method. So, starting from the C++
5953 main program, the process passes back and forth between the two
5954 languages.
5956 Here are the compilation commands:
5958 @example
5959 $ gnatmake -c simple_cpp_interface
5960 $ g++ -c cpp_main.C
5961 $ g++ -c ex7.C
5962 $ gnatbind -n simple_cpp_interface
5963 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
5964 @end example
5966 Here are the corresponding sources:
5968 @example
5969 //cpp_main.C
5971 #include "ex7.h"
5973 extern "C" @{
5974   void adainit (void);
5975   void adafinal (void);
5976   void method1 (A *t);
5979 void method1 (A *t)
5981   t->method1 ();
5984 int main ()
5986   A obj;
5987   adainit ();
5988   obj.method2 (3030);
5989   adafinal ();
5991 @end example
5993 @example
5994 //ex7.h
5996 class Origin @{
5997  public:
5998   int o_value;
6000 class A : public Origin @{
6001  public:
6002   void method1 (void);
6003   void method2 (int v);
6004   A();
6005   int   a_value;
6007 @end example
6009 @example
6010 //ex7.C
6012 #include "ex7.h"
6013 #include <stdio.h>
6015 extern "C" @{ void ada_method2 (A *t, int v);@}
6017 void A::method1 (void)
6019   a_value = 2020;
6020   printf ("in A::method1, a_value = %d \\n",a_value);
6023 void A::method2 (int v)
6025    ada_method2 (this, v);
6026    printf ("in A::method2, a_value = %d \\n",a_value);
6029 A::A(void)
6031    a_value = 1010;
6032   printf ("in A::A, a_value = %d \\n",a_value);
6034 @end example
6036 @example
6037 -- simple_cpp_interface.ads
6038 with System;
6039 package Simple_Cpp_Interface is
6040    type A is limited
6041       record
6042          Vptr    : System.Address;
6043          O_Value : Integer;
6044          A_Value : Integer;
6045       end record;
6046    pragma Convention (C, A);
6048    procedure Method1 (This : in out A);
6049    pragma Import (C, Method1);
6051    procedure Ada_Method2 (This : in out A; V : Integer);
6052    pragma Export (C, Ada_Method2);
6054 end Simple_Cpp_Interface;
6055 @end example
6057 @example
6058 -- simple_cpp_interface.adb
6059 package body Simple_Cpp_Interface is
6061    procedure Ada_Method2 (This : in out A; V : Integer) is
6062    begin
6063       Method1 (This);
6064       This.A_Value := V;
6065    end Ada_Method2;
6067 end Simple_Cpp_Interface;
6068 @end example
6070 @node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
6071 @anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{bf}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{c0}
6072 @subsubsection Interfacing with C++ constructors
6075 In order to interface with C++ constructors GNAT provides the
6076 @cite{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
6077 for additional information).
6078 In this section we present some common uses of C++ constructors
6079 in mixed-languages programs in GNAT.
6081 Let us assume that we need to interface with the following
6082 C++ class:
6084 @example
6085 class Root @{
6086 public:
6087   int  a_value;
6088   int  b_value;
6089   virtual int Get_Value ();
6090   Root();              // Default constructor
6091   Root(int v);         // 1st non-default constructor
6092   Root(int v, int w);  // 2nd non-default constructor
6094 @end example
6096 For this purpose we can write the following package spec (further
6097 information on how to build this spec is available in
6098 @ref{c1,,Interfacing with C++ at the Class Level} and
6099 @ref{19,,Generating Ada Bindings for C and C++ headers}).
6101 @example
6102 with Interfaces.C; use Interfaces.C;
6103 package Pkg_Root is
6104   type Root is tagged limited record
6105      A_Value : int;
6106      B_Value : int;
6107   end record;
6108   pragma Import (CPP, Root);
6110   function Get_Value (Obj : Root) return int;
6111   pragma Import (CPP, Get_Value);
6113   function Constructor return Root;
6114   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
6116   function Constructor (v : Integer) return Root;
6117   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
6119   function Constructor (v, w : Integer) return Root;
6120   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
6121 end Pkg_Root;
6122 @end example
6124 On the Ada side the constructor is represented by a function (whose
6125 name is arbitrary) that returns the classwide type corresponding to
6126 the imported C++ class. Although the constructor is described as a
6127 function, it is typically a procedure with an extra implicit argument
6128 (the object being initialized) at the implementation level. GNAT
6129 issues the appropriate call, whatever it is, to get the object
6130 properly initialized.
6132 Constructors can only appear in the following contexts:
6135 @itemize *
6137 @item 
6138 On the right side of an initialization of an object of type @cite{T}.
6140 @item 
6141 On the right side of an initialization of a record component of type @cite{T}.
6143 @item 
6144 In an Ada 2005 limited aggregate.
6146 @item 
6147 In an Ada 2005 nested limited aggregate.
6149 @item 
6150 In an Ada 2005 limited aggregate that initializes an object built in
6151 place by an extended return statement.
6152 @end itemize
6154 In a declaration of an object whose type is a class imported from C++,
6155 either the default C++ constructor is implicitly called by GNAT, or
6156 else the required C++ constructor must be explicitly called in the
6157 expression that initializes the object. For example:
6159 @example
6160 Obj1 : Root;
6161 Obj2 : Root := Constructor;
6162 Obj3 : Root := Constructor (v => 10);
6163 Obj4 : Root := Constructor (30, 40);
6164 @end example
6166 The first two declarations are equivalent: in both cases the default C++
6167 constructor is invoked (in the former case the call to the constructor is
6168 implicit, and in the latter case the call is explicit in the object
6169 declaration). @cite{Obj3} is initialized by the C++ non-default constructor
6170 that takes an integer argument, and @cite{Obj4} is initialized by the
6171 non-default C++ constructor that takes two integers.
6173 Let us derive the imported C++ class in the Ada side. For example:
6175 @example
6176 type DT is new Root with record
6177    C_Value : Natural := 2009;
6178 end record;
6179 @end example
6181 In this case the components DT inherited from the C++ side must be
6182 initialized by a C++ constructor, and the additional Ada components
6183 of type DT are initialized by GNAT. The initialization of such an
6184 object is done either by default, or by means of a function returning
6185 an aggregate of type DT, or by means of an extension aggregate.
6187 @example
6188 Obj5 : DT;
6189 Obj6 : DT := Function_Returning_DT (50);
6190 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6191 @end example
6193 The declaration of @cite{Obj5} invokes the default constructors: the
6194 C++ default constructor of the parent type takes care of the initialization
6195 of the components inherited from Root, and GNAT takes care of the default
6196 initialization of the additional Ada components of type DT (that is,
6197 @cite{C_Value} is initialized to value 2009). The order of invocation of
6198 the constructors is consistent with the order of elaboration required by
6199 Ada and C++. That is, the constructor of the parent type is always called
6200 before the constructor of the derived type.
6202 Let us now consider a record that has components whose type is imported
6203 from C++. For example:
6205 @example
6206 type Rec1 is limited record
6207    Data1 : Root := Constructor (10);
6208    Value : Natural := 1000;
6209 end record;
6211 type Rec2 (D : Integer := 20) is limited record
6212    Rec   : Rec1;
6213    Data2 : Root := Constructor (D, 30);
6214 end record;
6215 @end example
6217 The initialization of an object of type @cite{Rec2} will call the
6218 non-default C++ constructors specified for the imported components.
6219 For example:
6221 @example
6222 Obj8 : Rec2 (40);
6223 @end example
6225 Using Ada 2005 we can use limited aggregates to initialize an object
6226 invoking C++ constructors that differ from those specified in the type
6227 declarations. For example:
6229 @example
6230 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6231                         others => <>),
6232                 others => <>);
6233 @end example
6235 The above declaration uses an Ada 2005 limited aggregate to
6236 initialize @cite{Obj9}, and the C++ constructor that has two integer
6237 arguments is invoked to initialize the @cite{Data1} component instead
6238 of the constructor specified in the declaration of type @cite{Rec1}. In
6239 Ada 2005 the box in the aggregate indicates that unspecified components
6240 are initialized using the expression (if any) available in the component
6241 declaration. That is, in this case discriminant @cite{D} is initialized
6242 to value @cite{20}, @cite{Value} is initialized to value 1000, and the
6243 non-default C++ constructor that handles two integers takes care of
6244 initializing component @cite{Data2} with values @cite{20@comma{}30}.
6246 In Ada 2005 we can use the extended return statement to build the Ada
6247 equivalent to C++ non-default constructors. For example:
6249 @example
6250 function Constructor (V : Integer) return Rec2 is
6251 begin
6252    return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
6253                                  others => <>),
6254                          others => <>) do
6255       --  Further actions required for construction of
6256       --  objects of type Rec2
6257       ...
6258    end record;
6259 end Constructor;
6260 @end example
6262 In this example the extended return statement construct is used to
6263 build in place the returned object whose components are initialized
6264 by means of a limited aggregate. Any further action associated with
6265 the constructor can be placed inside the construct.
6267 @node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6268 @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}
6269 @subsubsection Interfacing with C++ at the Class Level
6272 In this section we demonstrate the GNAT features for interfacing with
6273 C++ by means of an example making use of Ada 2005 abstract interface
6274 types. This example consists of a classification of animals; classes
6275 have been used to model our main classification of animals, and
6276 interfaces provide support for the management of secondary
6277 classifications. We first demonstrate a case in which the types and
6278 constructors are defined on the C++ side and imported from the Ada
6279 side, and latter the reverse case.
6281 The root of our derivation will be the @cite{Animal} class, with a
6282 single private attribute (the @cite{Age} of the animal), a constructor,
6283 and two public primitives to set and get the value of this attribute.
6285 @example
6286 class Animal @{
6287  public:
6288    virtual void Set_Age (int New_Age);
6289    virtual int Age ();
6290    Animal() @{Age_Count = 0;@};
6291  private:
6292    int Age_Count;
6294 @end example
6296 Abstract interface types are defined in C++ by means of classes with pure
6297 virtual functions and no data members. In our example we will use two
6298 interfaces that provide support for the common management of @cite{Carnivore}
6299 and @cite{Domestic} animals:
6301 @example
6302 class Carnivore @{
6303 public:
6304    virtual int Number_Of_Teeth () = 0;
6307 class Domestic @{
6308 public:
6309    virtual void Set_Owner (char* Name) = 0;
6311 @end example
6313 Using these declarations, we can now say that a @cite{Dog} is an animal that is
6314 both Carnivore and Domestic, that is:
6316 @example
6317 class Dog : Animal, Carnivore, Domestic @{
6318  public:
6319    virtual int  Number_Of_Teeth ();
6320    virtual void Set_Owner (char* Name);
6322    Dog(); // Constructor
6323  private:
6324    int  Tooth_Count;
6325    char *Owner;
6327 @end example
6329 In the following examples we will assume that the previous declarations are
6330 located in a file named @cite{animals.h}. The following package demonstrates
6331 how to import these C++ declarations from the Ada side:
6333 @example
6334 with Interfaces.C.Strings; use Interfaces.C.Strings;
6335 package Animals is
6336   type Carnivore is limited interface;
6337   pragma Convention (C_Plus_Plus, Carnivore);
6338   function Number_Of_Teeth (X : Carnivore)
6339      return Natural is abstract;
6341   type Domestic is limited interface;
6342   pragma Convention (C_Plus_Plus, Domestic);
6343   procedure Set_Owner
6344     (X    : in out Domestic;
6345      Name : Chars_Ptr) is abstract;
6347   type Animal is tagged limited record
6348     Age : Natural;
6349   end record;
6350   pragma Import (C_Plus_Plus, Animal);
6352   procedure Set_Age (X : in out Animal; Age : Integer);
6353   pragma Import (C_Plus_Plus, Set_Age);
6355   function Age (X : Animal) return Integer;
6356   pragma Import (C_Plus_Plus, Age);
6358   function New_Animal return Animal;
6359   pragma CPP_Constructor (New_Animal);
6360   pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6362   type Dog is new Animal and Carnivore and Domestic with record
6363     Tooth_Count : Natural;
6364     Owner       : String (1 .. 30);
6365   end record;
6366   pragma Import (C_Plus_Plus, Dog);
6368   function Number_Of_Teeth (A : Dog) return Natural;
6369   pragma Import (C_Plus_Plus, Number_Of_Teeth);
6371   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6372   pragma Import (C_Plus_Plus, Set_Owner);
6374   function New_Dog return Dog;
6375   pragma CPP_Constructor (New_Dog);
6376   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6377 end Animals;
6378 @end example
6380 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6381 interfacing with these C++ classes is easy. The only requirement is that all
6382 the primitives and components must be declared exactly in the same order in
6383 the two languages.
6385 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6386 means of a @cite{pragma Convention (C_Plus_Plus)}, the convention used to pass
6387 the arguments to the called primitives will be the same as for C++. For the
6388 imported classes we use @cite{pragma Import} with convention @cite{C_Plus_Plus}
6389 to indicate that they have been defined on the C++ side; this is required
6390 because the dispatch table associated with these tagged types will be built
6391 in the C++ side and therefore will not contain the predefined Ada primitives
6392 which Ada would otherwise expect.
6394 As the reader can see there is no need to indicate the C++ mangled names
6395 associated with each subprogram because it is assumed that all the calls to
6396 these primitives will be dispatching calls. The only exception is the
6397 constructor, which must be registered with the compiler by means of
6398 @cite{pragma CPP_Constructor} and needs to provide its associated C++
6399 mangled name because the Ada compiler generates direct calls to it.
6401 With the above packages we can now declare objects of type Dog on the Ada side
6402 and dispatch calls to the corresponding subprograms on the C++ side. We can
6403 also extend the tagged type Dog with further fields and primitives, and
6404 override some of its C++ primitives on the Ada side. For example, here we have
6405 a type derivation defined on the Ada side that inherits all the dispatching
6406 primitives of the ancestor from the C++ side.
6408 @example
6409 with Animals; use Animals;
6410 package Vaccinated_Animals is
6411   type Vaccinated_Dog is new Dog with null record;
6412   function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6413 end Vaccinated_Animals;
6414 @end example
6416 It is important to note that, because of the ABI compatibility, the programmer
6417 does not need to add any further information to indicate either the object
6418 layout or the dispatch table entry associated with each dispatching operation.
6420 Now let us define all the types and constructors on the Ada side and export
6421 them to C++, using the same hierarchy of our previous example:
6423 @example
6424 with Interfaces.C.Strings;
6425 use Interfaces.C.Strings;
6426 package Animals is
6427   type Carnivore is limited interface;
6428   pragma Convention (C_Plus_Plus, Carnivore);
6429   function Number_Of_Teeth (X : Carnivore)
6430      return Natural is abstract;
6432   type Domestic is limited interface;
6433   pragma Convention (C_Plus_Plus, Domestic);
6434   procedure Set_Owner
6435     (X    : in out Domestic;
6436      Name : Chars_Ptr) is abstract;
6438   type Animal is tagged record
6439     Age : Natural;
6440   end record;
6441   pragma Convention (C_Plus_Plus, Animal);
6443   procedure Set_Age (X : in out Animal; Age : Integer);
6444   pragma Export (C_Plus_Plus, Set_Age);
6446   function Age (X : Animal) return Integer;
6447   pragma Export (C_Plus_Plus, Age);
6449   function New_Animal return Animal'Class;
6450   pragma Export (C_Plus_Plus, New_Animal);
6452   type Dog is new Animal and Carnivore and Domestic with record
6453     Tooth_Count : Natural;
6454     Owner       : String (1 .. 30);
6455   end record;
6456   pragma Convention (C_Plus_Plus, Dog);
6458   function Number_Of_Teeth (A : Dog) return Natural;
6459   pragma Export (C_Plus_Plus, Number_Of_Teeth);
6461   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6462   pragma Export (C_Plus_Plus, Set_Owner);
6464   function New_Dog return Dog'Class;
6465   pragma Export (C_Plus_Plus, New_Dog);
6466 end Animals;
6467 @end example
6469 Compared with our previous example the only differences are the use of
6470 @cite{pragma Convention} (instead of @cite{pragma Import}), and the use of
6471 @cite{pragma Export} to indicate to the GNAT compiler that the primitives will
6472 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6473 nothing else to be done; as explained above, the only requirement is that all
6474 the primitives and components are declared in exactly the same order.
6476 For completeness, let us see a brief C++ main program that uses the
6477 declarations available in @cite{animals.h} (presented in our first example) to
6478 import and use the declarations from the Ada side, properly initializing and
6479 finalizing the Ada run-time system along the way:
6481 @example
6482 #include "animals.h"
6483 #include <iostream>
6484 using namespace std;
6486 void Check_Carnivore (Carnivore *obj) @{...@}
6487 void Check_Domestic (Domestic *obj)   @{...@}
6488 void Check_Animal (Animal *obj)       @{...@}
6489 void Check_Dog (Dog *obj)             @{...@}
6491 extern "C" @{
6492   void adainit (void);
6493   void adafinal (void);
6494   Dog* new_dog ();
6497 void test ()
6499   Dog *obj = new_dog();  // Ada constructor
6500   Check_Carnivore (obj); // Check secondary DT
6501   Check_Domestic (obj);  // Check secondary DT
6502   Check_Animal (obj);    // Check primary DT
6503   Check_Dog (obj);       // Check primary DT
6506 int main ()
6508   adainit ();  test();  adafinal ();
6509   return 0;
6511 @end example
6513 @node Generating Ada Bindings for C and C++ headers,Generating C Headers for Ada Specifications,Building Mixed Ada and C++ Programs,Mixed Language Programming
6514 @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}
6515 @subsection Generating Ada Bindings for C and C++ headers
6518 @geindex Binding generation (for C and C++ headers)
6520 @geindex C headers (binding generation)
6522 @geindex C++ headers (binding generation)
6524 GNAT includes a binding generator for C and C++ headers which is
6525 intended to do 95% of the tedious work of generating Ada specs from C
6526 or C++ header files.
6528 Note that this capability is not intended to generate 100% correct Ada specs,
6529 and will is some cases require manual adjustments, although it can often
6530 be used out of the box in practice.
6532 Some of the known limitations include:
6535 @itemize *
6537 @item 
6538 only very simple character constant macros are translated into Ada
6539 constants. Function macros (macros with arguments) are partially translated
6540 as comments, to be completed manually if needed.
6542 @item 
6543 some extensions (e.g. vector types) are not supported
6545 @item 
6546 pointers to pointers or complex structures are mapped to System.Address
6548 @item 
6549 identifiers with identical name (except casing) will generate compilation
6550 errors (e.g. @cite{shm_get} vs @cite{SHM_GET}).
6551 @end itemize
6553 The code generated is using the Ada 2005 syntax, which makes it
6554 easier to interface with other languages than previous versions of Ada.
6556 @menu
6557 * Running the Binding Generator:: 
6558 * Generating Bindings for C++ Headers:: 
6559 * Switches:: 
6561 @end menu
6563 @node Running the Binding Generator,Generating Bindings for C++ Headers,,Generating Ada Bindings for C and C++ headers
6564 @anchor{gnat_ugn/the_gnat_compilation_model id71}@anchor{c4}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{c5}
6565 @subsubsection Running the Binding Generator
6568 The binding generator is part of the @emph{gcc} compiler and can be
6569 invoked via the @emph{-fdump-ada-spec} switch, which will generate Ada
6570 spec files for the header files specified on the command line, and all
6571 header files needed by these files transitively. For example:
6573 @example
6574 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
6575 $ gcc -c -gnat05 *.ads
6576 @end example
6578 will generate, under GNU/Linux, the following files: @code{time_h.ads},
6579 @code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6580 correspond to the files @code{/usr/include/time.h},
6581 @code{/usr/include/bits/time.h}, etc..., and will then compile in Ada 2005
6582 mode these Ada specs.
6584 The @cite{-C} switch tells @emph{gcc} to extract comments from headers,
6585 and will attempt to generate corresponding Ada comments.
6587 If you want to generate a single Ada file and not the transitive closure, you
6588 can use instead the @emph{-fdump-ada-spec-slim} switch.
6590 You can optionally specify a parent unit, of which all generated units will
6591 be children, using @cite{-fada-spec-parent=<unit>}.
6593 Note that we recommend when possible to use the @emph{g++} driver to
6594 generate bindings, even for most C headers, since this will in general
6595 generate better Ada specs. For generating bindings for C++ headers, it is
6596 mandatory to use the @emph{g++} command, or @emph{gcc -x c++} which
6597 is equivalent in this case. If @emph{g++} cannot work on your C headers
6598 because of incompatibilities between C and C++, then you can fallback to
6599 @emph{gcc} instead.
6601 For an example of better bindings generated from the C++ front-end,
6602 the name of the parameters (when available) are actually ignored by the C
6603 front-end. Consider the following C header:
6605 @example
6606 extern void foo (int variable);
6607 @end example
6609 with the C front-end, @cite{variable} is ignored, and the above is handled as:
6611 @example
6612 extern void foo (int);
6613 @end example
6615 generating a generic:
6617 @example
6618 procedure foo (param1 : int);
6619 @end example
6621 with the C++ front-end, the name is available, and we generate:
6623 @example
6624 procedure foo (variable : int);
6625 @end example
6627 In some cases, the generated bindings will be more complete or more meaningful
6628 when defining some macros, which you can do via the @emph{-D} switch. This
6629 is for example the case with @code{Xlib.h} under GNU/Linux:
6631 @example
6632 $ g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6633 @end example
6635 The above will generate more complete bindings than a straight call without
6636 the @emph{-DXLIB_ILLEGAL_ACCESS} switch.
6638 In other cases, it is not possible to parse a header file in a stand-alone
6639 manner, because other include files need to be included first. In this
6640 case, the solution is to create a small header file including the needed
6641 @cite{#include} and possible @cite{#define} directives. For example, to
6642 generate Ada bindings for @code{readline/readline.h}, you need to first
6643 include @code{stdio.h}, so you can create a file with the following two
6644 lines in e.g. @code{readline1.h}:
6646 @example
6647 #include <stdio.h>
6648 #include <readline/readline.h>
6649 @end example
6651 and then generate Ada bindings from this file:
6653 @example
6654 $ g++ -c -fdump-ada-spec readline1.h
6655 @end example
6657 @node Generating Bindings for C++ Headers,Switches,Running the Binding Generator,Generating Ada Bindings for C and C++ headers
6658 @anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{c6}@anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{c7}
6659 @subsubsection Generating Bindings for C++ Headers
6662 Generating bindings for C++ headers is done using the same options, always
6663 with the @emph{g++} compiler. Note that generating Ada spec from C++ headers is a
6664 much more complex job and support for C++ headers is much more limited that
6665 support for C headers. As a result, you will need to modify the resulting
6666 bindings by hand more extensively when using C++ headers.
6668 In this mode, C++ classes will be mapped to Ada tagged types, constructors
6669 will be mapped using the @cite{CPP_Constructor} pragma, and when possible,
6670 multiple inheritance of abstract classes will be mapped to Ada interfaces
6671 (see the @emph{Interfacing to C++} section in the @cite{GNAT Reference Manual}
6672 for additional information on interfacing to C++).
6674 For example, given the following C++ header file:
6676 @example
6677 class Carnivore @{
6678 public:
6679    virtual int Number_Of_Teeth () = 0;
6682 class Domestic @{
6683 public:
6684    virtual void Set_Owner (char* Name) = 0;
6687 class Animal @{
6688 public:
6689   int Age_Count;
6690   virtual void Set_Age (int New_Age);
6693 class Dog : Animal, Carnivore, Domestic @{
6694  public:
6695   int  Tooth_Count;
6696   char *Owner;
6698   virtual int  Number_Of_Teeth ();
6699   virtual void Set_Owner (char* Name);
6701   Dog();
6703 @end example
6705 The corresponding Ada code is generated:
6707 @example
6708 package Class_Carnivore is
6709   type Carnivore is limited interface;
6710   pragma Import (CPP, Carnivore);
6712   function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6713 end;
6714 use Class_Carnivore;
6716 package Class_Domestic is
6717   type Domestic is limited interface;
6718   pragma Import (CPP, Domestic);
6720   procedure Set_Owner
6721     (this : access Domestic;
6722      Name : Interfaces.C.Strings.chars_ptr) is abstract;
6723 end;
6724 use Class_Domestic;
6726 package Class_Animal is
6727   type Animal is tagged limited record
6728     Age_Count : aliased int;
6729   end record;
6730   pragma Import (CPP, Animal);
6732   procedure Set_Age (this : access Animal; New_Age : int);
6733   pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6734 end;
6735 use Class_Animal;
6737 package Class_Dog is
6738   type Dog is new Animal and Carnivore and Domestic with record
6739     Tooth_Count : aliased int;
6740     Owner : Interfaces.C.Strings.chars_ptr;
6741   end record;
6742   pragma Import (CPP, Dog);
6744   function Number_Of_Teeth (this : access Dog) return int;
6745   pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6747   procedure Set_Owner
6748     (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6749   pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6751   function New_Dog return Dog;
6752   pragma CPP_Constructor (New_Dog);
6753   pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6754 end;
6755 use Class_Dog;
6756 @end example
6758 @node Switches,,Generating Bindings for C++ Headers,Generating Ada Bindings for C and C++ headers
6759 @anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{c8}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{c9}
6760 @subsubsection Switches
6763 @geindex -fdump-ada-spec (gcc)
6766 @table @asis
6768 @item @code{-fdump-ada-spec}
6770 Generate Ada spec files for the given header files transitively (including
6771 all header files that these headers depend upon).
6772 @end table
6774 @geindex -fdump-ada-spec-slim (gcc)
6777 @table @asis
6779 @item @code{-fdump-ada-spec-slim}
6781 Generate Ada spec files for the header files specified on the command line
6782 only.
6783 @end table
6785 @geindex -fada-spec-parent (gcc)
6788 @table @asis
6790 @item @code{-fada-spec-parent=@emph{unit}}
6792 Specifies that all files generated by @emph{-fdump-ada-spec*} are
6793 to be child units of the specified parent unit.
6794 @end table
6796 @geindex -C (gcc)
6799 @table @asis
6801 @item @code{-C}
6803 Extract comments from headers and generate Ada comments in the Ada spec files.
6804 @end table
6806 @node Generating C Headers for Ada Specifications,,Generating Ada Bindings for C and C++ headers,Mixed Language Programming
6807 @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}
6808 @subsection Generating C Headers for Ada Specifications
6811 @geindex Binding generation (for Ada specs)
6813 @geindex C headers (binding generation)
6815 GNAT includes a C header generator for Ada specifications which supports
6816 Ada types that have a direct mapping to C types. This includes in particular
6817 support for:
6820 @itemize *
6822 @item 
6823 Scalar types
6825 @item 
6826 Constrained arrays
6828 @item 
6829 Records (untagged)
6831 @item 
6832 Composition of the above types
6834 @item 
6835 Constant declarations
6837 @item 
6838 Object declarations
6840 @item 
6841 Subprogram declarations
6842 @end itemize
6844 @menu
6845 * Running the C Header Generator:: 
6847 @end menu
6849 @node Running the C Header Generator,,,Generating C Headers for Ada Specifications
6850 @anchor{gnat_ugn/the_gnat_compilation_model running-the-c-header-generator}@anchor{cc}
6851 @subsubsection Running the C Header Generator
6854 The C header generator is part of the GNAT compiler and can be invoked via
6855 the @emph{-gnatceg} combination of switches, which will generate a @code{.h}
6856 file corresponding to the given input file (Ada spec or body). Note that
6857 only spec files are processed in any case, so giving a spec or a body file
6858 as input is equivalent. For example:
6860 @example
6861 $ gcc -c -gnatceg pack1.ads
6862 @end example
6864 will generate a self-contained file called @code{pack1.h} including
6865 common definitions from the Ada Standard package, followed by the
6866 definitions included in @code{pack1.ads}, as well as all the other units
6867 withed by this file.
6869 For instance, given the following Ada files:
6871 @example
6872 package Pack2 is
6873    type Int is range 1 .. 10;
6874 end Pack2;
6875 @end example
6877 @example
6878 with Pack2;
6880 package Pack1 is
6881    type Rec is record
6882       Field1, Field2 : Pack2.Int;
6883    end record;
6885    Global : Rec := (1, 2);
6887    procedure Proc1 (R : Rec);
6888    procedure Proc2 (R : in out Rec);
6889 end Pack1;
6890 @end example
6892 The above @cite{gcc} command will generate the following @code{pack1.h} file:
6894 @example
6895 /* Standard definitions skipped */
6896 #ifndef PACK2_ADS
6897 #define PACK2_ADS
6898 typedef short_short_integer pack2__TintB;
6899 typedef pack2__TintB pack2__int;
6900 #endif /* PACK2_ADS */
6902 #ifndef PACK1_ADS
6903 #define PACK1_ADS
6904 typedef struct _pack1__rec @{
6905   pack2__int field1;
6906   pack2__int field2;
6907 @} pack1__rec;
6908 extern pack1__rec pack1__global;
6909 extern void pack1__proc1(const pack1__rec r);
6910 extern void pack1__proc2(pack1__rec *r);
6911 #endif /* PACK1_ADS */
6912 @end example
6914 You can then @cite{include} @code{pack1.h} from a C source file and use the types,
6915 call subprograms, reference objects, and constants.
6917 @node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
6918 @anchor{gnat_ugn/the_gnat_compilation_model id74}@anchor{cd}@anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{45}
6919 @section GNAT and Other Compilation Models
6922 This section compares the GNAT model with the approaches taken in
6923 other environents, first the C/C++ model and then the mechanism that
6924 has been used in other Ada systems, in particular those traditionally
6925 used for Ada 83.
6927 @menu
6928 * Comparison between GNAT and C/C++ Compilation Models:: 
6929 * Comparison between GNAT and Conventional Ada Library Models:: 
6931 @end menu
6933 @node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
6934 @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}
6935 @subsection Comparison between GNAT and C/C++ Compilation Models
6938 The GNAT model of compilation is close to the C and C++ models. You can
6939 think of Ada specs as corresponding to header files in C. As in C, you
6940 don't need to compile specs; they are compiled when they are used. The
6941 Ada @emph{with} is similar in effect to the @cite{#include} of a C
6942 header.
6944 One notable difference is that, in Ada, you may compile specs separately
6945 to check them for semantic and syntactic accuracy. This is not always
6946 possible with C headers because they are fragments of programs that have
6947 less specific syntactic or semantic rules.
6949 The other major difference is the requirement for running the binder,
6950 which performs two important functions. First, it checks for
6951 consistency. In C or C++, the only defense against assembling
6952 inconsistent programs lies outside the compiler, in a makefile, for
6953 example. The binder satisfies the Ada requirement that it be impossible
6954 to construct an inconsistent program when the compiler is used in normal
6955 mode.
6957 @geindex Elaboration order control
6959 The other important function of the binder is to deal with elaboration
6960 issues. There are also elaboration issues in C++ that are handled
6961 automatically. This automatic handling has the advantage of being
6962 simpler to use, but the C++ programmer has no control over elaboration.
6963 Where @cite{gnatbind} might complain there was no valid order of
6964 elaboration, a C++ compiler would simply construct a program that
6965 malfunctioned at run time.
6967 @node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
6968 @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}
6969 @subsection Comparison between GNAT and Conventional Ada Library Models
6972 This section is intended for Ada programmers who have
6973 used an Ada compiler implementing the traditional Ada library
6974 model, as described in the Ada Reference Manual.
6976 @geindex GNAT library
6978 In GNAT, there is no 'library' in the normal sense. Instead, the set of
6979 source files themselves acts as the library. Compiling Ada programs does
6980 not generate any centralized information, but rather an object file and
6981 a ALI file, which are of interest only to the binder and linker.
6982 In a traditional system, the compiler reads information not only from
6983 the source file being compiled, but also from the centralized library.
6984 This means that the effect of a compilation depends on what has been
6985 previously compiled. In particular:
6988 @itemize *
6990 @item 
6991 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
6992 to the version of the unit most recently compiled into the library.
6994 @item 
6995 Inlining is effective only if the necessary body has already been
6996 compiled into the library.
6998 @item 
6999 Compiling a unit may obsolete other units in the library.
7000 @end itemize
7002 In GNAT, compiling one unit never affects the compilation of any other
7003 units because the compiler reads only source files. Only changes to source
7004 files can affect the results of a compilation. In particular:
7007 @itemize *
7009 @item 
7010 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7011 to the source version of the unit that is currently accessible to the
7012 compiler.
7014 @geindex Inlining
7016 @item 
7017 Inlining requires the appropriate source files for the package or
7018 subprogram bodies to be available to the compiler. Inlining is always
7019 effective, independent of the order in which units are compiled.
7021 @item 
7022 Compiling a unit never affects any other compilations. The editing of
7023 sources may cause previous compilations to be out of date if they
7024 depended on the source file being modified.
7025 @end itemize
7027 The most important result of these differences is that order of compilation
7028 is never significant in GNAT. There is no situation in which one is
7029 required to do one compilation before another. What shows up as order of
7030 compilation requirements in the traditional Ada library becomes, in
7031 GNAT, simple source dependencies; in other words, there is only a set
7032 of rules saying what source files must be present when a file is
7033 compiled.
7035 @node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
7036 @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}
7037 @section Using GNAT Files with External Tools
7040 This section explains how files that are produced by GNAT may be
7041 used with tools designed for other languages.
7043 @menu
7044 * Using Other Utility Programs with GNAT:: 
7045 * The External Symbol Naming Scheme of GNAT:: 
7047 @end menu
7049 @node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
7050 @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}
7051 @subsection Using Other Utility Programs with GNAT
7054 The object files generated by GNAT are in standard system format and in
7055 particular the debugging information uses this format. This means
7056 programs generated by GNAT can be used with existing utilities that
7057 depend on these formats.
7059 In general, any utility program that works with C will also often work with
7060 Ada programs generated by GNAT. This includes software utilities such as
7061 gprof (a profiling program), gdb (the FSF debugger), and utilities such
7062 as Purify.
7064 @node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
7065 @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}
7066 @subsection The External Symbol Naming Scheme of GNAT
7069 In order to interpret the output from GNAT, when using tools that are
7070 originally intended for use with other languages, it is useful to
7071 understand the conventions used to generate link names from the Ada
7072 entity names.
7074 All link names are in all lowercase letters. With the exception of library
7075 procedure names, the mechanism used is simply to use the full expanded
7076 Ada name with dots replaced by double underscores. For example, suppose
7077 we have the following package spec:
7079 @example
7080 package QRS is
7081    MN : Integer;
7082 end QRS;
7083 @end example
7085 @geindex pragma Export
7087 The variable @cite{MN} has a full expanded Ada name of @cite{QRS.MN}, so
7088 the corresponding link name is @cite{qrs__mn}.
7089 Of course if a @cite{pragma Export} is used this may be overridden:
7091 @example
7092 package Exports is
7093    Var1 : Integer;
7094    pragma Export (Var1, C, External_Name => "var1_name");
7095    Var2 : Integer;
7096    pragma Export (Var2, C, Link_Name => "var2_link_name");
7097 end Exports;
7098 @end example
7100 In this case, the link name for @cite{Var1} is whatever link name the
7101 C compiler would assign for the C function @cite{var1_name}. This typically
7102 would be either @cite{var1_name} or @cite{_var1_name}, depending on operating
7103 system conventions, but other possibilities exist. The link name for
7104 @cite{Var2} is @cite{var2_link_name}, and this is not operating system
7105 dependent.
7107 One exception occurs for library level procedures. A potential ambiguity
7108 arises between the required name @cite{_main} for the C main program,
7109 and the name we would otherwise assign to an Ada library level procedure
7110 called @cite{Main} (which might well not be the main program).
7112 To avoid this ambiguity, we attach the prefix @cite{_ada_} to such
7113 names. So if we have a library level procedure such as:
7115 @example
7116 procedure Hello (S : String);
7117 @end example
7119 the external name of this procedure will be @cite{_ada_hello}.
7121 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7123 @node Building Executable Programs with GNAT,GNAT Utility Programs,The GNAT Compilation Model,Top
7124 @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}
7125 @chapter Building Executable Programs with GNAT
7128 This chapter describes first the gnatmake tool
7129 (@ref{1b,,Building with gnatmake}),
7130 which automatically determines the set of sources
7131 needed by an Ada compilation unit and executes the necessary
7132 (re)compilations, binding and linking.
7133 It also explains how to use each tool individually: the
7134 compiler (gcc, see @ref{1c,,Compiling with gcc}),
7135 binder (gnatbind, see @ref{1d,,Binding with gnatbind}),
7136 and linker (gnatlink, see @ref{1e,,Linking with gnatlink})
7137 to build executable programs.
7138 Finally, this chapter provides examples of
7139 how to make use of the general GNU make mechanism
7140 in a GNAT context (see @ref{1f,,Using the GNU make Utility}).
7143 @menu
7144 * Building with gnatmake:: 
7145 * Compiling with gcc:: 
7146 * Compiler Switches:: 
7147 * Binding with gnatbind:: 
7148 * Linking with gnatlink:: 
7149 * Using the GNU make Utility:: 
7151 @end menu
7153 @node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
7154 @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}
7155 @section Building with @emph{gnatmake}
7158 @geindex gnatmake
7160 A typical development cycle when working on an Ada program consists of
7161 the following steps:
7164 @enumerate 
7166 @item 
7167 Edit some sources to fix bugs;
7169 @item 
7170 Add enhancements;
7172 @item 
7173 Compile all sources affected;
7175 @item 
7176 Rebind and relink; and
7178 @item 
7179 Test.
7180 @end enumerate
7182 @geindex Dependency rules (compilation)
7184 The third step in particular can be tricky, because not only do the modified
7185 files have to be compiled, but any files depending on these files must also be
7186 recompiled. The dependency rules in Ada can be quite complex, especially
7187 in the presence of overloading, @cite{use} clauses, generics and inlined
7188 subprograms.
7190 @emph{gnatmake} automatically takes care of the third and fourth steps
7191 of this process. It determines which sources need to be compiled,
7192 compiles them, and binds and links the resulting object files.
7194 Unlike some other Ada make programs, the dependencies are always
7195 accurately recomputed from the new sources. The source based approach of
7196 the GNAT compilation model makes this possible. This means that if
7197 changes to the source program cause corresponding changes in
7198 dependencies, they will always be tracked exactly correctly by
7199 @emph{gnatmake}.
7201 Note that for advanced forms of project structure, we recommend creating
7202 a project file as explained in the @emph{GNAT_Project_Manager} chapter in the
7203 @emph{GPRbuild User's Guide}, and using the
7204 @emph{gprbuild} tool which supports building with project files and works similarly
7205 to @emph{gnatmake}.
7207 @menu
7208 * Running gnatmake:: 
7209 * Switches for gnatmake:: 
7210 * Mode Switches for gnatmake:: 
7211 * Notes on the Command Line:: 
7212 * How gnatmake Works:: 
7213 * Examples of gnatmake Usage:: 
7215 @end menu
7217 @node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7218 @anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{da}@anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{db}
7219 @subsection Running @emph{gnatmake}
7222 The usual form of the @emph{gnatmake} command is
7224 @example
7225 $ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7226 @end example
7228 The only required argument is one @cite{file_name}, which specifies
7229 a compilation unit that is a main program. Several @cite{file_names} can be
7230 specified: this will result in several executables being built.
7231 If @cite{switches} are present, they can be placed before the first
7232 @cite{file_name}, between @cite{file_names} or after the last @cite{file_name}.
7233 If @cite{mode_switches} are present, they must always be placed after
7234 the last @cite{file_name} and all @cite{switches}.
7236 If you are using standard file extensions (@code{.adb} and
7237 @code{.ads}), then the
7238 extension may be omitted from the @cite{file_name} arguments. However, if
7239 you are using non-standard extensions, then it is required that the
7240 extension be given. A relative or absolute directory path can be
7241 specified in a @cite{file_name}, in which case, the input source file will
7242 be searched for in the specified directory only. Otherwise, the input
7243 source file will first be searched in the directory where
7244 @emph{gnatmake} was invoked and if it is not found, it will be search on
7245 the source path of the compiler as described in
7246 @ref{89,,Search Paths and the Run-Time Library (RTL)}.
7248 All @emph{gnatmake} output (except when you specify @emph{-M}) is sent to
7249 @code{stderr}. The output produced by the
7250 @emph{-M} switch is sent to @code{stdout}.
7252 @node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7253 @anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{dc}@anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{dd}
7254 @subsection Switches for @emph{gnatmake}
7257 You may specify any of the following switches to @emph{gnatmake}:
7259 @geindex --version (gnatmake)
7262 @table @asis
7264 @item @code{--version}
7266 Display Copyright and version, then exit disregarding all other options.
7267 @end table
7269 @geindex --help (gnatmake)
7272 @table @asis
7274 @item @code{--help}
7276 If @code{--version} was not used, display usage, then exit disregarding
7277 all other options.
7278 @end table
7280 @geindex --GCC=compiler_name (gnatmake)
7283 @table @asis
7285 @item @code{--GCC=@emph{compiler_name}}
7287 Program used for compiling. The default is @code{gcc}. You need to use
7288 quotes around @cite{compiler_name} if @cite{compiler_name} contains
7289 spaces or other separator characters.
7290 As an example @code{--GCC="foo -x  -y"}
7291 will instruct @emph{gnatmake} to use @code{foo -x -y} as your
7292 compiler. A limitation of this syntax is that the name and path name of
7293 the executable itself must not include any embedded spaces. Note that
7294 switch @code{-c} is always inserted after your command name. Thus in the
7295 above example the compiler command that will be used by @emph{gnatmake}
7296 will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7297 used, only the last @cite{compiler_name} is taken into account. However,
7298 all the additional switches are also taken into account. Thus,
7299 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7300 @code{--GCC="bar -x -y -z -t"}.
7301 @end table
7303 @geindex --GNATBIND=binder_name (gnatmake)
7306 @table @asis
7308 @item @code{--GNATBIND=@emph{binder_name}}
7310 Program used for binding. The default is @code{gnatbind}. You need to
7311 use quotes around @cite{binder_name} if @cite{binder_name} contains spaces
7312 or other separator characters.
7313 As an example @code{--GNATBIND="bar -x  -y"}
7314 will instruct @emph{gnatmake} to use @cite{bar -x -y} as your
7315 binder. Binder switches that are normally appended by @emph{gnatmake}
7316 to @code{gnatbind} are now appended to the end of @cite{bar -x -y}.
7317 A limitation of this syntax is that the name and path name of the executable
7318 itself must not include any embedded spaces.
7319 @end table
7321 @geindex --GNATLINK=linker_name (gnatmake)
7324 @table @asis
7326 @item @code{--GNATLINK=@emph{linker_name}}
7328 Program used for linking. The default is @code{gnatlink}. You need to
7329 use quotes around @cite{linker_name} if @cite{linker_name} contains spaces
7330 or other separator characters.
7331 As an example @code{--GNATLINK="lan -x  -y"}
7332 will instruct @emph{gnatmake} to use @code{lan -x -y} as your
7333 linker. Linker switches that are normally appended by @code{gnatmake} to
7334 @code{gnatlink} are now appended to the end of @code{lan -x -y}.
7335 A limitation of this syntax is that the name and path name of the executable
7336 itself must not include any embedded spaces.
7338 @item @code{--create-map-file}
7340 When linking an executable, create a map file. The name of the map file
7341 has the same name as the executable with extension ".map".
7343 @item @code{--create-map-file=@emph{mapfile}}
7345 When linking an executable, create a map file with the specified name.
7346 @end table
7348 @geindex --create-missing-dirs (gnatmake)
7351 @table @asis
7353 @item @code{--create-missing-dirs}
7355 When using project files (@code{-P@emph{project}}), automatically create
7356 missing object directories, library directories and exec
7357 directories.
7359 @item @code{--single-compile-per-obj-dir}
7361 Disallow simultaneous compilations in the same object directory when
7362 project files are used.
7364 @item @code{--subdirs=@emph{subdir}}
7366 Actual object directory of each project file is the subdirectory subdir of the
7367 object directory specified or defaulted in the project file.
7369 @item @code{--unchecked-shared-lib-imports}
7371 By default, shared library projects are not allowed to import static library
7372 projects. When this switch is used on the command line, this restriction is
7373 relaxed.
7375 @item @code{--source-info=@emph{source info file}}
7377 Specify a source info file. This switch is active only when project files
7378 are used. If the source info file is specified as a relative path, then it is
7379 relative to the object directory of the main project. If the source info file
7380 does not exist, then after the Project Manager has successfully parsed and
7381 processed the project files and found the sources, it creates the source info
7382 file. If the source info file already exists and can be read successfully,
7383 then the Project Manager will get all the needed information about the sources
7384 from the source info file and will not look for them. This reduces the time
7385 to process the project files, especially when looking for sources that take a
7386 long time. If the source info file exists but cannot be parsed successfully,
7387 the Project Manager will attempt to recreate it. If the Project Manager fails
7388 to create the source info file, a message is issued, but gnatmake does not
7389 fail. @emph{gnatmake} "trusts" the source info file. This means that
7390 if the source files have changed (addition, deletion, moving to a different
7391 source directory), then the source info file need to be deleted and recreated.
7392 @end table
7394 @geindex -a (gnatmake)
7397 @table @asis
7399 @item @code{-a}
7401 Consider all files in the make process, even the GNAT internal system
7402 files (for example, the predefined Ada library files), as well as any
7403 locked files. Locked files are files whose ALI file is write-protected.
7404 By default,
7405 @emph{gnatmake} does not check these files,
7406 because the assumption is that the GNAT internal files are properly up
7407 to date, and also that any write protected ALI files have been properly
7408 installed. Note that if there is an installation problem, such that one
7409 of these files is not up to date, it will be properly caught by the
7410 binder.
7411 You may have to specify this switch if you are working on GNAT
7412 itself. The switch @code{-a} is also useful
7413 in conjunction with @code{-f}
7414 if you need to recompile an entire application,
7415 including run-time files, using special configuration pragmas,
7416 such as a @cite{Normalize_Scalars} pragma.
7418 By default
7419 @code{gnatmake -a} compiles all GNAT
7420 internal files with
7421 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7422 @end table
7424 @geindex -b (gnatmake)
7427 @table @asis
7429 @item @code{-b}
7431 Bind only. Can be combined with @emph{-c} to do
7432 compilation and binding, but no link.
7433 Can be combined with @emph{-l}
7434 to do binding and linking. When not combined with
7435 @emph{-c}
7436 all the units in the closure of the main program must have been previously
7437 compiled and must be up to date. The root unit specified by @cite{file_name}
7438 may be given without extension, with the source extension or, if no GNAT
7439 Project File is specified, with the ALI file extension.
7440 @end table
7442 @geindex -c (gnatmake)
7445 @table @asis
7447 @item @code{-c}
7449 Compile only. Do not perform binding, except when @emph{-b}
7450 is also specified. Do not perform linking, except if both
7451 @emph{-b} and
7452 @emph{-l} are also specified.
7453 If the root unit specified by @cite{file_name} is not a main unit, this is the
7454 default. Otherwise @emph{gnatmake} will attempt binding and linking
7455 unless all objects are up to date and the executable is more recent than
7456 the objects.
7457 @end table
7459 @geindex -C (gnatmake)
7462 @table @asis
7464 @item @code{-C}
7466 Use a temporary mapping file. A mapping file is a way to communicate
7467 to the compiler two mappings: from unit names to file names (without
7468 any directory information) and from file names to path names (with
7469 full directory information). A mapping file can make the compiler's
7470 file searches faster, especially if there are many source directories,
7471 or the sources are read over a slow network connection. If
7472 @emph{-P} is used, a mapping file is always used, so
7473 @emph{-C} is unnecessary; in this case the mapping file
7474 is initially populated based on the project file. If
7475 @emph{-C} is used without
7476 @emph{-P},
7477 the mapping file is initially empty. Each invocation of the compiler
7478 will add any newly accessed sources to the mapping file.
7479 @end table
7481 @geindex -C= (gnatmake)
7484 @table @asis
7486 @item @code{-C=@emph{file}}
7488 Use a specific mapping file. The file, specified as a path name (absolute or
7489 relative) by this switch, should already exist, otherwise the switch is
7490 ineffective. The specified mapping file will be communicated to the compiler.
7491 This switch is not compatible with a project file
7492 (-P`file`) or with multiple compiling processes
7493 (-jnnn, when nnn is greater than 1).
7494 @end table
7496 @geindex -d (gnatmake)
7499 @table @asis
7501 @item @code{-d}
7503 Display progress for each source, up to date or not, as a single line:
7505 @example
7506 completed x out of y (zz%)
7507 @end example
7509 If the file needs to be compiled this is displayed after the invocation of
7510 the compiler. These lines are displayed even in quiet output mode.
7511 @end table
7513 @geindex -D (gnatmake)
7516 @table @asis
7518 @item @code{-D @emph{dir}}
7520 Put all object files and ALI file in directory @cite{dir}.
7521 If the @emph{-D} switch is not used, all object files
7522 and ALI files go in the current working directory.
7524 This switch cannot be used when using a project file.
7525 @end table
7527 @geindex -eI (gnatmake)
7530 @table @asis
7532 @item @code{-eI@emph{nnn}}
7534 Indicates that the main source is a multi-unit source and the rank of the unit
7535 in the source file is nnn. nnn needs to be a positive number and a valid
7536 index in the source. This switch cannot be used when @emph{gnatmake} is
7537 invoked for several mains.
7538 @end table
7540 @geindex -eL (gnatmake)
7542 @geindex symbolic links
7545 @table @asis
7547 @item @code{-eL}
7549 Follow all symbolic links when processing project files.
7550 This should be used if your project uses symbolic links for files or
7551 directories, but is not needed in other cases.
7553 @geindex naming scheme
7555 This also assumes that no directory matches the naming scheme for files (for
7556 instance that you do not have a directory called "sources.ads" when using the
7557 default GNAT naming scheme).
7559 When you do not have to use this switch (i.e., by default), gnatmake is able to
7560 save a lot of system calls (several per source file and object file), which
7561 can result in a significant speed up to load and manipulate a project file,
7562 especially when using source files from a remote system.
7563 @end table
7565 @geindex -eS (gnatmake)
7568 @table @asis
7570 @item @code{-eS}
7572 Output the commands for the compiler, the binder and the linker
7573 on standard output,
7574 instead of standard error.
7575 @end table
7577 @geindex -f (gnatmake)
7580 @table @asis
7582 @item @code{-f}
7584 Force recompilations. Recompile all sources, even though some object
7585 files may be up to date, but don't recompile predefined or GNAT internal
7586 files or locked files (files with a write-protected ALI file),
7587 unless the @emph{-a} switch is also specified.
7588 @end table
7590 @geindex -F (gnatmake)
7593 @table @asis
7595 @item @code{-F}
7597 When using project files, if some errors or warnings are detected during
7598 parsing and verbose mode is not in effect (no use of switch
7599 -v), then error lines start with the full path name of the project
7600 file, rather than its simple file name.
7601 @end table
7603 @geindex -g (gnatmake)
7606 @table @asis
7608 @item @code{-g}
7610 Enable debugging. This switch is simply passed to the compiler and to the
7611 linker.
7612 @end table
7614 @geindex -i (gnatmake)
7617 @table @asis
7619 @item @code{-i}
7621 In normal mode, @emph{gnatmake} compiles all object files and ALI files
7622 into the current directory. If the @emph{-i} switch is used,
7623 then instead object files and ALI files that already exist are overwritten
7624 in place. This means that once a large project is organized into separate
7625 directories in the desired manner, then @emph{gnatmake} will automatically
7626 maintain and update this organization. If no ALI files are found on the
7627 Ada object path (see @ref{89,,Search Paths and the Run-Time Library (RTL)}),
7628 the new object and ALI files are created in the
7629 directory containing the source being compiled. If another organization
7630 is desired, where objects and sources are kept in different directories,
7631 a useful technique is to create dummy ALI files in the desired directories.
7632 When detecting such a dummy file, @emph{gnatmake} will be forced to
7633 recompile the corresponding source file, and it will be put the resulting
7634 object and ALI files in the directory where it found the dummy file.
7635 @end table
7637 @geindex -j (gnatmake)
7639 @geindex Parallel make
7642 @table @asis
7644 @item @code{-j@emph{n}}
7646 Use @cite{n} processes to carry out the (re)compilations. On a multiprocessor
7647 machine compilations will occur in parallel. If @cite{n} is 0, then the
7648 maximum number of parallel compilations is the number of core processors
7649 on the platform. In the event of compilation errors, messages from various
7650 compilations might get interspersed (but @emph{gnatmake} will give you the
7651 full ordered list of failing compiles at the end). If this is problematic,
7652 rerun the make process with n set to 1 to get a clean list of messages.
7653 @end table
7655 @geindex -k (gnatmake)
7658 @table @asis
7660 @item @code{-k}
7662 Keep going. Continue as much as possible after a compilation error. To
7663 ease the programmer's task in case of compilation errors, the list of
7664 sources for which the compile fails is given when @emph{gnatmake}
7665 terminates.
7667 If @emph{gnatmake} is invoked with several @code{file_names} and with this
7668 switch, if there are compilation errors when building an executable,
7669 @emph{gnatmake} will not attempt to build the following executables.
7670 @end table
7672 @geindex -l (gnatmake)
7675 @table @asis
7677 @item @code{-l}
7679 Link only. Can be combined with @emph{-b} to binding
7680 and linking. Linking will not be performed if combined with
7681 @emph{-c}
7682 but not with @emph{-b}.
7683 When not combined with @emph{-b}
7684 all the units in the closure of the main program must have been previously
7685 compiled and must be up to date, and the main program needs to have been bound.
7686 The root unit specified by @cite{file_name}
7687 may be given without extension, with the source extension or, if no GNAT
7688 Project File is specified, with the ALI file extension.
7689 @end table
7691 @geindex -m (gnatmake)
7694 @table @asis
7696 @item @code{-m}
7698 Specify that the minimum necessary amount of recompilations
7699 be performed. In this mode @emph{gnatmake} ignores time
7700 stamp differences when the only
7701 modifications to a source file consist in adding/removing comments,
7702 empty lines, spaces or tabs. This means that if you have changed the
7703 comments in a source file or have simply reformatted it, using this
7704 switch will tell @emph{gnatmake} not to recompile files that depend on it
7705 (provided other sources on which these files depend have undergone no
7706 semantic modifications). Note that the debugging information may be
7707 out of date with respect to the sources if the @emph{-m} switch causes
7708 a compilation to be switched, so the use of this switch represents a
7709 trade-off between compilation time and accurate debugging information.
7710 @end table
7712 @geindex Dependencies
7713 @geindex producing list
7715 @geindex -M (gnatmake)
7718 @table @asis
7720 @item @code{-M}
7722 Check if all objects are up to date. If they are, output the object
7723 dependences to @code{stdout} in a form that can be directly exploited in
7724 a @code{Makefile}. By default, each source file is prefixed with its
7725 (relative or absolute) directory name. This name is whatever you
7726 specified in the various @emph{-aI}
7727 and @emph{-I} switches. If you use
7728 @cite{gnatmake -M}  @emph{-q}
7729 (see below), only the source file names,
7730 without relative paths, are output. If you just specify the  @emph{-M}
7731 switch, dependencies of the GNAT internal system files are omitted. This
7732 is typically what you want. If you also specify
7733 the @emph{-a} switch,
7734 dependencies of the GNAT internal files are also listed. Note that
7735 dependencies of the objects in external Ada libraries (see
7736 switch  @code{-aL@emph{dir}} in the following list)
7737 are never reported.
7738 @end table
7740 @geindex -n (gnatmake)
7743 @table @asis
7745 @item @code{-n}
7747 Don't compile, bind, or link. Checks if all objects are up to date.
7748 If they are not, the full name of the first file that needs to be
7749 recompiled is printed.
7750 Repeated use of this option, followed by compiling the indicated source
7751 file, will eventually result in recompiling all required units.
7752 @end table
7754 @geindex -o (gnatmake)
7757 @table @asis
7759 @item @code{-o @emph{exec_name}}
7761 Output executable name. The name of the final executable program will be
7762 @cite{exec_name}. If the @emph{-o} switch is omitted the default
7763 name for the executable will be the name of the input file in appropriate form
7764 for an executable file on the host system.
7766 This switch cannot be used when invoking @emph{gnatmake} with several
7767 @code{file_names}.
7768 @end table
7770 @geindex -p (gnatmake)
7773 @table @asis
7775 @item @code{-p}
7777 Same as @code{--create-missing-dirs}
7778 @end table
7780 @geindex -P (gnatmake)
7783 @table @asis
7785 @item @code{-P@emph{project}}
7787 Use project file @cite{project}. Only one such switch can be used.
7788 @end table
7790 @c -- Comment:
7791 @c :ref:`gnatmake_and_Project_Files`.
7793 @geindex -q (gnatmake)
7796 @table @asis
7798 @item @code{-q}
7800 Quiet. When this flag is not set, the commands carried out by
7801 @emph{gnatmake} are displayed.
7802 @end table
7804 @geindex -s (gnatmake)
7807 @table @asis
7809 @item @code{-s}
7811 Recompile if compiler switches have changed since last compilation.
7812 All compiler switches but -I and -o are taken into account in the
7813 following way:
7814 orders between different 'first letter' switches are ignored, but
7815 orders between same switches are taken into account. For example,
7816 @emph{-O -O2} is different than @emph{-O2 -O}, but @emph{-g -O}
7817 is equivalent to @emph{-O -g}.
7819 This switch is recommended when Integrated Preprocessing is used.
7820 @end table
7822 @geindex -u (gnatmake)
7825 @table @asis
7827 @item @code{-u}
7829 Unique. Recompile at most the main files. It implies -c. Combined with
7830 -f, it is equivalent to calling the compiler directly. Note that using
7831 -u with a project file and no main has a special meaning.
7832 @end table
7834 @c --Comment:
7835 @c (See :ref:`Project_Files_and_Main_Subprograms`.)
7837 @geindex -U (gnatmake)
7840 @table @asis
7842 @item @code{-U}
7844 When used without a project file or with one or several mains on the command
7845 line, is equivalent to -u. When used with a project file and no main
7846 on the command line, all sources of all project files are checked and compiled
7847 if not up to date, and libraries are rebuilt, if necessary.
7848 @end table
7850 @geindex -v (gnatmake)
7853 @table @asis
7855 @item @code{-v}
7857 Verbose. Display the reason for all recompilations @emph{gnatmake}
7858 decides are necessary, with the highest verbosity level.
7859 @end table
7861 @geindex -vl (gnatmake)
7864 @table @asis
7866 @item @code{-vl}
7868 Verbosity level Low. Display fewer lines than in verbosity Medium.
7869 @end table
7871 @geindex -vm (gnatmake)
7874 @table @asis
7876 @item @code{-vm}
7878 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7879 @end table
7881 @geindex -vm (gnatmake)
7884 @table @asis
7886 @item @code{-vh}
7888 Verbosity level High. Equivalent to -v.
7890 @item @code{-vP@emph{x}}
7892 Indicate the verbosity of the parsing of GNAT project files.
7893 See @ref{de,,Switches Related to Project Files}.
7894 @end table
7896 @geindex -x (gnatmake)
7899 @table @asis
7901 @item @code{-x}
7903 Indicate that sources that are not part of any Project File may be compiled.
7904 Normally, when using Project Files, only sources that are part of a Project
7905 File may be compile. When this switch is used, a source outside of all Project
7906 Files may be compiled. The ALI file and the object file will be put in the
7907 object directory of the main Project. The compilation switches used will only
7908 be those specified on the command line. Even when
7909 @emph{-x} is used, mains specified on the
7910 command line need to be sources of a project file.
7912 @item @code{-X@emph{name}=@emph{value}}
7914 Indicate that external variable @cite{name} has the value @cite{value}.
7915 The Project Manager will use this value for occurrences of
7916 @cite{external(name)} when parsing the project file.
7917 @ref{de,,Switches Related to Project Files}.
7918 @end table
7920 @geindex -z (gnatmake)
7923 @table @asis
7925 @item @code{-z}
7927 No main subprogram. Bind and link the program even if the unit name
7928 given on the command line is a package name. The resulting executable
7929 will execute the elaboration routines of the package and its closure,
7930 then the finalization routines.
7931 @end table
7933 @subsubheading GCC switches
7936 Any uppercase or multi-character switch that is not a @emph{gnatmake} switch
7937 is passed to @emph{gcc} (e.g., @emph{-O}, @emph{-gnato,} etc.)
7939 @subsubheading Source and library search path switches
7942 @geindex -aI (gnatmake)
7945 @table @asis
7947 @item @code{-aI@emph{dir}}
7949 When looking for source files also look in directory @cite{dir}.
7950 The order in which source files search is undertaken is
7951 described in @ref{89,,Search Paths and the Run-Time Library (RTL)}.
7952 @end table
7954 @geindex -aL (gnatmake)
7957 @table @asis
7959 @item @code{-aL@emph{dir}}
7961 Consider @cite{dir} as being an externally provided Ada library.
7962 Instructs @emph{gnatmake} to skip compilation units whose @code{.ALI}
7963 files have been located in directory @cite{dir}. This allows you to have
7964 missing bodies for the units in @cite{dir} and to ignore out of date bodies
7965 for the same units. You still need to specify
7966 the location of the specs for these units by using the switches
7967 @code{-aI@emph{dir}}  or @code{-I@emph{dir}}.
7968 Note: this switch is provided for compatibility with previous versions
7969 of @emph{gnatmake}. The easier method of causing standard libraries
7970 to be excluded from consideration is to write-protect the corresponding
7971 ALI files.
7972 @end table
7974 @geindex -aO (gnatmake)
7977 @table @asis
7979 @item @code{-aO@emph{dir}}
7981 When searching for library and object files, look in directory
7982 @cite{dir}. The order in which library files are searched is described in
7983 @ref{8c,,Search Paths for gnatbind}.
7984 @end table
7986 @geindex Search paths
7987 @geindex for gnatmake
7989 @geindex -A (gnatmake)
7992 @table @asis
7994 @item @code{-A@emph{dir}}
7996 Equivalent to @code{-aL@emph{dir}} @code{-aI@emph{dir}}.
7998 @geindex -I (gnatmake)
8000 @item @code{-I@emph{dir}}
8002 Equivalent to @code{-aO@emph{dir} -aI@emph{dir}}.
8003 @end table
8005 @geindex -I- (gnatmake)
8007 @geindex Source files
8008 @geindex suppressing search
8011 @table @asis
8013 @item @code{-I-}
8015 Do not look for source files in the directory containing the source
8016 file named in the command line.
8017 Do not look for ALI or object files in the directory
8018 where @emph{gnatmake} was invoked.
8019 @end table
8021 @geindex -L (gnatmake)
8023 @geindex Linker libraries
8026 @table @asis
8028 @item @code{-L@emph{dir}}
8030 Add directory @cite{dir} to the list of directories in which the linker
8031 will search for libraries. This is equivalent to
8032 @code{-largs} @code{-L@emph{dir}}.
8033 Furthermore, under Windows, the sources pointed to by the libraries path
8034 set in the registry are not searched for.
8035 @end table
8037 @geindex -nostdinc (gnatmake)
8040 @table @asis
8042 @item @code{-nostdinc}
8044 Do not look for source files in the system default directory.
8045 @end table
8047 @geindex -nostdlib (gnatmake)
8050 @table @asis
8052 @item @code{-nostdlib}
8054 Do not look for library files in the system default directory.
8055 @end table
8057 @geindex --RTS (gnatmake)
8060 @table @asis
8062 @item @code{--RTS=@emph{rts-path}}
8064 Specifies the default location of the runtime library. GNAT looks for the
8065 runtime
8066 in the following directories, and stops as soon as a valid runtime is found
8067 (@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
8068 @code{ada_object_path} present):
8071 @itemize *
8073 @item 
8074 @emph{<current directory>/$rts_path}
8076 @item 
8077 @emph{<default-search-dir>/$rts_path}
8079 @item 
8080 @emph{<default-search-dir>/rts-$rts_path}
8082 @item 
8083 The selected path is handled like a normal RTS path.
8084 @end itemize
8085 @end table
8087 @node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
8088 @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}
8089 @subsection Mode Switches for @emph{gnatmake}
8092 The mode switches (referred to as @cite{mode_switches}) allow the
8093 inclusion of switches that are to be passed to the compiler itself, the
8094 binder or the linker. The effect of a mode switch is to cause all
8095 subsequent switches up to the end of the switch list, or up to the next
8096 mode switch, to be interpreted as switches to be passed on to the
8097 designated component of GNAT.
8099 @geindex -cargs (gnatmake)
8102 @table @asis
8104 @item @code{-cargs @emph{switches}}
8106 Compiler switches. Here @cite{switches} is a list of switches
8107 that are valid switches for @emph{gcc}. They will be passed on to
8108 all compile steps performed by @emph{gnatmake}.
8109 @end table
8111 @geindex -bargs (gnatmake)
8114 @table @asis
8116 @item @code{-bargs @emph{switches}}
8118 Binder switches. Here @cite{switches} is a list of switches
8119 that are valid switches for @cite{gnatbind}. They will be passed on to
8120 all bind steps performed by @emph{gnatmake}.
8121 @end table
8123 @geindex -largs (gnatmake)
8126 @table @asis
8128 @item @code{-largs @emph{switches}}
8130 Linker switches. Here @cite{switches} is a list of switches
8131 that are valid switches for @emph{gnatlink}. They will be passed on to
8132 all link steps performed by @emph{gnatmake}.
8133 @end table
8135 @geindex -margs (gnatmake)
8138 @table @asis
8140 @item @code{-margs @emph{switches}}
8142 Make switches. The switches are directly interpreted by @emph{gnatmake},
8143 regardless of any previous occurrence of @emph{-cargs}, @emph{-bargs}
8144 or @emph{-largs}.
8145 @end table
8147 @node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
8148 @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}
8149 @subsection Notes on the Command Line
8152 This section contains some additional useful notes on the operation
8153 of the @emph{gnatmake} command.
8155 @geindex Recompilation (by gnatmake)
8158 @itemize *
8160 @item 
8161 If @emph{gnatmake} finds no ALI files, it recompiles the main program
8162 and all other units required by the main program.
8163 This means that @emph{gnatmake}
8164 can be used for the initial compile, as well as during subsequent steps of
8165 the development cycle.
8167 @item 
8168 If you enter @code{gnatmake foo.adb}, where @code{foo}
8169 is a subunit or body of a generic unit, @emph{gnatmake} recompiles
8170 @code{foo.adb} (because it finds no ALI) and stops, issuing a
8171 warning.
8173 @item 
8174 In @emph{gnatmake} the switch @emph{-I}
8175 is used to specify both source and
8176 library file paths. Use @emph{-aI}
8177 instead if you just want to specify
8178 source paths only and @emph{-aO}
8179 if you want to specify library paths
8180 only.
8182 @item 
8183 @emph{gnatmake} will ignore any files whose ALI file is write-protected.
8184 This may conveniently be used to exclude standard libraries from
8185 consideration and in particular it means that the use of the
8186 @emph{-f} switch will not recompile these files
8187 unless @emph{-a} is also specified.
8189 @item 
8190 @emph{gnatmake} has been designed to make the use of Ada libraries
8191 particularly convenient. Assume you have an Ada library organized
8192 as follows: @emph{obj-dir} contains the objects and ALI files for
8193 of your Ada compilation units,
8194 whereas @emph{include-dir} contains the
8195 specs of these units, but no bodies. Then to compile a unit
8196 stored in @cite{main.adb}, which uses this Ada library you would just type:
8198 @example
8199 $ gnatmake -aI`include-dir`  -aL`obj-dir`  main
8200 @end example
8202 @item 
8203 Using @emph{gnatmake} along with the @emph{-m (minimal recompilation)}
8204 switch provides a mechanism for avoiding unnecessary recompilations. Using
8205 this switch,
8206 you can update the comments/format of your
8207 source files without having to recompile everything. Note, however, that
8208 adding or deleting lines in a source files may render its debugging
8209 info obsolete. If the file in question is a spec, the impact is rather
8210 limited, as that debugging info will only be useful during the
8211 elaboration phase of your program. For bodies the impact can be more
8212 significant. In all events, your debugger will warn you if a source file
8213 is more recent than the corresponding object, and alert you to the fact
8214 that the debugging information may be out of date.
8215 @end itemize
8217 @node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8218 @anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{e3}@anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{e4}
8219 @subsection How @emph{gnatmake} Works
8222 Generally @emph{gnatmake} automatically performs all necessary
8223 recompilations and you don't need to worry about how it works. However,
8224 it may be useful to have some basic understanding of the @emph{gnatmake}
8225 approach and in particular to understand how it uses the results of
8226 previous compilations without incorrectly depending on them.
8228 First a definition: an object file is considered @emph{up to date} if the
8229 corresponding ALI file exists and if all the source files listed in the
8230 dependency section of this ALI file have time stamps matching those in
8231 the ALI file. This means that neither the source file itself nor any
8232 files that it depends on have been modified, and hence there is no need
8233 to recompile this file.
8235 @emph{gnatmake} works by first checking if the specified main unit is up
8236 to date. If so, no compilations are required for the main unit. If not,
8237 @emph{gnatmake} compiles the main program to build a new ALI file that
8238 reflects the latest sources. Then the ALI file of the main unit is
8239 examined to find all the source files on which the main program depends,
8240 and @emph{gnatmake} recursively applies the above procedure on all these
8241 files.
8243 This process ensures that @emph{gnatmake} only trusts the dependencies
8244 in an existing ALI file if they are known to be correct. Otherwise it
8245 always recompiles to determine a new, guaranteed accurate set of
8246 dependencies. As a result the program is compiled 'upside down' from what may
8247 be more familiar as the required order of compilation in some other Ada
8248 systems. In particular, clients are compiled before the units on which
8249 they depend. The ability of GNAT to compile in any order is critical in
8250 allowing an order of compilation to be chosen that guarantees that
8251 @emph{gnatmake} will recompute a correct set of new dependencies if
8252 necessary.
8254 When invoking @emph{gnatmake} with several @cite{file_names}, if a unit is
8255 imported by several of the executables, it will be recompiled at most once.
8257 Note: when using non-standard naming conventions
8258 (@ref{35,,Using Other File Names}), changing through a configuration pragmas
8259 file the version of a source and invoking @emph{gnatmake} to recompile may
8260 have no effect, if the previous version of the source is still accessible
8261 by @emph{gnatmake}. It may be necessary to use the switch
8264 @node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8265 @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}
8266 @subsection Examples of @emph{gnatmake} Usage
8270 @table @asis
8272 @item @emph{gnatmake hello.adb}
8274 Compile all files necessary to bind and link the main program
8275 @code{hello.adb} (containing unit @cite{Hello}) and bind and link the
8276 resulting object files to generate an executable file @code{hello}.
8278 @item @emph{gnatmake main1 main2 main3}
8280 Compile all files necessary to bind and link the main programs
8281 @code{main1.adb} (containing unit @cite{Main1}), @code{main2.adb}
8282 (containing unit @cite{Main2}) and @code{main3.adb}
8283 (containing unit @cite{Main3}) and bind and link the resulting object files
8284 to generate three executable files @code{main1},
8285 @code{main2}  and @code{main3}.
8287 @item @emph{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8289 Compile all files necessary to bind and link the main program unit
8290 @cite{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8291 be done with optimization level 2 and the order of elaboration will be
8292 listed by the binder. @emph{gnatmake} will operate in quiet mode, not
8293 displaying commands it is executing.
8294 @end table
8296 @node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8297 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{1c}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{e7}
8298 @section Compiling with @emph{gcc}
8301 This section discusses how to compile Ada programs using the @emph{gcc}
8302 command. It also describes the set of switches
8303 that can be used to control the behavior of the compiler.
8305 @menu
8306 * Compiling Programs:: 
8307 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
8308 * Order of Compilation Issues:: 
8309 * Examples:: 
8311 @end menu
8313 @node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8314 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{e8}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{e9}
8315 @subsection Compiling Programs
8318 The first step in creating an executable program is to compile the units
8319 of the program using the @emph{gcc} command. You must compile the
8320 following files:
8323 @itemize *
8325 @item 
8326 the body file (@code{.adb}) for a library level subprogram or generic
8327 subprogram
8329 @item 
8330 the spec file (@code{.ads}) for a library level package or generic
8331 package that has no body
8333 @item 
8334 the body file (@code{.adb}) for a library level package
8335 or generic package that has a body
8336 @end itemize
8338 You need @emph{not} compile the following files
8341 @itemize *
8343 @item 
8344 the spec of a library unit which has a body
8346 @item 
8347 subunits
8348 @end itemize
8350 because they are compiled as part of compiling related units. GNAT
8351 package specs
8352 when the corresponding body is compiled, and subunits when the parent is
8353 compiled.
8355 @geindex cannot generate code
8357 If you attempt to compile any of these files, you will get one of the
8358 following error messages (where @cite{fff} is the name of the file you
8359 compiled):
8361 @quotation
8363 @example
8364 cannot generate code for file `fff` (package spec)
8365 to check package spec, use -gnatc
8367 cannot generate code for file `fff` (missing subunits)
8368 to check parent unit, use -gnatc
8370 cannot generate code for file `fff` (subprogram spec)
8371 to check subprogram spec, use -gnatc
8373 cannot generate code for file `fff` (subunit)
8374 to check subunit, use -gnatc
8375 @end example
8376 @end quotation
8378 As indicated by the above error messages, if you want to submit
8379 one of these files to the compiler to check for correct semantics
8380 without generating code, then use the @emph{-gnatc} switch.
8382 The basic command for compiling a file containing an Ada unit is:
8384 @example
8385 $ gcc -c [switches] <file name>
8386 @end example
8388 where @cite{file name} is the name of the Ada file (usually
8389 having an extension @code{.ads} for a spec or @code{.adb} for a body).
8390 You specify the
8391 @code{-c} switch to tell @emph{gcc} to compile, but not link, the file.
8392 The result of a successful compilation is an object file, which has the
8393 same name as the source file but an extension of @code{.o} and an Ada
8394 Library Information (ALI) file, which also has the same name as the
8395 source file, but with @code{.ali} as the extension. GNAT creates these
8396 two output files in the current directory, but you may specify a source
8397 file in any directory using an absolute or relative path specification
8398 containing the directory information.
8400 @geindex gnat1
8402 @emph{gcc} is actually a driver program that looks at the extensions of
8403 the file arguments and loads the appropriate compiler. For example, the
8404 GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8405 These programs are in directories known to the driver program (in some
8406 configurations via environment variables you set), but need not be in
8407 your path. The @emph{gcc} driver also calls the assembler and any other
8408 utilities needed to complete the generation of the required object
8409 files.
8411 It is possible to supply several file names on the same @emph{gcc}
8412 command. This causes @emph{gcc} to call the appropriate compiler for
8413 each file. For example, the following command lists two separate
8414 files to be compiled:
8416 @example
8417 $ gcc -c x.adb y.adb
8418 @end example
8420 calls @cite{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8421 @code{y.adb}.
8422 The compiler generates two object files @code{x.o} and @code{y.o}
8423 and the two ALI files @code{x.ali} and @code{y.ali}.
8425 Any switches apply to all the files listed, see @ref{ea,,Compiler Switches} for a
8426 list of available @emph{gcc} switches.
8428 @node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8429 @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}
8430 @subsection Search Paths and the Run-Time Library (RTL)
8433 With the GNAT source-based library system, the compiler must be able to
8434 find source files for units that are needed by the unit being compiled.
8435 Search paths are used to guide this process.
8437 The compiler compiles one source file whose name must be given
8438 explicitly on the command line. In other words, no searching is done
8439 for this file. To find all other source files that are needed (the most
8440 common being the specs of units), the compiler examines the following
8441 directories, in the following order:
8444 @itemize *
8446 @item 
8447 The directory containing the source file of the main unit being compiled
8448 (the file name on the command line).
8450 @item 
8451 Each directory named by an @emph{-I} switch given on the @emph{gcc}
8452 command line, in the order given.
8454 @geindex ADA_PRJ_INCLUDE_FILE
8456 @item 
8457 Each of the directories listed in the text file whose name is given
8458 by the 
8459 @geindex ADA_PRJ_INCLUDE_FILE
8460 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8461 @code{ADA_PRJ_INCLUDE_FILE} environment variable.
8462 @geindex ADA_PRJ_INCLUDE_FILE
8463 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8464 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8465 driver when project files are used. It should not normally be set
8466 by other means.
8468 @geindex ADA_INCLUDE_PATH
8470 @item 
8471 Each of the directories listed in the value of the
8472 @geindex ADA_INCLUDE_PATH
8473 @geindex environment variable; ADA_INCLUDE_PATH
8474 @code{ADA_INCLUDE_PATH} environment variable.
8475 Construct this value
8476 exactly as the 
8477 @geindex PATH
8478 @geindex environment variable; PATH
8479 @code{PATH} environment variable: a list of directory
8480 names separated by colons (semicolons when working with the NT version).
8482 @item 
8483 The content of the @code{ada_source_path} file which is part of the GNAT
8484 installation tree and is used to store standard libraries such as the
8485 GNAT Run Time Library (RTL) source files.
8486 @ref{87,,Installing a library}
8487 @end itemize
8489 Specifying the switch @emph{-I-}
8490 inhibits the use of the directory
8491 containing the source file named in the command line. You can still
8492 have this directory on your search path, but in this case it must be
8493 explicitly requested with a @emph{-I} switch.
8495 Specifying the switch @emph{-nostdinc}
8496 inhibits the search of the default location for the GNAT Run Time
8497 Library (RTL) source files.
8499 The compiler outputs its object files and ALI files in the current
8500 working directory.
8501 Caution: The object file can be redirected with the @emph{-o} switch;
8502 however, @emph{gcc} and @cite{gnat1} have not been coordinated on this
8503 so the @code{ALI} file will not go to the right place. Therefore, you should
8504 avoid using the @emph{-o} switch.
8506 @geindex System.IO
8508 The packages @cite{Ada}, @cite{System}, and @cite{Interfaces} and their
8509 children make up the GNAT RTL, together with the simple @cite{System.IO}
8510 package used in the @cite{"Hello World"} example. The sources for these units
8511 are needed by the compiler and are kept together in one directory. Not
8512 all of the bodies are needed, but all of the sources are kept together
8513 anyway. In a normal installation, you need not specify these directory
8514 names when compiling or binding. Either the environment variables or
8515 the built-in defaults cause these files to be found.
8517 In addition to the language-defined hierarchies (@cite{System}, @cite{Ada} and
8518 @cite{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8519 consisting of child units of @cite{GNAT}. This is a collection of generally
8520 useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8521 for further details.
8523 Besides simplifying access to the RTL, a major use of search paths is
8524 in compiling sources from multiple directories. This can make
8525 development environments much more flexible.
8527 @node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8528 @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}
8529 @subsection Order of Compilation Issues
8532 If, in our earlier example, there was a spec for the @cite{hello}
8533 procedure, it would be contained in the file @code{hello.ads}; yet this
8534 file would not have to be explicitly compiled. This is the result of the
8535 model we chose to implement library management. Some of the consequences
8536 of this model are as follows:
8539 @itemize *
8541 @item 
8542 There is no point in compiling specs (except for package
8543 specs with no bodies) because these are compiled as needed by clients. If
8544 you attempt a useless compilation, you will receive an error message.
8545 It is also useless to compile subunits because they are compiled as needed
8546 by the parent.
8548 @item 
8549 There are no order of compilation requirements: performing a
8550 compilation never obsoletes anything. The only way you can obsolete
8551 something and require recompilations is to modify one of the
8552 source files on which it depends.
8554 @item 
8555 There is no library as such, apart from the ALI files
8556 (@ref{42,,The Ada Library Information Files}, for information on the format
8557 of these files). For now we find it convenient to create separate ALI files,
8558 but eventually the information therein may be incorporated into the object
8559 file directly.
8561 @item 
8562 When you compile a unit, the source files for the specs of all units
8563 that it @emph{with}s, all its subunits, and the bodies of any generics it
8564 instantiates must be available (reachable by the search-paths mechanism
8565 described above), or you will receive a fatal error message.
8566 @end itemize
8568 @node Examples,,Order of Compilation Issues,Compiling with gcc
8569 @anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{ee}@anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{ef}
8570 @subsection Examples
8573 The following are some typical Ada compilation command line examples:
8575 @example
8576 $ gcc -c xyz.adb
8577 @end example
8579 Compile body in file @code{xyz.adb} with all default options.
8581 @example
8582 $ gcc -c -O2 -gnata xyz-def.adb
8583 @end example
8585 Compile the child unit package in file @code{xyz-def.adb} with extensive
8586 optimizations, and pragma @cite{Assert}/@cite{Debug} statements
8587 enabled.
8589 @example
8590 $ gcc -c -gnatc abc-def.adb
8591 @end example
8593 Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8594 mode.
8596 @node Compiler Switches,Binding with gnatbind,Compiling with gcc,Building Executable Programs with GNAT
8597 @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}
8598 @section Compiler Switches
8601 The @emph{gcc} command accepts switches that control the
8602 compilation process. These switches are fully described in this section:
8603 first an alphabetical listing of all switches with a brief description,
8604 and then functionally grouped sets of switches with more detailed
8605 information.
8607 More switches exist for GCC than those documented here, especially
8608 for specific targets. However, their use is not recommended as
8609 they may change code generation in ways that are incompatible with
8610 the Ada run-time library, or can cause inconsistencies between
8611 compilation units.
8613 @menu
8614 * Alphabetical List of All Switches:: 
8615 * Output and Error Message Control:: 
8616 * Warning Message Control:: 
8617 * Debugging and Assertion Control:: 
8618 * Validity Checking:: 
8619 * Style Checking:: 
8620 * Run-Time Checks:: 
8621 * Using gcc for Syntax Checking:: 
8622 * Using gcc for Semantic Checking:: 
8623 * Compiling Different Versions of Ada:: 
8624 * Character Set Control:: 
8625 * File Naming Control:: 
8626 * Subprogram Inlining Control:: 
8627 * Auxiliary Output Control:: 
8628 * Debugging Control:: 
8629 * Exception Handling Control:: 
8630 * Units to Sources Mapping Files:: 
8631 * Code Generation Control:: 
8633 @end menu
8635 @node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8636 @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}
8637 @subsection Alphabetical List of All Switches
8640 @geindex -b (gcc)
8643 @table @asis
8645 @item @code{-b @emph{target}}
8647 Compile your program to run on @cite{target}, which is the name of a
8648 system configuration. You must have a GNAT cross-compiler built if
8649 @cite{target} is not the same as your host system.
8650 @end table
8652 @geindex -B (gcc)
8655 @table @asis
8657 @item @code{-B@emph{dir}}
8659 Load compiler executables (for example, @cite{gnat1}, the Ada compiler)
8660 from @cite{dir} instead of the default location. Only use this switch
8661 when multiple versions of the GNAT compiler are available.
8662 See the "Options for Directory Search" section in the
8663 @cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8664 You would normally use the @emph{-b} or @emph{-V} switch instead.
8665 @end table
8667 @geindex -c (gcc)
8670 @table @asis
8672 @item @code{-c}
8674 Compile. Always use this switch when compiling Ada programs.
8676 Note: for some other languages when using @emph{gcc}, notably in
8677 the case of C and C++, it is possible to use
8678 use @emph{gcc} without a @emph{-c} switch to
8679 compile and link in one step. In the case of GNAT, you
8680 cannot use this approach, because the binder must be run
8681 and @emph{gcc} cannot be used to run the GNAT binder.
8682 @end table
8684 @geindex -fcallgraph-info (gcc)
8687 @table @asis
8689 @item @code{-fcallgraph-info[=su,da]}
8691 Makes the compiler output callgraph information for the program, on a
8692 per-file basis. The information is generated in the VCG format.  It can
8693 be decorated with additional, per-node and/or per-edge information, if a
8694 list of comma-separated markers is additionally specified. When the
8695 @cite{su} marker is specified, the callgraph is decorated with stack usage
8696 information; it is equivalent to @emph{-fstack-usage}. When the @cite{da}
8697 marker is specified, the callgraph is decorated with information about
8698 dynamically allocated objects.
8699 @end table
8701 @geindex -fdump-scos (gcc)
8704 @table @asis
8706 @item @code{-fdump-scos}
8708 Generates SCO (Source Coverage Obligation) information in the ALI file.
8709 This information is used by advanced coverage tools. See unit @code{SCOs}
8710 in the compiler sources for details in files @code{scos.ads} and
8711 @code{scos.adb}.
8712 @end table
8714 @geindex -fdump-xref (gcc)
8717 @table @asis
8719 @item @code{-fdump-xref}
8721 Generates cross reference information in GLI files for C and C++ sources.
8722 The GLI files have the same syntax as the ALI files for Ada, and can be used
8723 for source navigation in IDEs and on the command line using e.g. gnatxref
8724 and the @emph{--ext=gli} switch.
8725 @end table
8727 @geindex -flto (gcc)
8730 @table @asis
8732 @item @code{-flto[=@emph{n}]}
8734 Enables Link Time Optimization. This switch must be used in conjunction
8735 with the traditional @emph{-Ox} switches and instructs the compiler to
8736 defer most optimizations until the link stage. The advantage of this
8737 approach is that the compiler can do a whole-program analysis and choose
8738 the best interprocedural optimization strategy based on a complete view
8739 of the program, instead of a fragmentary view with the usual approach.
8740 This can also speed up the compilation of big programs and reduce the
8741 size of the executable, compared with a traditional per-unit compilation
8742 with inlining across modules enabled by the @emph{-gnatn} switch.
8743 The drawback of this approach is that it may require more memory and that
8744 the debugging information generated by -g with it might be hardly usable.
8745 The switch, as well as the accompanying @emph{-Ox} switches, must be
8746 specified both for the compilation and the link phases.
8747 If the @cite{n} parameter is specified, the optimization and final code
8748 generation at link time are executed using @cite{n} parallel jobs by
8749 means of an installed @emph{make} program.
8750 @end table
8752 @geindex -fno-inline (gcc)
8755 @table @asis
8757 @item @code{-fno-inline}
8759 Suppresses all inlining, unless requested with pragma @cite{Inline_Always}. The
8760 effect is enforced regardless of other optimization or inlining switches.
8761 Note that inlining can also be suppressed on a finer-grained basis with
8762 pragma @cite{No_Inline}.
8763 @end table
8765 @geindex -fno-inline-functions (gcc)
8768 @table @asis
8770 @item @code{-fno-inline-functions}
8772 Suppresses automatic inlining of subprograms, which is enabled
8773 if @emph{-O3} is used.
8774 @end table
8776 @geindex -fno-inline-small-functions (gcc)
8779 @table @asis
8781 @item @code{-fno-inline-small-functions}
8783 Suppresses automatic inlining of small subprograms, which is enabled
8784 if @emph{-O2} is used.
8785 @end table
8787 @geindex -fno-inline-functions-called-once (gcc)
8790 @table @asis
8792 @item @code{-fno-inline-functions-called-once}
8794 Suppresses inlining of subprograms local to the unit and called once
8795 from within it, which is enabled if @emph{-O1} is used.
8796 @end table
8798 @geindex -fno-ivopts (gcc)
8801 @table @asis
8803 @item @code{-fno-ivopts}
8805 Suppresses high-level loop induction variable optimizations, which are
8806 enabled if @emph{-O1} is used. These optimizations are generally
8807 profitable but, for some specific cases of loops with numerous uses
8808 of the iteration variable that follow a common pattern, they may end
8809 up destroying the regularity that could be exploited at a lower level
8810 and thus producing inferior code.
8811 @end table
8813 @geindex -fno-strict-aliasing (gcc)
8816 @table @asis
8818 @item @code{-fno-strict-aliasing}
8820 Causes the compiler to avoid assumptions regarding non-aliasing
8821 of objects of different types. See
8822 @ref{f3,,Optimization and Strict Aliasing} for details.
8823 @end table
8825 @geindex -fno-strict-overflow (gcc)
8828 @table @asis
8830 @item @code{-fno-strict-overflow}
8832 Causes the compiler to avoid assumptions regarding the rules of signed
8833 integer overflow. These rules specify that signed integer overflow will
8834 result in a Constraint_Error exception at run time and are enforced in
8835 default mode by the compiler, so this switch should not be necessary in
8836 normal operating mode. It might be useful in conjunction with @emph{-gnato0}
8837 for very peculiar cases of low-level programming.
8838 @end table
8840 @geindex -fstack-check (gcc)
8843 @table @asis
8845 @item @code{-fstack-check}
8847 Activates stack checking.
8848 See @ref{f4,,Stack Overflow Checking} for details.
8849 @end table
8851 @geindex -fstack-usage (gcc)
8854 @table @asis
8856 @item @code{-fstack-usage}
8858 Makes the compiler output stack usage information for the program, on a
8859 per-subprogram basis. See @ref{f5,,Static Stack Usage Analysis} for details.
8860 @end table
8862 @geindex -g (gcc)
8865 @table @asis
8867 @item @code{-g}
8869 Generate debugging information. This information is stored in the object
8870 file and copied from there to the final executable file by the linker,
8871 where it can be read by the debugger. You must use the
8872 @emph{-g} switch if you plan on using the debugger.
8873 @end table
8875 @geindex -gnat05 (gcc)
8878 @table @asis
8880 @item @code{-gnat05}
8882 Allow full Ada 2005 features.
8883 @end table
8885 @geindex -gnat12 (gcc)
8888 @table @asis
8890 @item @code{-gnat12}
8892 Allow full Ada 2012 features.
8893 @end table
8895 @geindex -gnat83 (gcc)
8897 @geindex -gnat2005 (gcc)
8900 @table @asis
8902 @item @code{-gnat2005}
8904 Allow full Ada 2005 features (same as @emph{-gnat05})
8905 @end table
8907 @geindex -gnat2012 (gcc)
8910 @table @asis
8912 @item @code{-gnat2012}
8914 Allow full Ada 2012 features (same as @emph{-gnat12})
8916 @item @code{-gnat83}
8918 Enforce Ada 83 restrictions.
8919 @end table
8921 @geindex -gnat95 (gcc)
8924 @table @asis
8926 @item @code{-gnat95}
8928 Enforce Ada 95 restrictions.
8930 Note: for compatibility with some Ada 95 compilers which support only
8931 the @cite{overriding} keyword of Ada 2005, the @emph{-gnatd.D} switch can
8932 be used along with @emph{-gnat95} to achieve a similar effect with GNAT.
8934 @emph{-gnatd.D} instructs GNAT to consider @cite{overriding} as a keyword
8935 and handle its associated semantic checks, even in Ada 95 mode.
8936 @end table
8938 @geindex -gnata (gcc)
8941 @table @asis
8943 @item @code{-gnata}
8945 Assertions enabled. @cite{Pragma Assert} and @cite{pragma Debug} to be
8946 activated. Note that these pragmas can also be controlled using the
8947 configuration pragmas @cite{Assertion_Policy} and @cite{Debug_Policy}.
8948 It also activates pragmas @cite{Check}, @cite{Precondition}, and
8949 @cite{Postcondition}. Note that these pragmas can also be controlled
8950 using the configuration pragma @cite{Check_Policy}. In Ada 2012, it
8951 also activates all assertions defined in the RM as aspects: preconditions,
8952 postconditions, type invariants and (sub)type predicates. In all Ada modes,
8953 corresponding pragmas for type invariants and (sub)type predicates are
8954 also activated. The default is that all these assertions are disabled,
8955 and have no effect, other than being checked for syntactic validity, and
8956 in the case of subtype predicates, constructions such as membership tests
8957 still test predicates even if assertions are turned off.
8958 @end table
8960 @geindex -gnatA (gcc)
8963 @table @asis
8965 @item @code{-gnatA}
8967 Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
8968 it will be ignored.
8969 @end table
8971 @geindex -gnatb (gcc)
8974 @table @asis
8976 @item @code{-gnatb}
8978 Generate brief messages to @code{stderr} even if verbose mode set.
8979 @end table
8981 @geindex -gnatB (gcc)
8984 @table @asis
8986 @item @code{-gnatB}
8988 Assume no invalid (bad) values except for 'Valid attribute use
8989 (@ref{f6,,Validity Checking}).
8990 @end table
8992 @geindex -gnatc (gcc)
8995 @table @asis
8997 @item @code{-gnatc}
8999 Check syntax and semantics only (no code generation attempted). When the
9000 compiler is invoked by @emph{gnatmake}, if the switch @emph{-gnatc} is
9001 only given to the compiler (after @emph{-cargs} or in package Compiler of
9002 the project file, @emph{gnatmake} will fail because it will not find the
9003 object file after compilation. If @emph{gnatmake} is called with
9004 @emph{-gnatc} as a builder switch (before @emph{-cargs} or in package
9005 Builder of the project file) then @emph{gnatmake} will not fail because
9006 it will not look for the object files after compilation, and it will not try
9007 to build and link. This switch may not be given if a previous @cite{-gnatR}
9008 switch has been given, since @cite{-gnatR} requires that the code generator
9009 be called to complete determination of representation information.
9010 @end table
9012 @geindex -gnatC (gcc)
9015 @table @asis
9017 @item @code{-gnatC}
9019 Generate CodePeer intermediate format (no code generation attempted).
9020 This switch will generate an intermediate representation suitable for
9021 use by CodePeer (@code{.scil} files). This switch is not compatible with
9022 code generation (it will, among other things, disable some switches such
9023 as -gnatn, and enable others such as -gnata).
9024 @end table
9026 @geindex -gnatd (gcc)
9029 @table @asis
9031 @item @code{-gnatd}
9033 Specify debug options for the compiler. The string of characters after
9034 the @emph{-gnatd} specify the specific debug options. The possible
9035 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
9036 compiler source file @code{debug.adb} for details of the implemented
9037 debug options. Certain debug options are relevant to applications
9038 programmers, and these are documented at appropriate points in this
9039 users guide.
9040 @end table
9042 @geindex -gnatD[nn] (gcc)
9045 @table @asis
9047 @item @code{-gnatD}
9049 Create expanded source files for source level debugging. This switch
9050 also suppress generation of cross-reference information
9051 (see @emph{-gnatx}). Note that this switch is not allowed if a previous
9052 -gnatR switch has been given, since these two switches are not compatible.
9053 @end table
9055 @geindex -gnateA (gcc)
9058 @table @asis
9060 @item @code{-gnateA}
9062 Check that the actual parameters of a subprogram call are not aliases of one
9063 another. To qualify as aliasing, the actuals must denote objects of a composite
9064 type, their memory locations must be identical or overlapping, and at least one
9065 of the corresponding formal parameters must be of mode OUT or IN OUT.
9067 @example
9068 type Rec_Typ is record
9069    Data : Integer := 0;
9070 end record;
9072 function Self (Val : Rec_Typ) return Rec_Typ is
9073 begin
9074    return Val;
9075 end Self;
9077 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
9078 begin
9079    null;
9080 end Detect_Aliasing;
9082 Obj : Rec_Typ;
9084 Detect_Aliasing (Obj, Obj);
9085 Detect_Aliasing (Obj, Self (Obj));
9086 @end example
9088 In the example above, the first call to @cite{Detect_Aliasing} fails with a
9089 @cite{Program_Error} at runtime because the actuals for @cite{Val_1} and
9090 @cite{Val_2} denote the same object. The second call executes without raising
9091 an exception because @cite{Self(Obj)} produces an anonymous object which does
9092 not share the memory location of @cite{Obj}.
9093 @end table
9095 @geindex -gnatec (gcc)
9098 @table @asis
9100 @item @code{-gnatec=@emph{path}}
9102 Specify a configuration pragma file
9103 (the equal sign is optional)
9104 (@ref{79,,The Configuration Pragmas Files}).
9105 @end table
9107 @geindex -gnateC (gcc)
9110 @table @asis
9112 @item @code{-gnateC}
9114 Generate CodePeer messages in a compiler-like format. This switch is only
9115 effective if @emph{-gnatcC} is also specified and requires an installation
9116 of CodePeer.
9117 @end table
9119 @geindex -gnated (gcc)
9122 @table @asis
9124 @item @code{-gnated}
9126 Disable atomic synchronization
9127 @end table
9129 @geindex -gnateD (gcc)
9132 @table @asis
9134 @item @code{-gnateDsymbol[=@emph{value}]}
9136 Defines a symbol, associated with @cite{value}, for preprocessing.
9137 (@ref{18,,Integrated Preprocessing}).
9138 @end table
9140 @geindex -gnateE (gcc)
9143 @table @asis
9145 @item @code{-gnateE}
9147 Generate extra information in exception messages. In particular, display
9148 extra column information and the value and range associated with index and
9149 range check failures, and extra column information for access checks.
9150 In cases where the compiler is able to determine at compile time that
9151 a check will fail, it gives a warning, and the extra information is not
9152 produced at run time.
9153 @end table
9155 @geindex -gnatef (gcc)
9158 @table @asis
9160 @item @code{-gnatef}
9162 Display full source path name in brief error messages.
9163 @end table
9165 @geindex -gnateF (gcc)
9168 @table @asis
9170 @item @code{-gnateF}
9172 Check for overflow on all floating-point operations, including those
9173 for unconstrained predefined types. See description of pragma
9174 @cite{Check_Float_Overflow} in GNAT RM.
9175 @end table
9177 @geindex -gnateg (gcc)
9179 @code{-gnateg}
9180 @code{-gnatceg}
9182 @quotation
9184 The @cite{-gnatc} switch must always be specified before this switch, e.g.
9185 @cite{-gnatceg}. Generate a C header from the Ada input file. See
9186 @ref{ca,,Generating C Headers for Ada Specifications} for more
9187 information.
9188 @end quotation
9190 @geindex -gnateG (gcc)
9193 @table @asis
9195 @item @code{-gnateG}
9197 Save result of preprocessing in a text file.
9198 @end table
9200 @geindex -gnatei (gcc)
9203 @table @asis
9205 @item @code{-gnatei@emph{nnn}}
9207 Set maximum number of instantiations during compilation of a single unit to
9208 @cite{nnn}. This may be useful in increasing the default maximum of 8000 for
9209 the rare case when a single unit legitimately exceeds this limit.
9210 @end table
9212 @geindex -gnateI (gcc)
9215 @table @asis
9217 @item @code{-gnateI@emph{nnn}}
9219 Indicates that the source is a multi-unit source and that the index of the
9220 unit to compile is @cite{nnn}. @cite{nnn} needs to be a positive number and need
9221 to be a valid index in the multi-unit source.
9222 @end table
9224 @geindex -gnatel (gcc)
9227 @table @asis
9229 @item @code{-gnatel}
9231 This switch can be used with the static elaboration model to issue info
9232 messages showing
9233 where implicit @cite{pragma Elaborate} and @cite{pragma Elaborate_All}
9234 are generated. This is useful in diagnosing elaboration circularities
9235 caused by these implicit pragmas when using the static elaboration
9236 model. See See the section in this guide on elaboration checking for
9237 further details. These messages are not generated by default, and are
9238 intended only for temporary use when debugging circularity problems.
9239 @end table
9241 @geindex -gnatel (gcc)
9244 @table @asis
9246 @item @code{-gnateL}
9248 This switch turns off the info messages about implicit elaboration pragmas.
9249 @end table
9251 @geindex -gnatem (gcc)
9254 @table @asis
9256 @item @code{-gnatem=@emph{path}}
9258 Specify a mapping file
9259 (the equal sign is optional)
9260 (@ref{f7,,Units to Sources Mapping Files}).
9261 @end table
9263 @geindex -gnatep (gcc)
9266 @table @asis
9268 @item @code{-gnatep=@emph{file}}
9270 Specify a preprocessing data file
9271 (the equal sign is optional)
9272 (@ref{18,,Integrated Preprocessing}).
9273 @end table
9275 @geindex -gnateP (gcc)
9278 @table @asis
9280 @item @code{-gnateP}
9282 Turn categorization dependency errors into warnings.
9283 Ada requires that units that WITH one another have compatible categories, for
9284 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9285 these errors become warnings (which can be ignored, or suppressed in the usual
9286 manner). This can be useful in some specialized circumstances such as the
9287 temporary use of special test software.
9288 @end table
9290 @geindex -gnateS (gcc)
9293 @table @asis
9295 @item @code{-gnateS}
9297 Synonym of @emph{-fdump-scos}, kept for backwards compatibility.
9298 @end table
9300 @geindex -gnatet=file (gcc)
9303 @table @asis
9305 @item @code{-gnatet=@emph{path}}
9307 Generate target dependent information. The format of the output file is
9308 described in the section about switch @emph{-gnateT}.
9309 @end table
9311 @geindex -gnateT (gcc)
9314 @table @asis
9316 @item @code{-gnateT=@emph{path}}
9318 Read target dependent information, such as endianness or sizes and alignments
9319 of base type. If this switch is passed, the default target dependent
9320 information of the compiler is replaced by the one read from the input file.
9321 This is used by tools other than the compiler, e.g. to do
9322 semantic analysis of programs that will run on some other target than
9323 the machine on which the tool is run.
9325 The following target dependent values should be defined,
9326 where @cite{Nat} denotes a natural integer value, @cite{Pos} denotes a
9327 positive integer value, and fields marked with a question mark are
9328 boolean fields, where a value of 0 is False, and a value of 1 is True:
9330 @example
9331 Bits_BE                    : Nat; -- Bits stored big-endian?
9332 Bits_Per_Unit              : Pos; -- Bits in a storage unit
9333 Bits_Per_Word              : Pos; -- Bits in a word
9334 Bytes_BE                   : Nat; -- Bytes stored big-endian?
9335 Char_Size                  : Pos; -- Standard.Character'Size
9336 Double_Float_Alignment     : Nat; -- Alignment of double float
9337 Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
9338 Double_Size                : Pos; -- Standard.Long_Float'Size
9339 Float_Size                 : Pos; -- Standard.Float'Size
9340 Float_Words_BE             : Nat; -- Float words stored big-endian?
9341 Int_Size                   : Pos; -- Standard.Integer'Size
9342 Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
9343 Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
9344 Long_Size                  : Pos; -- Standard.Long_Integer'Size
9345 Maximum_Alignment          : Pos; -- Maximum permitted alignment
9346 Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
9347 Pointer_Size               : Pos; -- System.Address'Size
9348 Short_Enums                : Nat; -- Short foreign convention enums?
9349 Short_Size                 : Pos; -- Standard.Short_Integer'Size
9350 Strict_Alignment           : Nat; -- Strict alignment?
9351 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9352 Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
9353 Words_BE                   : Nat; -- Words stored big-endian?
9354 @end example
9356 The format of the input file is as follows. First come the values of
9357 the variables defined above, with one line per value:
9359 @example
9360 name  value
9361 @end example
9363 where @cite{name} is the name of the parameter, spelled out in full,
9364 and cased as in the above list, and @cite{value} is an unsigned decimal
9365 integer. Two or more blanks separates the name from the value.
9367 All the variables must be present, in alphabetical order (i.e. the
9368 same order as the list above).
9370 Then there is a blank line to separate the two parts of the file. Then
9371 come the lines showing the floating-point types to be registered, with
9372 one line per registered mode:
9374 @example
9375 name  digs float_rep size alignment
9376 @end example
9378 where @cite{name} is the string name of the type (which can have
9379 single spaces embedded in the name (e.g. long double), @cite{digs} is
9380 the number of digits for the floating-point type, @cite{float_rep} is
9381 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
9382 AAMP), @cite{size} is the size in bits, @cite{alignment} is the
9383 alignment in bits. The name is followed by at least two blanks, fields
9384 are separated by at least one blank, and a LF character immediately
9385 follows the alignment field.
9387 Here is an example of a target parameterization file:
9389 @example
9390 Bits_BE                       0
9391 Bits_Per_Unit                 8
9392 Bits_Per_Word                64
9393 Bytes_BE                      0
9394 Char_Size                     8
9395 Double_Float_Alignment        0
9396 Double_Scalar_Alignment       0
9397 Double_Size                  64
9398 Float_Size                   32
9399 Float_Words_BE                0
9400 Int_Size                     64
9401 Long_Double_Size            128
9402 Long_Long_Size               64
9403 Long_Size                    64
9404 Maximum_Alignment            16
9405 Max_Unaligned_Field          64
9406 Pointer_Size                 64
9407 Short_Size                   16
9408 Strict_Alignment              0
9409 System_Allocator_Alignment   16
9410 Wchar_T_Size                 32
9411 Words_BE                      0
9413 float         15  I  64  64
9414 double        15  I  64  64
9415 long double   18  I  80 128
9416 TF            33  I 128 128
9417 @end example
9418 @end table
9420 @geindex -gnateu (gcc)
9423 @table @asis
9425 @item @code{-gnateu}
9427 Ignore unrecognized validity, warning, and style switches that
9428 appear after this switch is given. This may be useful when
9429 compiling sources developed on a later version of the compiler
9430 with an earlier version. Of course the earlier version must
9431 support this switch.
9432 @end table
9434 @geindex -gnateV (gcc)
9437 @table @asis
9439 @item @code{-gnateV}
9441 Check that all actual parameters of a subprogram call are valid according to
9442 the rules of validity checking (@ref{f6,,Validity Checking}).
9443 @end table
9445 @geindex -gnateY (gcc)
9448 @table @asis
9450 @item @code{-gnateY}
9452 Ignore all STYLE_CHECKS pragmas. Full legality checks
9453 are still carried out, but the pragmas have no effect
9454 on what style checks are active. This allows all style
9455 checking options to be controlled from the command line.
9456 @end table
9458 @geindex -gnatE (gcc)
9461 @table @asis
9463 @item @code{-gnatE}
9465 Full dynamic elaboration checks.
9466 @end table
9468 @geindex -gnatf (gcc)
9471 @table @asis
9473 @item @code{-gnatf}
9475 Full errors. Multiple errors per line, all undefined references, do not
9476 attempt to suppress cascaded errors.
9477 @end table
9479 @geindex -gnatF (gcc)
9482 @table @asis
9484 @item @code{-gnatF}
9486 Externals names are folded to all uppercase.
9487 @end table
9489 @geindex -gnatg (gcc)
9492 @table @asis
9494 @item @code{-gnatg}
9496 Internal GNAT implementation mode. This should not be used for
9497 applications programs, it is intended only for use by the compiler
9498 and its run-time library. For documentation, see the GNAT sources.
9499 Note that @emph{-gnatg} implies
9500 @emph{-gnatw.ge} and
9501 @emph{-gnatyg}
9502 so that all standard warnings and all standard style options are turned on.
9503 All warnings and style messages are treated as errors.
9504 @end table
9506 @geindex -gnatG[nn] (gcc)
9509 @table @asis
9511 @item @code{-gnatG=nn}
9513 List generated expanded code in source form.
9514 @end table
9516 @geindex -gnath (gcc)
9519 @table @asis
9521 @item @code{-gnath}
9523 Output usage information. The output is written to @code{stdout}.
9524 @end table
9526 @geindex -gnati (gcc)
9529 @table @asis
9531 @item @code{-gnati@emph{c}}
9533 Identifier character set (@cite{c} = 1/2/3/4/8/9/p/f/n/w).
9534 For details of the possible selections for @cite{c},
9535 see @ref{48,,Character Set Control}.
9536 @end table
9538 @geindex -gnatI (gcc)
9541 @table @asis
9543 @item @code{-gnatI}
9545 Ignore representation clauses. When this switch is used,
9546 representation clauses are treated as comments. This is useful
9547 when initially porting code where you want to ignore rep clause
9548 problems, and also for compiling foreign code (particularly
9549 for use with ASIS). The representation clauses that are ignored
9550 are: enumeration_representation_clause, record_representation_clause,
9551 and attribute_definition_clause for the following attributes:
9552 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9553 Object_Size, Size, Small, Stream_Size, and Value_Size.
9554 Note that this option should be used only for compiling -- the
9555 code is likely to malfunction at run time.
9557 Note that when @cite{-gnatct} is used to generate trees for input
9558 into @cite{ASIS} tools, these representation clauses are removed
9559 from the tree and ignored. This means that the tool will not see them.
9560 @end table
9562 @geindex -gnatjnn (gcc)
9565 @table @asis
9567 @item @code{-gnatj@emph{nn}}
9569 Reformat error messages to fit on @cite{nn} character lines
9570 @end table
9572 @geindex -gnatk (gcc)
9575 @table @asis
9577 @item @code{-gnatk=@emph{n}}
9579 Limit file names to @cite{n} (1-999) characters (@cite{k} = krunch).
9580 @end table
9582 @geindex -gnatl (gcc)
9585 @table @asis
9587 @item @code{-gnatl}
9589 Output full source listing with embedded error messages.
9590 @end table
9592 @geindex -gnatL (gcc)
9595 @table @asis
9597 @item @code{-gnatL}
9599 Used in conjunction with -gnatG or -gnatD to intersperse original
9600 source lines (as comment lines with line numbers) in the expanded
9601 source output.
9602 @end table
9604 @geindex -gnatm (gcc)
9607 @table @asis
9609 @item @code{-gnatm=@emph{n}}
9611 Limit number of detected error or warning messages to @cite{n}
9612 where @cite{n} is in the range 1..999999. The default setting if
9613 no switch is given is 9999. If the number of warnings reaches this
9614 limit, then a message is output and further warnings are suppressed,
9615 but the compilation is continued. If the number of error messages
9616 reaches this limit, then a message is output and the compilation
9617 is abandoned. The equal sign here is optional. A value of zero
9618 means that no limit applies.
9619 @end table
9621 @geindex -gnatn (gcc)
9624 @table @asis
9626 @item @code{-gnatn[12]}
9628 Activate inlining for subprograms for which pragma @cite{Inline} is
9629 specified. This inlining is performed by the GCC back-end. An optional
9630 digit sets the inlining level: 1 for moderate inlining across modules
9631 or 2 for full inlining across modules. If no inlining level is specified,
9632 the compiler will pick it based on the optimization level.
9633 @end table
9635 @geindex -gnatN (gcc)
9638 @table @asis
9640 @item @code{-gnatN}
9642 Activate front end inlining for subprograms for which
9643 pragma @cite{Inline} is specified. This inlining is performed
9644 by the front end and will be visible in the
9645 @emph{-gnatG} output.
9647 When using a gcc-based back end (in practice this means using any version
9648 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
9649 @emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
9650 Historically front end inlining was more extensive than the gcc back end
9651 inlining, but that is no longer the case.
9652 @end table
9654 @geindex -gnato0 (gcc)
9657 @table @asis
9659 @item @code{-gnato0}
9661 Suppresses overflow checking. This causes the behavior of the compiler to
9662 match the default for older versions where overflow checking was suppressed
9663 by default. This is equivalent to having
9664 @cite{pragma Suppress (Overflow_Mode)} in a configuration pragma file.
9665 @end table
9667 @geindex -gnato?? (gcc)
9670 @table @asis
9672 @item @code{-gnato??}
9674 Set default mode for handling generation of code to avoid intermediate
9675 arithmetic overflow. Here @cite{??} is two digits, a
9676 single digit, or nothing. Each digit is one of the digits @cite{1}
9677 through @cite{3}:
9680 @multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
9681 @item
9683 Digit
9685 @tab
9687 Interpretation
9689 @item
9691 @emph{1}
9693 @tab
9695 All intermediate overflows checked against base type (@cite{STRICT})
9697 @item
9699 @emph{2}
9701 @tab
9703 Minimize intermediate overflows (@cite{MINIMIZED})
9705 @item
9707 @emph{3}
9709 @tab
9711 Eliminate intermediate overflows (@cite{ELIMINATED})
9713 @end multitable
9716 If only one digit appears, then it applies to all
9717 cases; if two digits are given, then the first applies outside
9718 assertions, pre/postconditions, and type invariants, and the second
9719 applies within assertions, pre/postconditions, and type invariants.
9721 If no digits follow the @emph{-gnato}, then it is equivalent to
9722 @emph{-gnato11},
9723 causing all intermediate overflows to be handled in strict
9724 mode.
9726 This switch also causes arithmetic overflow checking to be performed
9727 (as though @cite{pragma Unsuppress (Overflow_Mode)} had been specified).
9729 The default if no option @emph{-gnato} is given is that overflow handling
9730 is in @cite{STRICT} mode (computations done using the base type), and that
9731 overflow checking is enabled.
9733 Note that division by zero is a separate check that is not
9734 controlled by this switch (divide-by-zero checking is on by default).
9736 See also @ref{f8,,Specifying the Desired Mode}.
9737 @end table
9739 @geindex -gnatp (gcc)
9742 @table @asis
9744 @item @code{-gnatp}
9746 Suppress all checks. See @ref{f9,,Run-Time Checks} for details. This switch
9747 has no effect if cancelled by a subsequent @emph{-gnat-p} switch.
9748 @end table
9750 @geindex -gnat-p (gcc)
9753 @table @asis
9755 @item @code{-gnat-p}
9757 Cancel effect of previous @emph{-gnatp} switch.
9758 @end table
9760 @geindex -gnatP (gcc)
9763 @table @asis
9765 @item @code{-gnatP}
9767 Enable polling. This is required on some systems (notably Windows NT) to
9768 obtain asynchronous abort and asynchronous transfer of control capability.
9769 See @cite{Pragma_Polling} in the @cite{GNAT_Reference_Manual} for full
9770 details.
9771 @end table
9773 @geindex -gnatq (gcc)
9776 @table @asis
9778 @item @code{-gnatq}
9780 Don't quit. Try semantics, even if parse errors.
9781 @end table
9783 @geindex -gnatQ (gcc)
9786 @table @asis
9788 @item @code{-gnatQ}
9790 Don't quit. Generate @code{ALI} and tree files even if illegalities.
9791 Note that code generation is still suppressed in the presence of any
9792 errors, so even with @emph{-gnatQ} no object file is generated.
9793 @end table
9795 @geindex -gnatr (gcc)
9798 @table @asis
9800 @item @code{-gnatr}
9802 Treat pragma Restrictions as Restriction_Warnings.
9803 @end table
9805 @geindex -gnatR (gcc)
9808 @table @asis
9810 @item @code{-gnatR[0/1/2/3[s]]}
9812 Output representation information for declared types and objects.
9813 Note that this switch is not allowed if a previous @cite{-gnatD} switch has
9814 been given, since these two switches are not compatible.
9816 @item @code{-gnatRm[s]}
9818 Output convention and parameter passing mechanisms for all subprograms.
9819 @end table
9821 @geindex -gnats (gcc)
9824 @table @asis
9826 @item @code{-gnats}
9828 Syntax check only.
9829 @end table
9831 @geindex -gnatS (gcc)
9834 @table @asis
9836 @item @code{-gnatS}
9838 Print package Standard.
9839 @end table
9841 @geindex -gnatt (gcc)
9844 @table @asis
9846 @item @code{-gnatt}
9848 Generate tree output file.
9849 @end table
9851 @geindex -gnatT (gcc)
9854 @table @asis
9856 @item @code{-gnatT@emph{nnn}}
9858 All compiler tables start at @cite{nnn} times usual starting size.
9859 @end table
9861 @geindex -gnatu (gcc)
9864 @table @asis
9866 @item @code{-gnatu}
9868 List units for this compilation.
9869 @end table
9871 @geindex -gnatU (gcc)
9874 @table @asis
9876 @item @code{-gnatU}
9878 Tag all error messages with the unique string 'error:'
9879 @end table
9881 @geindex -gnatv (gcc)
9884 @table @asis
9886 @item @code{-gnatv}
9888 Verbose mode. Full error output with source lines to @code{stdout}.
9889 @end table
9891 @geindex -gnatV (gcc)
9894 @table @asis
9896 @item @code{-gnatV}
9898 Control level of validity checking (@ref{f6,,Validity Checking}).
9899 @end table
9901 @geindex -gnatw (gcc)
9904 @table @asis
9906 @item @code{-gnatw@emph{xxx}}
9908 Warning mode where
9909 @cite{xxx} is a string of option letters that denotes
9910 the exact warnings that
9911 are enabled or disabled (@ref{fa,,Warning Message Control}).
9912 @end table
9914 @geindex -gnatW (gcc)
9917 @table @asis
9919 @item @code{-gnatW@emph{e}}
9921 Wide character encoding method
9922 (@cite{e}=n/h/u/s/e/8).
9923 @end table
9925 @geindex -gnatx (gcc)
9928 @table @asis
9930 @item @code{-gnatx}
9932 Suppress generation of cross-reference information.
9933 @end table
9935 @geindex -gnatX (gcc)
9938 @table @asis
9940 @item @code{-gnatX}
9942 Enable GNAT implementation extensions and latest Ada version.
9943 @end table
9945 @geindex -gnaty (gcc)
9948 @table @asis
9950 @item @code{-gnaty}
9952 Enable built-in style checks (@ref{fb,,Style Checking}).
9953 @end table
9955 @geindex -gnatz (gcc)
9958 @table @asis
9960 @item @code{-gnatz@emph{m}}
9962 Distribution stub generation and compilation
9963 (@cite{m}=r/c for receiver/caller stubs).
9964 @end table
9966 @geindex -I (gcc)
9969 @table @asis
9971 @item @code{-I@emph{dir}}
9973 @geindex RTL
9975 Direct GNAT to search the @cite{dir} directory for source files needed by
9976 the current compilation
9977 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
9978 @end table
9980 @geindex -I- (gcc)
9983 @table @asis
9985 @item @code{-I-}
9987 @geindex RTL
9989 Except for the source file named in the command line, do not look for source
9990 files in the directory containing the source file named in the command line
9991 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
9992 @end table
9994 @geindex -o (gcc)
9997 @table @asis
9999 @item @code{-o @emph{file}}
10001 This switch is used in @emph{gcc} to redirect the generated object file
10002 and its associated ALI file. Beware of this switch with GNAT, because it may
10003 cause the object file and ALI file to have different names which in turn
10004 may confuse the binder and the linker.
10005 @end table
10007 @geindex -nostdinc (gcc)
10010 @table @asis
10012 @item @code{-nostdinc}
10014 Inhibit the search of the default location for the GNAT Run Time
10015 Library (RTL) source files.
10016 @end table
10018 @geindex -nostdlib (gcc)
10021 @table @asis
10023 @item @code{-nostdlib}
10025 Inhibit the search of the default location for the GNAT Run Time
10026 Library (RTL) ALI files.
10027 @end table
10029 @geindex -O (gcc)
10032 @table @asis
10034 @item @code{-O[@emph{n}]}
10036 @cite{n} controls the optimization level:
10039 @multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
10040 @item
10042 @emph{n}
10044 @tab
10046 Effect
10048 @item
10050 @emph{0}
10052 @tab
10054 No optimization, the default setting if no @emph{-O} appears
10056 @item
10058 @emph{1}
10060 @tab
10062 Normal optimization, the default if you specify @emph{-O} without an
10063 operand. A good compromise between code quality and compilation
10064 time.
10066 @item
10068 @emph{2}
10070 @tab
10072 Extensive optimization, may improve execution time, possibly at
10073 the cost of substantially increased compilation time.
10075 @item
10077 @emph{3}
10079 @tab
10081 Same as @emph{-O2}, and also includes inline expansion for small
10082 subprograms in the same unit.
10084 @item
10086 @emph{s}
10088 @tab
10090 Optimize space usage
10092 @end multitable
10095 See also @ref{fc,,Optimization Levels}.
10096 @end table
10098 @geindex -pass-exit-codes (gcc)
10101 @table @asis
10103 @item @code{-pass-exit-codes}
10105 Catch exit codes from the compiler and use the most meaningful as
10106 exit status.
10107 @end table
10109 @geindex --RTS (gcc)
10112 @table @asis
10114 @item @code{--RTS=@emph{rts-path}}
10116 Specifies the default location of the runtime library. Same meaning as the
10117 equivalent @emph{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
10118 @end table
10120 @geindex -S (gcc)
10123 @table @asis
10125 @item @code{-S}
10127 Used in place of @emph{-c} to
10128 cause the assembler source file to be
10129 generated, using @code{.s} as the extension,
10130 instead of the object file.
10131 This may be useful if you need to examine the generated assembly code.
10132 @end table
10134 @geindex -fverbose-asm (gcc)
10137 @table @asis
10139 @item @code{-fverbose-asm}
10141 Used in conjunction with @emph{-S}
10142 to cause the generated assembly code file to be annotated with variable
10143 names, making it significantly easier to follow.
10144 @end table
10146 @geindex -v (gcc)
10149 @table @asis
10151 @item @code{-v}
10153 Show commands generated by the @emph{gcc} driver. Normally used only for
10154 debugging purposes or if you need to be sure what version of the
10155 compiler you are executing.
10156 @end table
10158 @geindex -V (gcc)
10161 @table @asis
10163 @item @code{-V @emph{ver}}
10165 Execute @cite{ver} version of the compiler. This is the @emph{gcc}
10166 version, not the GNAT version.
10167 @end table
10169 @geindex -w (gcc)
10172 @table @asis
10174 @item @code{-w}
10176 Turn off warnings generated by the back end of the compiler. Use of
10177 this switch also causes the default for front end warnings to be set
10178 to suppress (as though @emph{-gnatws} had appeared at the start of
10179 the options).
10180 @end table
10182 @geindex Combining GNAT switches
10184 You may combine a sequence of GNAT switches into a single switch. For
10185 example, the combined switch
10187 @quotation
10189 @example
10190 -gnatofi3
10191 @end example
10192 @end quotation
10194 is equivalent to specifying the following sequence of switches:
10196 @quotation
10198 @example
10199 -gnato -gnatf -gnati3
10200 @end example
10201 @end quotation
10203 The following restrictions apply to the combination of switches
10204 in this manner:
10207 @itemize *
10209 @item 
10210 The switch @emph{-gnatc} if combined with other switches must come
10211 first in the string.
10213 @item 
10214 The switch @emph{-gnats} if combined with other switches must come
10215 first in the string.
10217 @item 
10218 The switches
10219 @emph{-gnatzc} and @emph{-gnatzr} may not be combined with any other
10220 switches, and only one of them may appear in the command line.
10222 @item 
10223 The switch @emph{-gnat-p} may not be combined with any other switch.
10225 @item 
10226 Once a 'y' appears in the string (that is a use of the @emph{-gnaty}
10227 switch), then all further characters in the switch are interpreted
10228 as style modifiers (see description of @emph{-gnaty}).
10230 @item 
10231 Once a 'd' appears in the string (that is a use of the @emph{-gnatd}
10232 switch), then all further characters in the switch are interpreted
10233 as debug flags (see description of @emph{-gnatd}).
10235 @item 
10236 Once a 'w' appears in the string (that is a use of the @emph{-gnatw}
10237 switch), then all further characters in the switch are interpreted
10238 as warning mode modifiers (see description of @emph{-gnatw}).
10240 @item 
10241 Once a 'V' appears in the string (that is a use of the @emph{-gnatV}
10242 switch), then all further characters in the switch are interpreted
10243 as validity checking options (@ref{f6,,Validity Checking}).
10245 @item 
10246 Option 'em', 'ec', 'ep', 'l=' and 'R' must be the last options in
10247 a combined list of options.
10248 @end itemize
10250 @node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10251 @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}
10252 @subsection Output and Error Message Control
10255 @geindex stderr
10257 The standard default format for error messages is called 'brief format'.
10258 Brief format messages are written to @code{stderr} (the standard error
10259 file) and have the following form:
10261 @example
10262 e.adb:3:04: Incorrect spelling of keyword "function"
10263 e.adb:4:20: ";" should be "is"
10264 @end example
10266 The first integer after the file name is the line number in the file,
10267 and the second integer is the column number within the line.
10268 @cite{GPS} can parse the error messages
10269 and point to the referenced character.
10270 The following switches provide control over the error message
10271 format:
10273 @geindex -gnatv (gcc)
10276 @table @asis
10278 @item @code{-gnatv}
10280 The @cite{v} stands for verbose.
10281 The effect of this setting is to write long-format error
10282 messages to @code{stdout} (the standard output file.
10283 The same program compiled with the
10284 @emph{-gnatv} switch would generate:
10286 @example
10287 3. funcion X (Q : Integer)
10288    |
10289 >>> Incorrect spelling of keyword "function"
10290 4. return Integer;
10291                  |
10292 >>> ";" should be "is"
10293 @end example
10295 The vertical bar indicates the location of the error, and the @code{>>>}
10296 prefix can be used to search for error messages. When this switch is
10297 used the only source lines output are those with errors.
10298 @end table
10300 @geindex -gnatl (gcc)
10303 @table @asis
10305 @item @code{-gnatl}
10307 The @cite{l} stands for list.
10308 This switch causes a full listing of
10309 the file to be generated. In the case where a body is
10310 compiled, the corresponding spec is also listed, along
10311 with any subunits. Typical output from compiling a package
10312 body @code{p.adb} might look like:
10314 @example
10315 Compiling: p.adb
10317      1. package body p is
10318      2.    procedure a;
10319      3.    procedure a is separate;
10320      4. begin
10321      5.    null
10322                |
10323         >>> missing ";"
10325      6. end;
10327 Compiling: p.ads
10329      1. package p is
10330      2.    pragma Elaborate_Body
10331                                 |
10332         >>> missing ";"
10334      3. end p;
10336 Compiling: p-a.adb
10338      1. separate p
10339                 |
10340         >>> missing "("
10342      2. procedure a is
10343      3. begin
10344      4.    null
10345                |
10346         >>> missing ";"
10348      5. end;
10349 @end example
10351 When you specify the @emph{-gnatv} or @emph{-gnatl} switches and
10352 standard output is redirected, a brief summary is written to
10353 @code{stderr} (standard error) giving the number of error messages and
10354 warning messages generated.
10355 @end table
10357 @geindex -gnatl=fname (gcc)
10360 @table @asis
10362 @item @code{-gnatl=@emph{fname}}
10364 This has the same effect as @emph{-gnatl} except that the output is
10365 written to a file instead of to standard output. If the given name
10366 @code{fname} does not start with a period, then it is the full name
10367 of the file to be written. If @code{fname} is an extension, it is
10368 appended to the name of the file being compiled. For example, if
10369 file @code{xyz.adb} is compiled with @emph{-gnatl=.lst},
10370 then the output is written to file xyz.adb.lst.
10371 @end table
10373 @geindex -gnatU (gcc)
10376 @table @asis
10378 @item @code{-gnatU}
10380 This switch forces all error messages to be preceded by the unique
10381 string 'error:'. This means that error messages take a few more
10382 characters in space, but allows easy searching for and identification
10383 of error messages.
10384 @end table
10386 @geindex -gnatb (gcc)
10389 @table @asis
10391 @item @code{-gnatb}
10393 The @cite{b} stands for brief.
10394 This switch causes GNAT to generate the
10395 brief format error messages to @code{stderr} (the standard error
10396 file) as well as the verbose
10397 format message or full listing (which as usual is written to
10398 @code{stdout} (the standard output file).
10399 @end table
10401 @geindex -gnatm (gcc)
10404 @table @asis
10406 @item @code{-gnatm=@emph{n}}
10408 The @cite{m} stands for maximum.
10409 @cite{n} is a decimal integer in the
10410 range of 1 to 999999 and limits the number of error or warning
10411 messages to be generated. For example, using
10412 @emph{-gnatm2} might yield
10414 @example
10415 e.adb:3:04: Incorrect spelling of keyword "function"
10416 e.adb:5:35: missing ".."
10417 fatal error: maximum number of errors detected
10418 compilation abandoned
10419 @end example
10421 The default setting if
10422 no switch is given is 9999. If the number of warnings reaches this
10423 limit, then a message is output and further warnings are suppressed,
10424 but the compilation is continued. If the number of error messages
10425 reaches this limit, then a message is output and the compilation
10426 is abandoned. A value of zero means that no limit applies.
10428 Note that the equal sign is optional, so the switches
10429 @emph{-gnatm2} and @emph{-gnatm=2} are equivalent.
10430 @end table
10432 @geindex -gnatf (gcc)
10435 @table @asis
10437 @item @code{-gnatf}
10439 @geindex Error messages
10440 @geindex suppressing
10442 The @cite{f} stands for full.
10443 Normally, the compiler suppresses error messages that are likely to be
10444 redundant. This switch causes all error
10445 messages to be generated. In particular, in the case of
10446 references to undefined variables. If a given variable is referenced
10447 several times, the normal format of messages is
10449 @example
10450 e.adb:7:07: "V" is undefined (more references follow)
10451 @end example
10453 where the parenthetical comment warns that there are additional
10454 references to the variable @cite{V}. Compiling the same program with the
10455 @emph{-gnatf} switch yields
10457 @example
10458 e.adb:7:07: "V" is undefined
10459 e.adb:8:07: "V" is undefined
10460 e.adb:8:12: "V" is undefined
10461 e.adb:8:16: "V" is undefined
10462 e.adb:9:07: "V" is undefined
10463 e.adb:9:12: "V" is undefined
10464 @end example
10466 The @emph{-gnatf} switch also generates additional information for
10467 some error messages.  Some examples are:
10470 @itemize *
10472 @item 
10473 Details on possibly non-portable unchecked conversion
10475 @item 
10476 List possible interpretations for ambiguous calls
10478 @item 
10479 Additional details on incorrect parameters
10480 @end itemize
10481 @end table
10483 @geindex -gnatjnn (gcc)
10486 @table @asis
10488 @item @code{-gnatjnn}
10490 In normal operation mode (or if @emph{-gnatj0} is used), then error messages
10491 with continuation lines are treated as though the continuation lines were
10492 separate messages (and so a warning with two continuation lines counts as
10493 three warnings, and is listed as three separate messages).
10495 If the @emph{-gnatjnn} switch is used with a positive value for nn, then
10496 messages are output in a different manner. A message and all its continuation
10497 lines are treated as a unit, and count as only one warning or message in the
10498 statistics totals. Furthermore, the message is reformatted so that no line
10499 is longer than nn characters.
10500 @end table
10502 @geindex -gnatq (gcc)
10505 @table @asis
10507 @item @code{-gnatq}
10509 The @cite{q} stands for quit (really 'don't quit').
10510 In normal operation mode, the compiler first parses the program and
10511 determines if there are any syntax errors. If there are, appropriate
10512 error messages are generated and compilation is immediately terminated.
10513 This switch tells
10514 GNAT to continue with semantic analysis even if syntax errors have been
10515 found. This may enable the detection of more errors in a single run. On
10516 the other hand, the semantic analyzer is more likely to encounter some
10517 internal fatal error when given a syntactically invalid tree.
10518 @end table
10520 @geindex -gnatQ (gcc)
10523 @table @asis
10525 @item @code{-gnatQ}
10527 In normal operation mode, the @code{ALI} file is not generated if any
10528 illegalities are detected in the program. The use of @emph{-gnatQ} forces
10529 generation of the @code{ALI} file. This file is marked as being in
10530 error, so it cannot be used for binding purposes, but it does contain
10531 reasonably complete cross-reference information, and thus may be useful
10532 for use by tools (e.g., semantic browsing tools or integrated development
10533 environments) that are driven from the @code{ALI} file. This switch
10534 implies @emph{-gnatq}, since the semantic phase must be run to get a
10535 meaningful ALI file.
10537 In addition, if @emph{-gnatt} is also specified, then the tree file is
10538 generated even if there are illegalities. It may be useful in this case
10539 to also specify @emph{-gnatq} to ensure that full semantic processing
10540 occurs. The resulting tree file can be processed by ASIS, for the purpose
10541 of providing partial information about illegal units, but if the error
10542 causes the tree to be badly malformed, then ASIS may crash during the
10543 analysis.
10545 When @emph{-gnatQ} is used and the generated @code{ALI} file is marked as
10546 being in error, @emph{gnatmake} will attempt to recompile the source when it
10547 finds such an @code{ALI} file, including with switch @emph{-gnatc}.
10549 Note that @emph{-gnatQ} has no effect if @emph{-gnats} is specified,
10550 since ALI files are never generated if @emph{-gnats} is set.
10551 @end table
10553 @node Warning Message Control,Debugging and Assertion Control,Output and Error Message Control,Compiler Switches
10554 @anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{fa}@anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{ff}
10555 @subsection Warning Message Control
10558 @geindex Warning messages
10560 In addition to error messages, which correspond to illegalities as defined
10561 in the Ada Reference Manual, the compiler detects two kinds of warning
10562 situations.
10564 First, the compiler considers some constructs suspicious and generates a
10565 warning message to alert you to a possible error. Second, if the
10566 compiler detects a situation that is sure to raise an exception at
10567 run time, it generates a warning message. The following shows an example
10568 of warning messages:
10570 @example
10571 e.adb:4:24: warning: creation of object may raise Storage_Error
10572 e.adb:10:17: warning: static value out of range
10573 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10574 @end example
10576 GNAT considers a large number of situations as appropriate
10577 for the generation of warning messages. As always, warnings are not
10578 definite indications of errors. For example, if you do an out-of-range
10579 assignment with the deliberate intention of raising a
10580 @cite{Constraint_Error} exception, then the warning that may be
10581 issued does not indicate an error. Some of the situations for which GNAT
10582 issues warnings (at least some of the time) are given in the following
10583 list. This list is not complete, and new warnings are often added to
10584 subsequent versions of GNAT. The list is intended to give a general idea
10585 of the kinds of warnings that are generated.
10588 @itemize *
10590 @item 
10591 Possible infinitely recursive calls
10593 @item 
10594 Out-of-range values being assigned
10596 @item 
10597 Possible order of elaboration problems
10599 @item 
10600 Size not a multiple of alignment for a record type
10602 @item 
10603 Assertions (pragma Assert) that are sure to fail
10605 @item 
10606 Unreachable code
10608 @item 
10609 Address clauses with possibly unaligned values, or where an attempt is
10610 made to overlay a smaller variable with a larger one.
10612 @item 
10613 Fixed-point type declarations with a null range
10615 @item 
10616 Direct_IO or Sequential_IO instantiated with a type that has access values
10618 @item 
10619 Variables that are never assigned a value
10621 @item 
10622 Variables that are referenced before being initialized
10624 @item 
10625 Task entries with no corresponding @cite{accept} statement
10627 @item 
10628 Duplicate accepts for the same task entry in a @cite{select}
10630 @item 
10631 Objects that take too much storage
10633 @item 
10634 Unchecked conversion between types of differing sizes
10636 @item 
10637 Missing @cite{return} statement along some execution path in a function
10639 @item 
10640 Incorrect (unrecognized) pragmas
10642 @item 
10643 Incorrect external names
10645 @item 
10646 Allocation from empty storage pool
10648 @item 
10649 Potentially blocking operation in protected type
10651 @item 
10652 Suspicious parenthesization of expressions
10654 @item 
10655 Mismatching bounds in an aggregate
10657 @item 
10658 Attempt to return local value by reference
10660 @item 
10661 Premature instantiation of a generic body
10663 @item 
10664 Attempt to pack aliased components
10666 @item 
10667 Out of bounds array subscripts
10669 @item 
10670 Wrong length on string assignment
10672 @item 
10673 Violations of style rules if style checking is enabled
10675 @item 
10676 Unused @emph{with} clauses
10678 @item 
10679 @cite{Bit_Order} usage that does not have any effect
10681 @item 
10682 @cite{Standard.Duration} used to resolve universal fixed expression
10684 @item 
10685 Dereference of possibly null value
10687 @item 
10688 Declaration that is likely to cause storage error
10690 @item 
10691 Internal GNAT unit @emph{with}ed by application unit
10693 @item 
10694 Values known to be out of range at compile time
10696 @item 
10697 Unreferenced or unmodified variables. Note that a special
10698 exemption applies to variables which contain any of the substrings
10699 @cite{DISCARD@comma{} DUMMY@comma{} IGNORE@comma{} JUNK@comma{} UNUSED}, in any casing. Such variables
10700 are considered likely to be intentionally used in a situation where
10701 otherwise a warning would be given, so warnings of this kind are
10702 always suppressed for such variables.
10704 @item 
10705 Address overlays that could clobber memory
10707 @item 
10708 Unexpected initialization when address clause present
10710 @item 
10711 Bad alignment for address clause
10713 @item 
10714 Useless type conversions
10716 @item 
10717 Redundant assignment statements and other redundant constructs
10719 @item 
10720 Useless exception handlers
10722 @item 
10723 Accidental hiding of name by child unit
10725 @item 
10726 Access before elaboration detected at compile time
10728 @item 
10729 A range in a @cite{for} loop that is known to be null or might be null
10730 @end itemize
10732 The following section lists compiler switches that are available
10733 to control the handling of warning messages. It is also possible
10734 to exercise much finer control over what warnings are issued and
10735 suppressed using the GNAT pragma Warnings (see the description
10736 of the pragma in the @cite{GNAT_Reference_manual}).
10738 @geindex -gnatwa (gcc)
10741 @table @asis
10743 @item @code{-gnatwa}
10745 @emph{Activate most optional warnings.}
10747 This switch activates most optional warning messages.  See the remaining list
10748 in this section for details on optional warning messages that can be
10749 individually controlled.  The warnings that are not turned on by this
10750 switch are:
10753 @itemize *
10755 @item 
10756 @code{-gnatwd} (implicit dereferencing)
10758 @item 
10759 @code{-gnatw.d} (tag warnings with -gnatw switch)
10761 @item 
10762 @code{-gnatwh} (hiding)
10764 @item 
10765 @code{-gnatw.h} (holes in record layouts)
10767 @item 
10768 @code{-gnatw.k} (redefinition of names in standard)
10770 @item 
10771 @code{-gnatwl} (elaboration warnings)
10773 @item 
10774 @code{-gnatw.l} (inherited aspects)
10776 @item 
10777 @code{-gnatw.n} (atomic synchronization)
10779 @item 
10780 @code{-gnatwo} (address clause overlay)
10782 @item 
10783 @code{-gnatw.o} (values set by out parameters ignored)
10785 @item 
10786 @code{-gnatw.s} (overridden size clause)
10788 @item 
10789 @code{-gnatwt} (tracking of deleted conditional code)
10791 @item 
10792 @code{-gnatw.u} (unordered enumeration)
10794 @item 
10795 @code{-gnatw.w} (use of Warnings Off)
10797 @item 
10798 @code{-gnatw.y} (reasons for package needing body)
10799 @end itemize
10801 All other optional warnings are turned on.
10802 @end table
10804 @geindex -gnatwA (gcc)
10807 @table @asis
10809 @item @code{-gnatwA}
10811 @emph{Suppress all optional errors.}
10813 This switch suppresses all optional warning messages, see remaining list
10814 in this section for details on optional warning messages that can be
10815 individually controlled. Note that unlike switch @emph{-gnatws}, the
10816 use of switch @emph{-gnatwA} does not suppress warnings that are
10817 normally given unconditionally and cannot be individually controlled
10818 (for example, the warning about a missing exit path in a function).
10819 Also, again unlike switch @emph{-gnatws}, warnings suppressed by
10820 the use of switch @emph{-gnatwA} can be individually turned back
10821 on. For example the use of switch @emph{-gnatwA} followed by
10822 switch @emph{-gnatwd} will suppress all optional warnings except
10823 the warnings for implicit dereferencing.
10824 @end table
10826 @geindex -gnatw.a (gcc)
10829 @table @asis
10831 @item @code{-gnatw.a}
10833 @emph{Activate warnings on failing assertions.}
10835 @geindex Assert failures
10837 This switch activates warnings for assertions where the compiler can tell at
10838 compile time that the assertion will fail. Note that this warning is given
10839 even if assertions are disabled. The default is that such warnings are
10840 generated.
10841 @end table
10843 @geindex -gnatw.A (gcc)
10846 @table @asis
10848 @item @code{-gnatw.A}
10850 @emph{Suppress warnings on failing assertions.}
10852 @geindex Assert failures
10854 This switch suppresses warnings for assertions where the compiler can tell at
10855 compile time that the assertion will fail.
10856 @end table
10858 @geindex -gnatwb (gcc)
10861 @table @asis
10863 @item @code{-gnatwb}
10865 @emph{Activate warnings on bad fixed values.}
10867 @geindex Bad fixed values
10869 @geindex Fixed-point Small value
10871 @geindex Small value
10873 This switch activates warnings for static fixed-point expressions whose
10874 value is not an exact multiple of Small. Such values are implementation
10875 dependent, since an implementation is free to choose either of the multiples
10876 that surround the value. GNAT always chooses the closer one, but this is not
10877 required behavior, and it is better to specify a value that is an exact
10878 multiple, ensuring predictable execution. The default is that such warnings
10879 are not generated.
10880 @end table
10882 @geindex -gnatwB (gcc)
10885 @table @asis
10887 @item @code{-gnatwB}
10889 @emph{Suppress warnings on bad fixed values.}
10891 This switch suppresses warnings for static fixed-point expressions whose
10892 value is not an exact multiple of Small.
10893 @end table
10895 @geindex -gnatw.b (gcc)
10898 @table @asis
10900 @item @code{-gnatw.b}
10902 @emph{Activate warnings on biased representation.}
10904 @geindex Biased representation
10906 This switch activates warnings when a size clause, value size clause, component
10907 clause, or component size clause forces the use of biased representation for an
10908 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
10909 to represent 10/11). The default is that such warnings are generated.
10910 @end table
10912 @geindex -gnatwB (gcc)
10915 @table @asis
10917 @item @code{-gnatw.B}
10919 @emph{Suppress warnings on biased representation.}
10921 This switch suppresses warnings for representation clauses that force the use
10922 of biased representation.
10923 @end table
10925 @geindex -gnatwc (gcc)
10928 @table @asis
10930 @item @code{-gnatwc}
10932 @emph{Activate warnings on conditionals.}
10934 @geindex Conditionals
10935 @geindex constant
10937 This switch activates warnings for conditional expressions used in
10938 tests that are known to be True or False at compile time. The default
10939 is that such warnings are not generated.
10940 Note that this warning does
10941 not get issued for the use of boolean variables or constants whose
10942 values are known at compile time, since this is a standard technique
10943 for conditional compilation in Ada, and this would generate too many
10944 false positive warnings.
10946 This warning option also activates a special test for comparisons using
10947 the operators '>=' and' <='.
10948 If the compiler can tell that only the equality condition is possible,
10949 then it will warn that the '>' or '<' part of the test
10950 is useless and that the operator could be replaced by '='.
10951 An example would be comparing a @cite{Natural} variable <= 0.
10953 This warning option also generates warnings if
10954 one or both tests is optimized away in a membership test for integer
10955 values if the result can be determined at compile time. Range tests on
10956 enumeration types are not included, since it is common for such tests
10957 to include an end point.
10959 This warning can also be turned on using @emph{-gnatwa}.
10960 @end table
10962 @geindex -gnatwC (gcc)
10965 @table @asis
10967 @item @code{-gnatwC}
10969 @emph{Suppress warnings on conditionals.}
10971 This switch suppresses warnings for conditional expressions used in
10972 tests that are known to be True or False at compile time.
10973 @end table
10975 @geindex -gnatw.c (gcc)
10978 @table @asis
10980 @item @code{-gnatw.c}
10982 @emph{Activate warnings on missing component clauses.}
10984 @geindex Component clause
10985 @geindex missing
10987 This switch activates warnings for record components where a record
10988 representation clause is present and has component clauses for the
10989 majority, but not all, of the components. A warning is given for each
10990 component for which no component clause is present.
10991 @end table
10993 @geindex -gnatwC (gcc)
10996 @table @asis
10998 @item @code{-gnatw.C}
11000 @emph{Suppress warnings on missing component clauses.}
11002 This switch suppresses warnings for record components that are
11003 missing a component clause in the situation described above.
11004 @end table
11006 @geindex -gnatwd (gcc)
11009 @table @asis
11011 @item @code{-gnatwd}
11013 @emph{Activate warnings on implicit dereferencing.}
11015 If this switch is set, then the use of a prefix of an access type
11016 in an indexed component, slice, or selected component without an
11017 explicit @cite{.all} will generate a warning. With this warning
11018 enabled, access checks occur only at points where an explicit
11019 @cite{.all} appears in the source code (assuming no warnings are
11020 generated as a result of this switch). The default is that such
11021 warnings are not generated.
11022 @end table
11024 @geindex -gnatwD (gcc)
11027 @table @asis
11029 @item @code{-gnatwD}
11031 @emph{Suppress warnings on implicit dereferencing.}
11033 @geindex Implicit dereferencing
11035 @geindex Dereferencing
11036 @geindex implicit
11038 This switch suppresses warnings for implicit dereferences in
11039 indexed components, slices, and selected components.
11040 @end table
11042 @geindex -gnatw.d (gcc)
11045 @table @asis
11047 @item @code{-gnatw.d}
11049 @emph{Activate tagging of warning and info messages.}
11051 If this switch is set, then warning messages are tagged, with one of the
11052 following strings:
11054 @quotation
11057 @itemize -
11059 @item 
11060 @emph{[-gnatw?]}
11061 Used to tag warnings controlled by the switch @emph{-gnatwx} where x
11062 is a letter a-z.
11064 @item 
11065 @emph{[-gnatw.?]}
11066 Used to tag warnings controlled by the switch @emph{-gnatw.x} where x
11067 is a letter a-z.
11069 @item 
11070 @emph{[-gnatel]}
11071 Used to tag elaboration information (info) messages generated when the
11072 static model of elaboration is used and the @emph{-gnatel} switch is set.
11074 @item 
11075 @emph{[restriction warning]}
11076 Used to tag warning messages for restriction violations, activated by use
11077 of the pragma @emph{Restriction_Warnings}.
11079 @item 
11080 @emph{[warning-as-error]}
11081 Used to tag warning messages that have been converted to error messages by
11082 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
11083 the string "error: " rather than "warning: ".
11085 @item 
11086 @emph{[enabled by default]}
11087 Used to tag all other warnings that are always given by default, unless
11088 warnings are completely suppressed using pragma @emph{Warnings(Off)} or
11089 the switch @emph{-gnatws}.
11090 @end itemize
11091 @end quotation
11092 @end table
11094 @geindex -gnatw.d (gcc)
11097 @table @asis
11099 @item @code{-gnatw.D}
11101 @emph{Deactivate tagging of warning and info messages messages.}
11103 If this switch is set, then warning messages return to the default
11104 mode in which warnings and info messages are not tagged as described above for
11105 @cite{-gnatw.d}.
11106 @end table
11108 @geindex -gnatwe (gcc)
11110 @geindex Warnings
11111 @geindex treat as error
11114 @table @asis
11116 @item @code{-gnatwe}
11118 @emph{Treat warnings and style checks as errors.}
11120 This switch causes warning messages and style check messages to be
11121 treated as errors.
11122 The warning string still appears, but the warning messages are counted
11123 as errors, and prevent the generation of an object file. Note that this
11124 is the only -gnatw switch that affects the handling of style check messages.
11125 Note also that this switch has no effect on info (information) messages, which
11126 are not treated as errors if this switch is present.
11127 @end table
11129 @geindex -gnatw.e (gcc)
11132 @table @asis
11134 @item @code{-gnatw.e}
11136 @emph{Activate every optional warning.}
11138 @geindex Warnings
11139 @geindex activate every optional warning
11141 This switch activates all optional warnings, including those which
11142 are not activated by @cite{-gnatwa}. The use of this switch is not
11143 recommended for normal use. If you turn this switch on, it is almost
11144 certain that you will get large numbers of useless warnings. The
11145 warnings that are excluded from @cite{-gnatwa} are typically highly
11146 specialized warnings that are suitable for use only in code that has
11147 been specifically designed according to specialized coding rules.
11148 @end table
11150 @geindex -gnatwf (gcc)
11153 @table @asis
11155 @item @code{-gnatwf}
11157 @emph{Activate warnings on unreferenced formals.}
11159 @geindex Formals
11160 @geindex unreferenced
11162 This switch causes a warning to be generated if a formal parameter
11163 is not referenced in the body of the subprogram. This warning can
11164 also be turned on using @emph{-gnatwu}. The
11165 default is that these warnings are not generated.
11166 @end table
11168 @geindex -gnatwF (gcc)
11171 @table @asis
11173 @item @code{-gnatwF}
11175 @emph{Suppress warnings on unreferenced formals.}
11177 This switch suppresses warnings for unreferenced formal
11178 parameters. Note that the
11179 combination @emph{-gnatwu} followed by @emph{-gnatwF} has the
11180 effect of warning on unreferenced entities other than subprogram
11181 formals.
11182 @end table
11184 @geindex -gnatwg (gcc)
11187 @table @asis
11189 @item @code{-gnatwg}
11191 @emph{Activate warnings on unrecognized pragmas.}
11193 @geindex Pragmas
11194 @geindex unrecognized
11196 This switch causes a warning to be generated if an unrecognized
11197 pragma is encountered. Apart from issuing this warning, the
11198 pragma is ignored and has no effect. The default
11199 is that such warnings are issued (satisfying the Ada Reference
11200 Manual requirement that such warnings appear).
11201 @end table
11203 @geindex -gnatwG (gcc)
11206 @table @asis
11208 @item @code{-gnatwG}
11210 @emph{Suppress warnings on unrecognized pragmas.}
11212 This switch suppresses warnings for unrecognized pragmas.
11213 @end table
11215 @geindex -gnatw.g (gcc)
11218 @table @asis
11220 @item @code{-gnatw.g}
11222 @emph{Warnings used for GNAT sources.}
11224 This switch sets the warning categories that are used by the standard
11225 GNAT style. Currently this is equivalent to
11226 @emph{-gnatwAao.sI.C.V.X}
11227 but more warnings may be added in the future without advanced notice.
11228 @end table
11230 @geindex -gnatwh (gcc)
11233 @table @asis
11235 @item @code{-gnatwh}
11237 @emph{Activate warnings on hiding.}
11239 @geindex Hiding of Declarations
11241 This switch activates warnings on hiding declarations that are considered
11242 potentially confusing. Not all cases of hiding cause warnings; for example an
11243 overriding declaration hides an implicit declaration, which is just normal
11244 code. The default is that warnings on hiding are not generated.
11245 @end table
11247 @geindex -gnatwH (gcc)
11250 @table @asis
11252 @item @code{-gnatwH}
11254 @emph{Suppress warnings on hiding.}
11256 This switch suppresses warnings on hiding declarations.
11257 @end table
11259 @geindex -gnatw.h (gcc)
11262 @table @asis
11264 @item @code{-gnatw.h}
11266 @emph{Activate warnings on holes/gaps in records.}
11268 @geindex Record Representation (gaps)
11270 This switch activates warnings on component clauses in record
11271 representation clauses that leave holes (gaps) in the record layout.
11272 If this warning option is active, then record representation clauses
11273 should specify a contiguous layout, adding unused fill fields if needed.
11274 @end table
11276 @geindex -gnatw.H (gcc)
11279 @table @asis
11281 @item @code{-gnatw.H}
11283 @emph{Suppress warnings on holes/gaps in records.}
11285 This switch suppresses warnings on component clauses in record
11286 representation clauses that leave holes (haps) in the record layout.
11287 @end table
11289 @geindex -gnatwi (gcc)
11292 @table @asis
11294 @item @code{-gnatwi}
11296 @emph{Activate warnings on implementation units.}
11298 This switch activates warnings for a @emph{with} of an internal GNAT
11299 implementation unit, defined as any unit from the @cite{Ada},
11300 @cite{Interfaces}, @cite{GNAT},
11301 or @cite{System}
11302 hierarchies that is not
11303 documented in either the Ada Reference Manual or the GNAT
11304 Programmer's Reference Manual. Such units are intended only
11305 for internal implementation purposes and should not be @emph{with}ed
11306 by user programs. The default is that such warnings are generated
11307 @end table
11309 @geindex -gnatwI (gcc)
11312 @table @asis
11314 @item @code{-gnatwI}
11316 @emph{Disable warnings on implementation units.}
11318 This switch disables warnings for a @emph{with} of an internal GNAT
11319 implementation unit.
11320 @end table
11322 @geindex -gnatw.i (gcc)
11325 @table @asis
11327 @item @code{-gnatw.i}
11329 @emph{Activate warnings on overlapping actuals.}
11331 This switch enables a warning on statically detectable overlapping actuals in
11332 a subprogram call, when one of the actuals is an in-out parameter, and the
11333 types of the actuals are not by-copy types. This warning is off by default.
11334 @end table
11336 @geindex -gnatw.I (gcc)
11339 @table @asis
11341 @item @code{-gnatw.I}
11343 @emph{Disable warnings on overlapping actuals.}
11345 This switch disables warnings on overlapping actuals in a call..
11346 @end table
11348 @geindex -gnatwj (gcc)
11351 @table @asis
11353 @item @code{-gnatwj}
11355 @emph{Activate warnings on obsolescent features (Annex J).}
11357 @geindex Features
11358 @geindex obsolescent
11360 @geindex Obsolescent features
11362 If this warning option is activated, then warnings are generated for
11363 calls to subprograms marked with @cite{pragma Obsolescent} and
11364 for use of features in Annex J of the Ada Reference Manual. In the
11365 case of Annex J, not all features are flagged. In particular use
11366 of the renamed packages (like @cite{Text_IO}) and use of package
11367 @cite{ASCII} are not flagged, since these are very common and
11368 would generate many annoying positive warnings. The default is that
11369 such warnings are not generated.
11371 In addition to the above cases, warnings are also generated for
11372 GNAT features that have been provided in past versions but which
11373 have been superseded (typically by features in the new Ada standard).
11374 For example, @cite{pragma Ravenscar} will be flagged since its
11375 function is replaced by @cite{pragma Profile(Ravenscar)}, and
11376 @cite{pragma Interface_Name} will be flagged since its function
11377 is replaced by @cite{pragma Import}.
11379 Note that this warning option functions differently from the
11380 restriction @cite{No_Obsolescent_Features} in two respects.
11381 First, the restriction applies only to annex J features.
11382 Second, the restriction does flag uses of package @cite{ASCII}.
11383 @end table
11385 @geindex -gnatwJ (gcc)
11388 @table @asis
11390 @item @code{-gnatwJ}
11392 @emph{Suppress warnings on obsolescent features (Annex J).}
11394 This switch disables warnings on use of obsolescent features.
11395 @end table
11397 @geindex -gnatwk (gcc)
11400 @table @asis
11402 @item @code{-gnatwk}
11404 @emph{Activate warnings on variables that could be constants.}
11406 This switch activates warnings for variables that are initialized but
11407 never modified, and then could be declared constants. The default is that
11408 such warnings are not given.
11409 @end table
11411 @geindex -gnatwK (gcc)
11414 @table @asis
11416 @item @code{-gnatwK}
11418 @emph{Suppress warnings on variables that could be constants.}
11420 This switch disables warnings on variables that could be declared constants.
11421 @end table
11423 @geindex -gnatw.k (gcc)
11426 @table @asis
11428 @item @code{-gnatw.k}
11430 @emph{Activate warnings on redefinition of names in standard.}
11432 This switch activates warnings for declarations that declare a name that
11433 is defined in package Standard. Such declarations can be confusing,
11434 especially since the names in package Standard continue to be directly
11435 visible, meaning that use visibiliy on such redeclared names does not
11436 work as expected. Names of discriminants and components in records are
11437 not included in this check.
11438 @end table
11440 @geindex -gnatwK (gcc)
11443 @table @asis
11445 @item @code{-gnatw.K}
11447 @emph{Suppress warnings on redefinition of names in standard.}
11449 This switch activates warnings for declarations that declare a name that
11450 is defined in package Standard.
11451 @end table
11453 @geindex -gnatwl (gcc)
11456 @table @asis
11458 @item @code{-gnatwl}
11460 @emph{Activate warnings for elaboration pragmas.}
11462 @geindex Elaboration
11463 @geindex warnings
11465 This switch activates warnings for possible elaboration problems,
11466 including suspicious use
11467 of @cite{Elaborate} pragmas, when using the static elaboration model, and
11468 possible situations that may raise @cite{Program_Error} when using the
11469 dynamic elaboration model.
11470 See the section in this guide on elaboration checking for further details.
11471 The default is that such warnings
11472 are not generated.
11473 @end table
11475 @geindex -gnatwL (gcc)
11478 @table @asis
11480 @item @code{-gnatwL}
11482 @emph{Suppress warnings for elaboration pragmas.}
11484 This switch suppresses warnings for possible elaboration problems.
11485 @end table
11487 @geindex -gnatw.l (gcc)
11490 @table @asis
11492 @item @code{-gnatw.l}
11494 @emph{List inherited aspects.}
11496 This switch causes the compiler to list inherited invariants,
11497 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
11498 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
11499 @end table
11501 @geindex -gnatw.L (gcc)
11504 @table @asis
11506 @item @code{-gnatw.L}
11508 @emph{Suppress listing of inherited aspects.}
11510 This switch suppresses listing of inherited aspects.
11511 @end table
11513 @geindex -gnatwm (gcc)
11516 @table @asis
11518 @item @code{-gnatwm}
11520 @emph{Activate warnings on modified but unreferenced variables.}
11522 This switch activates warnings for variables that are assigned (using
11523 an initialization value or with one or more assignment statements) but
11524 whose value is never read. The warning is suppressed for volatile
11525 variables and also for variables that are renamings of other variables
11526 or for which an address clause is given.
11527 The default is that these warnings are not given.
11528 @end table
11530 @geindex -gnatwM (gcc)
11533 @table @asis
11535 @item @code{-gnatwM}
11537 @emph{Disable warnings on modified but unreferenced variables.}
11539 This switch disables warnings for variables that are assigned or
11540 initialized, but never read.
11541 @end table
11543 @geindex -gnatw.m (gcc)
11546 @table @asis
11548 @item @code{-gnatw.m}
11550 @emph{Activate warnings on suspicious modulus values.}
11552 This switch activates warnings for modulus values that seem suspicious.
11553 The cases caught are where the size is the same as the modulus (e.g.
11554 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11555 with no size clause. The guess in both cases is that 2**x was intended
11556 rather than x. In addition expressions of the form 2*x for small x
11557 generate a warning (the almost certainly accurate guess being that
11558 2**x was intended). The default is that these warnings are given.
11559 @end table
11561 @geindex -gnatw.M (gcc)
11564 @table @asis
11566 @item @code{-gnatw.M}
11568 @emph{Disable warnings on suspicious modulus values.}
11570 This switch disables warnings for suspicious modulus values.
11571 @end table
11573 @geindex -gnatwn (gcc)
11576 @table @asis
11578 @item @code{-gnatwn}
11580 @emph{Set normal warnings mode.}
11582 This switch sets normal warning mode, in which enabled warnings are
11583 issued and treated as warnings rather than errors. This is the default
11584 mode. the switch @emph{-gnatwn} can be used to cancel the effect of
11585 an explicit @emph{-gnatws} or
11586 @emph{-gnatwe}. It also cancels the effect of the
11587 implicit @emph{-gnatwe} that is activated by the
11588 use of @emph{-gnatg}.
11589 @end table
11591 @geindex -gnatw.n (gcc)
11593 @geindex Atomic Synchronization
11594 @geindex warnings
11597 @table @asis
11599 @item @code{-gnatw.n}
11601 @emph{Activate warnings on atomic synchronization.}
11603 This switch actives warnings when an access to an atomic variable
11604 requires the generation of atomic synchronization code. These
11605 warnings are off by default.
11606 @end table
11608 @geindex -gnatw.N (gcc)
11611 @table @asis
11613 @item @code{-gnatw.N}
11615 @emph{Suppress warnings on atomic synchronization.}
11617 @geindex Atomic Synchronization
11618 @geindex warnings
11620 This switch suppresses warnings when an access to an atomic variable
11621 requires the generation of atomic synchronization code.
11622 @end table
11624 @geindex -gnatwo (gcc)
11626 @geindex Address Clauses
11627 @geindex warnings
11630 @table @asis
11632 @item @code{-gnatwo}
11634 @emph{Activate warnings on address clause overlays.}
11636 This switch activates warnings for possibly unintended initialization
11637 effects of defining address clauses that cause one variable to overlap
11638 another. The default is that such warnings are generated.
11639 @end table
11641 @geindex -gnatwO (gcc)
11644 @table @asis
11646 @item @code{-gnatwO}
11648 @emph{Suppress warnings on address clause overlays.}
11650 This switch suppresses warnings on possibly unintended initialization
11651 effects of defining address clauses that cause one variable to overlap
11652 another.
11653 @end table
11655 @geindex -gnatw.o (gcc)
11658 @table @asis
11660 @item @code{-gnatw.o}
11662 @emph{Activate warnings on modified but unreferenced out parameters.}
11664 This switch activates warnings for variables that are modified by using
11665 them as actuals for a call to a procedure with an out mode formal, where
11666 the resulting assigned value is never read. It is applicable in the case
11667 where there is more than one out mode formal. If there is only one out
11668 mode formal, the warning is issued by default (controlled by -gnatwu).
11669 The warning is suppressed for volatile
11670 variables and also for variables that are renamings of other variables
11671 or for which an address clause is given.
11672 The default is that these warnings are not given.
11673 @end table
11675 @geindex -gnatw.O (gcc)
11678 @table @asis
11680 @item @code{-gnatw.O}
11682 @emph{Disable warnings on modified but unreferenced out parameters.}
11684 This switch suppresses warnings for variables that are modified by using
11685 them as actuals for a call to a procedure with an out mode formal, where
11686 the resulting assigned value is never read.
11687 @end table
11689 @geindex -gnatwp (gcc)
11691 @geindex Inlining
11692 @geindex warnings
11695 @table @asis
11697 @item @code{-gnatwp}
11699 @emph{Activate warnings on ineffective pragma Inlines.}
11701 This switch activates warnings for failure of front end inlining
11702 (activated by @emph{-gnatN}) to inline a particular call. There are
11703 many reasons for not being able to inline a call, including most
11704 commonly that the call is too complex to inline. The default is
11705 that such warnings are not given.
11706 Warnings on ineffective inlining by the gcc back-end can be activated
11707 separately, using the gcc switch -Winline.
11708 @end table
11710 @geindex -gnatwP (gcc)
11713 @table @asis
11715 @item @code{-gnatwP}
11717 @emph{Suppress warnings on ineffective pragma Inlines.}
11719 This switch suppresses warnings on ineffective pragma Inlines. If the
11720 inlining mechanism cannot inline a call, it will simply ignore the
11721 request silently.
11722 @end table
11724 @geindex -gnatw.p (gcc)
11726 @geindex Parameter order
11727 @geindex warnings
11730 @table @asis
11732 @item @code{-gnatw.p}
11734 @emph{Activate warnings on parameter ordering.}
11736 This switch activates warnings for cases of suspicious parameter
11737 ordering when the list of arguments are all simple identifiers that
11738 match the names of the formals, but are in a different order. The
11739 warning is suppressed if any use of named parameter notation is used,
11740 so this is the appropriate way to suppress a false positive (and
11741 serves to emphasize that the "misordering" is deliberate). The
11742 default is that such warnings are not given.
11743 @end table
11745 @geindex -gnatw.P (gcc)
11748 @table @asis
11750 @item @code{-gnatw.P}
11752 @emph{Suppress warnings on parameter ordering.}
11754 This switch suppresses warnings on cases of suspicious parameter
11755 ordering.
11756 @end table
11758 @geindex -gnatwq (gcc)
11760 @geindex Parentheses
11761 @geindex warnings
11764 @table @asis
11766 @item @code{-gnatwq}
11768 @emph{Activate warnings on questionable missing parentheses.}
11770 This switch activates warnings for cases where parentheses are not used and
11771 the result is potential ambiguity from a readers point of view. For example
11772 (not a > b) when a and b are modular means ((not a) > b) and very likely the
11773 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
11774 quite likely ((-x) mod 5) was intended. In such situations it seems best to
11775 follow the rule of always parenthesizing to make the association clear, and
11776 this warning switch warns if such parentheses are not present. The default
11777 is that these warnings are given.
11778 @end table
11780 @geindex -gnatwQ (gcc)
11783 @table @asis
11785 @item @code{-gnatwQ}
11787 @emph{Suppress warnings on questionable missing parentheses.}
11789 This switch suppresses warnings for cases where the association is not
11790 clear and the use of parentheses is preferred.
11791 @end table
11793 @geindex -gnatwr (gcc)
11796 @table @asis
11798 @item @code{-gnatwr}
11800 @emph{Activate warnings on redundant constructs.}
11802 This switch activates warnings for redundant constructs. The following
11803 is the current list of constructs regarded as redundant:
11806 @itemize *
11808 @item 
11809 Assignment of an item to itself.
11811 @item 
11812 Type conversion that converts an expression to its own type.
11814 @item 
11815 Use of the attribute @cite{Base} where @cite{typ'Base} is the same
11816 as @cite{typ}.
11818 @item 
11819 Use of pragma @cite{Pack} when all components are placed by a record
11820 representation clause.
11822 @item 
11823 Exception handler containing only a reraise statement (raise with no
11824 operand) which has no effect.
11826 @item 
11827 Use of the operator abs on an operand that is known at compile time
11828 to be non-negative
11830 @item 
11831 Comparison of boolean expressions to an explicit True value.
11832 @end itemize
11834 The default is that warnings for redundant constructs are not given.
11835 @end table
11837 @geindex -gnatwR (gcc)
11840 @table @asis
11842 @item @code{-gnatwR}
11844 @emph{Suppress warnings on redundant constructs.}
11846 This switch suppresses warnings for redundant constructs.
11847 @end table
11849 @geindex -gnatw.r (gcc)
11852 @table @asis
11854 @item @code{-gnatw.r}
11856 @emph{Activate warnings for object renaming function.}
11858 This switch activates warnings for an object renaming that renames a
11859 function call, which is equivalent to a constant declaration (as
11860 opposed to renaming the function itself).  The default is that these
11861 warnings are given.
11862 @end table
11864 @geindex -gnatwT (gcc)
11867 @table @asis
11869 @item @code{-gnatw.R}
11871 @emph{Suppress warnings for object renaming function.}
11873 This switch suppresses warnings for object renaming function.
11874 @end table
11876 @geindex -gnatws (gcc)
11879 @table @asis
11881 @item @code{-gnatws}
11883 @emph{Suppress all warnings.}
11885 This switch completely suppresses the
11886 output of all warning messages from the GNAT front end, including
11887 both warnings that can be controlled by switches described in this
11888 section, and those that are normally given unconditionally. The
11889 effect of this suppress action can only be cancelled by a subsequent
11890 use of the switch @emph{-gnatwn}.
11892 Note that switch @emph{-gnatws} does not suppress
11893 warnings from the @emph{gcc} back end.
11894 To suppress these back end warnings as well, use the switch @emph{-w}
11895 in addition to @emph{-gnatws}. Also this switch has no effect on the
11896 handling of style check messages.
11897 @end table
11899 @geindex -gnatw.s (gcc)
11901 @geindex Record Representation (component sizes)
11904 @table @asis
11906 @item @code{-gnatw.s}
11908 @emph{Activate warnings on overridden size clauses.}
11910 This switch activates warnings on component clauses in record
11911 representation clauses where the length given overrides that
11912 specified by an explicit size clause for the component type. A
11913 warning is similarly given in the array case if a specified
11914 component size overrides an explicit size clause for the array
11915 component type.
11916 @end table
11918 @geindex -gnatw.S (gcc)
11921 @table @asis
11923 @item @code{-gnatw.S}
11925 @emph{Suppress warnings on overridden size clauses.}
11927 This switch suppresses warnings on component clauses in record
11928 representation clauses that override size clauses, and similar
11929 warnings when an array component size overrides a size clause.
11930 @end table
11932 @geindex -gnatwt (gcc)
11934 @geindex Deactivated code
11935 @geindex warnings
11937 @geindex Deleted code
11938 @geindex warnings
11941 @table @asis
11943 @item @code{-gnatwt}
11945 @emph{Activate warnings for tracking of deleted conditional code.}
11947 This switch activates warnings for tracking of code in conditionals (IF and
11948 CASE statements) that is detected to be dead code which cannot be executed, and
11949 which is removed by the front end. This warning is off by default. This may be
11950 useful for detecting deactivated code in certified applications.
11951 @end table
11953 @geindex -gnatwT (gcc)
11956 @table @asis
11958 @item @code{-gnatwT}
11960 @emph{Suppress warnings for tracking of deleted conditional code.}
11962 This switch suppresses warnings for tracking of deleted conditional code.
11963 @end table
11965 @geindex -gnatw.t (gcc)
11968 @table @asis
11970 @item @code{-gnatw.t}
11972 @emph{Activate warnings on suspicious contracts.}
11974 This switch activates warnings on suspicious contracts. This includes
11975 warnings on suspicious postconditions (whether a pragma @cite{Postcondition} or a
11976 @cite{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
11977 @cite{Contract_Cases}). A function postcondition or contract case is suspicious
11978 when no postcondition or contract case for this function mentions the result
11979 of the function.  A procedure postcondition or contract case is suspicious
11980 when it only refers to the pre-state of the procedure, because in that case
11981 it should rather be expressed as a precondition. This switch also controls
11982 warnings on suspicious cases of expressions typically found in contracts like
11983 quantified expressions and uses of Update attribute. The default is that such
11984 warnings are generated.
11985 @end table
11987 @geindex -gnatw.T (gcc)
11990 @table @asis
11992 @item @code{-gnatw.T}
11994 @emph{Suppress warnings on suspicious contracts.}
11996 This switch suppresses warnings on suspicious contracts.
11997 @end table
11999 @geindex -gnatwu (gcc)
12002 @table @asis
12004 @item @code{-gnatwu}
12006 @emph{Activate warnings on unused entities.}
12008 This switch activates warnings to be generated for entities that
12009 are declared but not referenced, and for units that are @emph{with}ed
12010 and not
12011 referenced. In the case of packages, a warning is also generated if
12012 no entities in the package are referenced. This means that if a with'ed
12013 package is referenced but the only references are in @cite{use}
12014 clauses or @cite{renames}
12015 declarations, a warning is still generated. A warning is also generated
12016 for a generic package that is @emph{with}ed but never instantiated.
12017 In the case where a package or subprogram body is compiled, and there
12018 is a @emph{with} on the corresponding spec
12019 that is only referenced in the body,
12020 a warning is also generated, noting that the
12021 @emph{with} can be moved to the body. The default is that
12022 such warnings are not generated.
12023 This switch also activates warnings on unreferenced formals
12024 (it includes the effect of @emph{-gnatwf}).
12025 @end table
12027 @geindex -gnatwU (gcc)
12030 @table @asis
12032 @item @code{-gnatwU}
12034 @emph{Suppress warnings on unused entities.}
12036 This switch suppresses warnings for unused entities and packages.
12037 It also turns off warnings on unreferenced formals (and thus includes
12038 the effect of @emph{-gnatwF}).
12039 @end table
12041 @geindex -gnatw.u (gcc)
12044 @table @asis
12046 @item @code{-gnatw.u}
12048 @emph{Activate warnings on unordered enumeration types.}
12050 This switch causes enumeration types to be considered as conceptually
12051 unordered, unless an explicit pragma @cite{Ordered} is given for the type.
12052 The effect is to generate warnings in clients that use explicit comparisons
12053 or subranges, since these constructs both treat objects of the type as
12054 ordered. (A @emph{client} is defined as a unit that is other than the unit in
12055 which the type is declared, or its body or subunits.) Please refer to
12056 the description of pragma @cite{Ordered} in the
12057 @cite{GNAT Reference Manual} for further details.
12058 The default is that such warnings are not generated.
12059 @end table
12061 @geindex -gnatw.U (gcc)
12064 @table @asis
12066 @item @code{-gnatw.U}
12068 @emph{Deactivate warnings on unordered enumeration types.}
12070 This switch causes all enumeration types to be considered as ordered, so
12071 that no warnings are given for comparisons or subranges for any type.
12072 @end table
12074 @geindex -gnatwv (gcc)
12076 @geindex Unassigned variable warnings
12079 @table @asis
12081 @item @code{-gnatwv}
12083 @emph{Activate warnings on unassigned variables.}
12085 This switch activates warnings for access to variables which
12086 may not be properly initialized. The default is that
12087 such warnings are generated.
12088 @end table
12090 @geindex -gnatwV (gcc)
12093 @table @asis
12095 @item @code{-gnatwV}
12097 @emph{Suppress warnings on unassigned variables.}
12099 This switch suppresses warnings for access to variables which
12100 may not be properly initialized.
12101 For variables of a composite type, the warning can also be suppressed in
12102 Ada 2005 by using a default initialization with a box. For example, if
12103 Table is an array of records whose components are only partially uninitialized,
12104 then the following code:
12106 @example
12107 Tab : Table := (others => <>);
12108 @end example
12110 will suppress warnings on subsequent statements that access components
12111 of variable Tab.
12112 @end table
12114 @geindex -gnatw.v (gcc)
12116 @geindex bit order warnings
12119 @table @asis
12121 @item @code{-gnatw.v}
12123 @emph{Activate info messages for non-default bit order.}
12125 This switch activates messages (labeled "info", they are not warnings,
12126 just informational messages) about the effects of non-default bit-order
12127 on records to which a component clause is applied. The effect of specifying
12128 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
12129 these messages, which are given by default, are useful in understanding the
12130 exact consequences of using this feature.
12131 @end table
12133 @geindex -gnatw.V (gcc)
12136 @table @asis
12138 @item @code{-gnatw.V}
12140 @emph{Suppress info messages for non-default bit order.}
12142 This switch suppresses information messages for the effects of specifying
12143 non-default bit order on record components with component clauses.
12144 @end table
12146 @geindex -gnatww (gcc)
12148 @geindex String indexing warnings
12151 @table @asis
12153 @item @code{-gnatww}
12155 @emph{Activate warnings on wrong low bound assumption.}
12157 This switch activates warnings for indexing an unconstrained string parameter
12158 with a literal or S'Length. This is a case where the code is assuming that the
12159 low bound is one, which is in general not true (for example when a slice is
12160 passed). The default is that such warnings are generated.
12161 @end table
12163 @geindex -gnatwW (gcc)
12166 @table @asis
12168 @item @code{-gnatwW}
12170 @emph{Suppress warnings on wrong low bound assumption.}
12172 This switch suppresses warnings for indexing an unconstrained string parameter
12173 with a literal or S'Length. Note that this warning can also be suppressed
12174 in a particular case by adding an assertion that the lower bound is 1,
12175 as shown in the following example:
12177 @example
12178 procedure K (S : String) is
12179    pragma Assert (S'First = 1);
12180    ...
12181 @end example
12182 @end table
12184 @geindex -gnatw.w (gcc)
12186 @geindex Warnings Off control
12189 @table @asis
12191 @item @code{-gnatw.w}
12193 @emph{Activate warnings on Warnings Off pragmas.}
12195 This switch activates warnings for use of @cite{pragma Warnings (Off@comma{} entity)}
12196 where either the pragma is entirely useless (because it suppresses no
12197 warnings), or it could be replaced by @cite{pragma Unreferenced} or
12198 @cite{pragma Unmodified}.
12199 Also activates warnings for the case of
12200 Warnings (Off, String), where either there is no matching
12201 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12202 The default is that these warnings are not given.
12203 @end table
12205 @geindex -gnatw.W (gcc)
12208 @table @asis
12210 @item @code{-gnatw.W}
12212 @emph{Suppress warnings on unnecessary Warnings Off pragmas.}
12214 This switch suppresses warnings for use of @cite{pragma Warnings (Off@comma{} ...)}.
12215 @end table
12217 @geindex -gnatwx (gcc)
12219 @geindex Export/Import pragma warnings
12222 @table @asis
12224 @item @code{-gnatwx}
12226 @emph{Activate warnings on Export/Import pragmas.}
12228 This switch activates warnings on Export/Import pragmas when
12229 the compiler detects a possible conflict between the Ada and
12230 foreign language calling sequences. For example, the use of
12231 default parameters in a convention C procedure is dubious
12232 because the C compiler cannot supply the proper default, so
12233 a warning is issued. The default is that such warnings are
12234 generated.
12235 @end table
12237 @geindex -gnatwX (gcc)
12240 @table @asis
12242 @item @code{-gnatwX}
12244 @emph{Suppress warnings on Export/Import pragmas.}
12246 This switch suppresses warnings on Export/Import pragmas.
12247 The sense of this is that you are telling the compiler that
12248 you know what you are doing in writing the pragma, and it
12249 should not complain at you.
12250 @end table
12252 @geindex -gnatwm (gcc)
12255 @table @asis
12257 @item @code{-gnatw.x}
12259 @emph{Activate warnings for No_Exception_Propagation mode.}
12261 This switch activates warnings for exception usage when pragma Restrictions
12262 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
12263 explicit exception raises which are not covered by a local handler, and for
12264 exception handlers which do not cover a local raise. The default is that these
12265 warnings are not given.
12267 @item @code{-gnatw.X}
12269 @emph{Disable warnings for No_Exception_Propagation mode.}
12271 This switch disables warnings for exception usage when pragma Restrictions
12272 (No_Exception_Propagation) is in effect.
12273 @end table
12275 @geindex -gnatwy (gcc)
12277 @geindex Ada compatibility issues warnings
12280 @table @asis
12282 @item @code{-gnatwy}
12284 @emph{Activate warnings for Ada compatibility issues.}
12286 For the most part, newer versions of Ada are upwards compatible
12287 with older versions. For example, Ada 2005 programs will almost
12288 always work when compiled as Ada 2012.
12289 However there are some exceptions (for example the fact that
12290 @cite{some} is now a reserved word in Ada 2012). This
12291 switch activates several warnings to help in identifying
12292 and correcting such incompatibilities. The default is that
12293 these warnings are generated. Note that at one point Ada 2005
12294 was called Ada 0Y, hence the choice of character.
12295 @end table
12297 @geindex -gnatwY (gcc)
12299 @geindex Ada compatibility issues warnings
12302 @table @asis
12304 @item @code{-gnatwY}
12306 @emph{Disable warnings for Ada compatibility issues.}
12308 This switch suppresses the warnings intended to help in identifying
12309 incompatibilities between Ada language versions.
12310 @end table
12312 @geindex -gnatw.y (gcc)
12314 @geindex Package spec needing body
12317 @table @asis
12319 @item @code{-gnatw.y}
12321 @emph{Activate information messages for why package spec needs body.}
12323 There are a number of cases in which a package spec needs a body.
12324 For example, the use of pragma Elaborate_Body, or the declaration
12325 of a procedure specification requiring a completion. This switch
12326 causes information messages to be output showing why a package
12327 specification requires a body. This can be useful in the case of
12328 a large package specification which is unexpectedly requiring a
12329 body. The default is that such information messages are not output.
12330 @end table
12332 @geindex -gnatw.Y (gcc)
12334 @geindex No information messages for why package spec needs body
12337 @table @asis
12339 @item @code{-gnatw.Y}
12341 @emph{Disable information messages for why package spec needs body.}
12343 This switch suppresses the output of information messages showing why
12344 a package specification needs a body.
12345 @end table
12347 @geindex -gnatwz (gcc)
12349 @geindex Unchecked_Conversion warnings
12352 @table @asis
12354 @item @code{-gnatwz}
12356 @emph{Activate warnings on unchecked conversions.}
12358 This switch activates warnings for unchecked conversions
12359 where the types are known at compile time to have different
12360 sizes. The default is that such warnings are generated. Warnings are also
12361 generated for subprogram pointers with different conventions.
12362 @end table
12364 @geindex -gnatwZ (gcc)
12367 @table @asis
12369 @item @code{-gnatwZ}
12371 @emph{Suppress warnings on unchecked conversions.}
12373 This switch suppresses warnings for unchecked conversions
12374 where the types are known at compile time to have different
12375 sizes or conventions.
12376 @end table
12378 @geindex -gnatw.z (gcc)
12380 @geindex Size/Alignment warnings
12383 @table @asis
12385 @item @code{-gnatw.z}
12387 @emph{Activate warnings for size not a multiple of alignment.}
12389 This switch activates warnings for cases of record types with
12390 specified @cite{Size} and @cite{Alignment} attributes where the
12391 size is not a multiple of the alignment, resulting in an object
12392 size that is greater than the specified size. The default
12393 is that such warnings are generated.
12394 @end table
12396 @geindex -gnatw.Z (gcc)
12398 @geindex Size/Alignment warnings
12401 @table @asis
12403 @item @code{-gnatw.Z}
12405 @emph{Suppress warnings for size not a multiple of alignment.}
12407 This switch suppresses warnings for cases of record types with
12408 specified @cite{Size} and @cite{Alignment} attributes where the
12409 size is not a multiple of the alignment, resulting in an object
12410 size that is greater than the specified size.
12411 The warning can also be
12412 suppressed by giving an explicit @cite{Object_Size} value.
12413 @end table
12415 @geindex -Wunused (gcc)
12418 @table @asis
12420 @item @code{-Wunused}
12422 The warnings controlled by the @emph{-gnatw} switch are generated by
12423 the front end of the compiler. The @emph{GCC} back end can provide
12424 additional warnings and they are controlled by the @emph{-W} switch.
12425 For example, @emph{-Wunused} activates back end
12426 warnings for entities that are declared but not referenced.
12427 @end table
12429 @geindex -Wuninitialized (gcc)
12432 @table @asis
12434 @item @code{-Wuninitialized}
12436 Similarly, @emph{-Wuninitialized} activates
12437 the back end warning for uninitialized variables. This switch must be
12438 used in conjunction with an optimization level greater than zero.
12439 @end table
12441 @geindex -Wstack-usage (gcc)
12444 @table @asis
12446 @item @code{-Wstack-usage=@emph{len}}
12448 Warn if the stack usage of a subprogram might be larger than @cite{len} bytes.
12449 See @ref{f5,,Static Stack Usage Analysis} for details.
12450 @end table
12452 @geindex -Wall (gcc)
12455 @table @asis
12457 @item @code{-Wall}
12459 This switch enables most warnings from the @emph{GCC} back end.
12460 The code generator detects a number of warning situations that are missed
12461 by the @emph{GNAT} front end, and this switch can be used to activate them.
12462 The use of this switch also sets the default front end warning mode to
12463 @emph{-gnatwa}, that is, most front end warnings activated as well.
12464 @end table
12466 @geindex -w (gcc)
12469 @table @asis
12471 @item @code{-w}
12473 Conversely, this switch suppresses warnings from the @emph{GCC} back end.
12474 The use of this switch also sets the default front end warning mode to
12475 @emph{-gnatws}, that is, front end warnings suppressed as well.
12476 @end table
12478 @geindex -Werror (gcc)
12481 @table @asis
12483 @item @code{-Werror}
12485 This switch causes warnings from the @emph{GCC} back end to be treated as
12486 errors.  The warning string still appears, but the warning messages are
12487 counted as errors, and prevent the generation of an object file.
12488 @end table
12490 A string of warning parameters can be used in the same parameter. For example:
12492 @example
12493 -gnatwaGe
12494 @end example
12496 will turn on all optional warnings except for unrecognized pragma warnings,
12497 and also specify that warnings should be treated as errors.
12499 When no switch @emph{-gnatw} is used, this is equivalent to:
12501 @quotation
12504 @itemize *
12506 @item 
12507 @code{-gnatw.a}
12509 @item 
12510 @code{-gnatwB}
12512 @item 
12513 @code{-gnatw.b}
12515 @item 
12516 @code{-gnatwC}
12518 @item 
12519 @code{-gnatw.C}
12521 @item 
12522 @code{-gnatwD}
12524 @item 
12525 @code{-gnatwF}
12527 @item 
12528 @code{-gnatwg}
12530 @item 
12531 @code{-gnatwH}
12533 @item 
12534 @code{-gnatwi}
12536 @item 
12537 @code{-gnatw.I}
12539 @item 
12540 @code{-gnatwJ}
12542 @item 
12543 @code{-gnatwK}
12545 @item 
12546 @code{-gnatwL}
12548 @item 
12549 @code{-gnatw.L}
12551 @item 
12552 @code{-gnatwM}
12554 @item 
12555 @code{-gnatw.m}
12557 @item 
12558 @code{-gnatwn}
12560 @item 
12561 @code{-gnatwo}
12563 @item 
12564 @code{-gnatw.O}
12566 @item 
12567 @code{-gnatwP}
12569 @item 
12570 @code{-gnatw.P}
12572 @item 
12573 @code{-gnatwq}
12575 @item 
12576 @code{-gnatwR}
12578 @item 
12579 @code{-gnatw.R}
12581 @item 
12582 @code{-gnatw.S}
12584 @item 
12585 @code{-gnatwT}
12587 @item 
12588 @code{-gnatw.T}
12590 @item 
12591 @code{-gnatwU}
12593 @item 
12594 @code{-gnatwv}
12596 @item 
12597 @code{-gnatww}
12599 @item 
12600 @code{-gnatw.W}
12602 @item 
12603 @code{-gnatwx}
12605 @item 
12606 @code{-gnatw.X}
12608 @item 
12609 @code{-gnatwy}
12611 @item 
12612 @code{-gnatwz}
12613 @end itemize
12614 @end quotation
12616 @node Debugging and Assertion Control,Validity Checking,Warning Message Control,Compiler Switches
12617 @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}
12618 @subsection Debugging and Assertion Control
12621 @geindex -gnata (gcc)
12624 @table @asis
12626 @item @code{-gnata}
12628 @geindex Assert
12630 @geindex Debug
12632 @geindex Assertions
12634 @geindex Precondition
12636 @geindex Postcondition
12638 @geindex Type invariants
12640 @geindex Subtype predicates
12642 The @cite{-gnata} option is equivalent to the following Assertion_Policy pragma:
12644 @example
12645 pragma Assertion_Policy (Check);
12646 @end example
12648 Which is a shorthand for:
12650 @example
12651 pragma Assertion_Policy
12652   (Assert               => Check,
12653    Static_Predicate     => Check,
12654    Dynamic_Predicate    => Check,
12655    Pre                  => Check,
12656    Pre'Class            => Check,
12657    Post                 => Check,
12658    Post'Class           => Check,
12659    Type_Invariant       => Check,
12660    Type_Invariant'Class => Check);
12661 @end example
12663 The pragmas @cite{Assert} and @cite{Debug} normally have no effect and
12664 are ignored. This switch, where @code{a} stands for assert, causes
12665 pragmas @cite{Assert} and @cite{Debug} to be activated. This switch also
12666 causes preconditions, postconditions, subtype predicates, and
12667 type invariants to be activated.
12669 The pragmas have the form:
12671 @example
12672 pragma Assert (<Boolean-expression> [, <static-string-expression>])
12673 pragma Debug (<procedure call>)
12674 pragma Type_Invariant (<type-local-name>, <Boolean-expression>)
12675 pragma Predicate (<type-local-name>, <Boolean-expression>)
12676 pragma Precondition (<Boolean-expression>, <string-expression>)
12677 pragma Postcondition (<Boolean-expression>, <string-expression>)
12678 @end example
12680 The aspects have the form:
12682 @example
12683 with [Pre|Post|Type_Invariant|Dynamic_Predicate|Static_Predicate]
12684   => <Boolean-expression>;
12685 @end example
12687 The @cite{Assert} pragma causes @cite{Boolean-expression} to be tested.
12688 If the result is @cite{True}, the pragma has no effect (other than
12689 possible side effects from evaluating the expression). If the result is
12690 @cite{False}, the exception @cite{Assert_Failure} declared in the package
12691 @cite{System.Assertions} is raised (passing @cite{static-string-expression}, if
12692 present, as the message associated with the exception). If no string
12693 expression is given, the default is a string containing the file name and
12694 line number of the pragma.
12696 The @cite{Debug} pragma causes @cite{procedure} to be called. Note that
12697 @cite{pragma Debug} may appear within a declaration sequence, allowing
12698 debugging procedures to be called between declarations.
12700 For the aspect specification, the @cite{<Boolean-expression>} is evaluated.
12701 If the result is @cite{True}, the aspect has no effect. If the result
12702 is @cite{False}, the exception @cite{Assert_Failure} is raised.
12703 @end table
12705 @node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
12706 @anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{102}
12707 @subsection Validity Checking
12710 @geindex Validity Checking
12712 The Ada Reference Manual defines the concept of invalid values (see
12713 RM 13.9.1). The primary source of invalid values is uninitialized
12714 variables. A scalar variable that is left uninitialized may contain
12715 an invalid value; the concept of invalid does not apply to access or
12716 composite types.
12718 It is an error to read an invalid value, but the RM does not require
12719 run-time checks to detect such errors, except for some minimal
12720 checking to prevent erroneous execution (i.e. unpredictable
12721 behavior). This corresponds to the @emph{-gnatVd} switch below,
12722 which is the default. For example, by default, if the expression of a
12723 case statement is invalid, it will raise Constraint_Error rather than
12724 causing a wild jump, and if an array index on the left-hand side of an
12725 assignment is invalid, it will raise Constraint_Error rather than
12726 overwriting an arbitrary memory location.
12728 The @emph{-gnatVa} may be used to enable additional validity checks,
12729 which are not required by the RM. These checks are often very
12730 expensive (which is why the RM does not require them). These checks
12731 are useful in tracking down uninitialized variables, but they are
12732 not usually recommended for production builds, and in particular
12733 we do not recommend using these extra validity checking options in
12734 combination with optimization, since this can confuse the optimizer.
12735 If performance is a consideration, leading to the need to optimize,
12736 then the validity checking options should not be used.
12738 The other @emph{-gnatV}@code{x} switches below allow finer-grained
12739 control; you can enable whichever validity checks you desire. However,
12740 for most debugging purposes, @emph{-gnatVa} is sufficient, and the
12741 default @emph{-gnatVd} (i.e. standard Ada behavior) is usually
12742 sufficient for non-debugging use.
12744 The @emph{-gnatB} switch tells the compiler to assume that all
12745 values are valid (that is, within their declared subtype range)
12746 except in the context of a use of the Valid attribute. This means
12747 the compiler can generate more efficient code, since the range
12748 of values is better known at compile time. However, an uninitialized
12749 variable can cause wild jumps and memory corruption in this mode.
12751 The @emph{-gnatV}@code{x} switch allows control over the validity
12752 checking mode as described below.
12753 The @code{x} argument is a string of letters that
12754 indicate validity checks that are performed or not performed in addition
12755 to the default checks required by Ada as described above.
12757 @geindex -gnatVa (gcc)
12760 @table @asis
12762 @item @code{-gnatVa}
12764 @emph{All validity checks.}
12766 All validity checks are turned on.
12767 That is, @emph{-gnatVa} is
12768 equivalent to @emph{gnatVcdfimorst}.
12769 @end table
12771 @geindex -gnatVc (gcc)
12774 @table @asis
12776 @item @code{-gnatVc}
12778 @emph{Validity checks for copies.}
12780 The right hand side of assignments, and the initializing values of
12781 object declarations are validity checked.
12782 @end table
12784 @geindex -gnatVd (gcc)
12787 @table @asis
12789 @item @code{-gnatVd}
12791 @emph{Default (RM) validity checks.}
12793 Some validity checks are done by default following normal Ada semantics
12794 (RM 13.9.1 (9-11)).
12795 A check is done in case statements that the expression is within the range
12796 of the subtype. If it is not, Constraint_Error is raised.
12797 For assignments to array components, a check is done that the expression used
12798 as index is within the range. If it is not, Constraint_Error is raised.
12799 Both these validity checks may be turned off using switch @emph{-gnatVD}.
12800 They are turned on by default. If @emph{-gnatVD} is specified, a subsequent
12801 switch @emph{-gnatVd} will leave the checks turned on.
12802 Switch @emph{-gnatVD} should be used only if you are sure that all such
12803 expressions have valid values. If you use this switch and invalid values
12804 are present, then the program is erroneous, and wild jumps or memory
12805 overwriting may occur.
12806 @end table
12808 @geindex -gnatVe (gcc)
12811 @table @asis
12813 @item @code{-gnatVe}
12815 @emph{Validity checks for elementary components.}
12817 In the absence of this switch, assignments to record or array components are
12818 not validity checked, even if validity checks for assignments generally
12819 (@emph{-gnatVc}) are turned on. In Ada, assignment of composite values do not
12820 require valid data, but assignment of individual components does. So for
12821 example, there is a difference between copying the elements of an array with a
12822 slice assignment, compared to assigning element by element in a loop. This
12823 switch allows you to turn off validity checking for components, even when they
12824 are assigned component by component.
12825 @end table
12827 @geindex -gnatVf (gcc)
12830 @table @asis
12832 @item @code{-gnatVf}
12834 @emph{Validity checks for floating-point values.}
12836 In the absence of this switch, validity checking occurs only for discrete
12837 values. If @emph{-gnatVf} is specified, then validity checking also applies
12838 for floating-point values, and NaNs and infinities are considered invalid,
12839 as well as out of range values for constrained types. Note that this means
12840 that standard IEEE infinity mode is not allowed. The exact contexts
12841 in which floating-point values are checked depends on the setting of other
12842 options. For example, @emph{-gnatVif} or @emph{-gnatVfi}
12843 (the order does not matter) specifies that floating-point parameters of mode
12844 @cite{in} should be validity checked.
12845 @end table
12847 @geindex -gnatVi (gcc)
12850 @table @asis
12852 @item @code{-gnatVi}
12854 @emph{Validity checks for `in` mode parameters.}
12856 Arguments for parameters of mode @cite{in} are validity checked in function
12857 and procedure calls at the point of call.
12858 @end table
12860 @geindex -gnatVm (gcc)
12863 @table @asis
12865 @item @code{-gnatVm}
12867 @emph{Validity checks for `in out` mode parameters.}
12869 Arguments for parameters of mode @cite{in out} are validity checked in
12870 procedure calls at the point of call. The @cite{'m'} here stands for
12871 modify, since this concerns parameters that can be modified by the call.
12872 Note that there is no specific option to test @cite{out} parameters,
12873 but any reference within the subprogram will be tested in the usual
12874 manner, and if an invalid value is copied back, any reference to it
12875 will be subject to validity checking.
12876 @end table
12878 @geindex -gnatVn (gcc)
12881 @table @asis
12883 @item @code{-gnatVn}
12885 @emph{No validity checks.}
12887 This switch turns off all validity checking, including the default checking
12888 for case statements and left hand side subscripts. Note that the use of
12889 the switch @emph{-gnatp} suppresses all run-time checks, including
12890 validity checks, and thus implies @emph{-gnatVn}. When this switch
12891 is used, it cancels any other @emph{-gnatV} previously issued.
12892 @end table
12894 @geindex -gnatVo (gcc)
12897 @table @asis
12899 @item @code{-gnatVo}
12901 @emph{Validity checks for operator and attribute operands.}
12903 Arguments for predefined operators and attributes are validity checked.
12904 This includes all operators in package @cite{Standard},
12905 the shift operators defined as intrinsic in package @cite{Interfaces}
12906 and operands for attributes such as @cite{Pos}. Checks are also made
12907 on individual component values for composite comparisons, and on the
12908 expressions in type conversions and qualified expressions. Checks are
12909 also made on explicit ranges using @code{..} (e.g., slices, loops etc).
12910 @end table
12912 @geindex -gnatVp (gcc)
12915 @table @asis
12917 @item @code{-gnatVp}
12919 @emph{Validity checks for parameters.}
12921 This controls the treatment of parameters within a subprogram (as opposed
12922 to @emph{-gnatVi} and @emph{-gnatVm} which control validity testing
12923 of parameters on a call. If either of these call options is used, then
12924 normally an assumption is made within a subprogram that the input arguments
12925 have been validity checking at the point of call, and do not need checking
12926 again within a subprogram). If @emph{-gnatVp} is set, then this assumption
12927 is not made, and parameters are not assumed to be valid, so their validity
12928 will be checked (or rechecked) within the subprogram.
12929 @end table
12931 @geindex -gnatVr (gcc)
12934 @table @asis
12936 @item @code{-gnatVr}
12938 @emph{Validity checks for function returns.}
12940 The expression in @cite{return} statements in functions is validity
12941 checked.
12942 @end table
12944 @geindex -gnatVs (gcc)
12947 @table @asis
12949 @item @code{-gnatVs}
12951 @emph{Validity checks for subscripts.}
12953 All subscripts expressions are checked for validity, whether they appear
12954 on the right side or left side (in default mode only left side subscripts
12955 are validity checked).
12956 @end table
12958 @geindex -gnatVt (gcc)
12961 @table @asis
12963 @item @code{-gnatVt}
12965 @emph{Validity checks for tests.}
12967 Expressions used as conditions in @cite{if}, @cite{while} or @cite{exit}
12968 statements are checked, as well as guard expressions in entry calls.
12969 @end table
12971 The @emph{-gnatV} switch may be followed by a string of letters
12972 to turn on a series of validity checking options.
12973 For example, @code{-gnatVcr}
12974 specifies that in addition to the default validity checking, copies and
12975 function return expressions are to be validity checked.
12976 In order to make it easier to specify the desired combination of effects,
12977 the upper case letters @cite{CDFIMORST} may
12978 be used to turn off the corresponding lower case option.
12979 Thus @code{-gnatVaM} turns on all validity checking options except for
12980 checking of @cite{**in out**} procedure arguments.
12982 The specification of additional validity checking generates extra code (and
12983 in the case of @emph{-gnatVa} the code expansion can be substantial).
12984 However, these additional checks can be very useful in detecting
12985 uninitialized variables, incorrect use of unchecked conversion, and other
12986 errors leading to invalid values. The use of pragma @cite{Initialize_Scalars}
12987 is useful in conjunction with the extra validity checking, since this
12988 ensures that wherever possible uninitialized variables have invalid values.
12990 See also the pragma @cite{Validity_Checks} which allows modification of
12991 the validity checking mode at the program source level, and also allows for
12992 temporary disabling of validity checks.
12994 @node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
12995 @anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{103}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{fb}
12996 @subsection Style Checking
12999 @geindex Style checking
13001 @geindex -gnaty (gcc)
13003 The @emph{-gnatyx} switch causes the compiler to
13004 enforce specified style rules. A limited set of style rules has been used
13005 in writing the GNAT sources themselves. This switch allows user programs
13006 to activate all or some of these checks. If the source program fails a
13007 specified style check, an appropriate message is given, preceded by
13008 the character sequence '(style)'. This message does not prevent
13009 successful compilation (unless the @emph{-gnatwe} switch is used).
13011 Note that this is by no means intended to be a general facility for
13012 checking arbitrary coding standards. It is simply an embedding of the
13013 style rules we have chosen for the GNAT sources. If you are starting
13014 a project which does not have established style standards, you may
13015 find it useful to adopt the entire set of GNAT coding standards, or
13016 some subset of them.
13019 The string @cite{x} is a sequence of letters or digits
13020 indicating the particular style
13021 checks to be performed. The following checks are defined:
13023 @geindex -gnaty[0-9] (gcc)
13026 @table @asis
13028 @item @code{-gnaty0}
13030 @emph{Specify indentation level.}
13032 If a digit from 1-9 appears
13033 in the string after @emph{-gnaty}
13034 then proper indentation is checked, with the digit indicating the
13035 indentation level required. A value of zero turns off this style check.
13036 The general style of required indentation is as specified by
13037 the examples in the Ada Reference Manual. Full line comments must be
13038 aligned with the @cite{--} starting on a column that is a multiple of
13039 the alignment level, or they may be aligned the same way as the following
13040 non-blank line (this is useful when full line comments appear in the middle
13041 of a statement, or they may be aligned with the source line on the previous
13042 non-blank line.
13043 @end table
13045 @geindex -gnatya (gcc)
13048 @table @asis
13050 @item @code{-gnatya}
13052 @emph{Check attribute casing.}
13054 Attribute names, including the case of keywords such as @cite{digits}
13055 used as attributes names, must be written in mixed case, that is, the
13056 initial letter and any letter following an underscore must be uppercase.
13057 All other letters must be lowercase.
13058 @end table
13060 @geindex -gnatyA (gcc)
13063 @table @asis
13065 @item @code{-gnatyA}
13067 @emph{Use of array index numbers in array attributes.}
13069 When using the array attributes First, Last, Range,
13070 or Length, the index number must be omitted for one-dimensional arrays
13071 and is required for multi-dimensional arrays.
13072 @end table
13074 @geindex -gnatyb (gcc)
13077 @table @asis
13079 @item @code{-gnatyb}
13081 @emph{Blanks not allowed at statement end.}
13083 Trailing blanks are not allowed at the end of statements. The purpose of this
13084 rule, together with h (no horizontal tabs), is to enforce a canonical format
13085 for the use of blanks to separate source tokens.
13086 @end table
13088 @geindex -gnatyB (gcc)
13091 @table @asis
13093 @item @code{-gnatyB}
13095 @emph{Check Boolean operators.}
13097 The use of AND/OR operators is not permitted except in the cases of modular
13098 operands, array operands, and simple stand-alone boolean variables or
13099 boolean constants. In all other cases @cite{and then}/@cite{or else} are
13100 required.
13101 @end table
13103 @geindex -gnatyc (gcc)
13106 @table @asis
13108 @item @code{-gnatyc}
13110 @emph{Check comments, double space.}
13112 Comments must meet the following set of rules:
13115 @itemize *
13117 @item 
13118 The '@cite{--}' that starts the column must either start in column one,
13119 or else at least one blank must precede this sequence.
13121 @item 
13122 Comments that follow other tokens on a line must have at least one blank
13123 following the '@cite{--}' at the start of the comment.
13125 @item 
13126 Full line comments must have at least two blanks following the
13127 '@cite{--}' that starts the comment, with the following exceptions.
13129 @item 
13130 A line consisting only of the '@cite{--}' characters, possibly preceded
13131 by blanks is permitted.
13133 @item 
13134 A comment starting with '@cite{--x}' where @cite{x} is a special character
13135 is permitted.
13136 This allows proper processing of the output generated by specialized tools
13137 including @emph{gnatprep} (where '@cite{--!}' is used) and the SPARK
13138 annotation
13139 language (where '@cite{--#}' is used). For the purposes of this rule, a
13140 special character is defined as being in one of the ASCII ranges
13141 @cite{16#21#...16#2F#} or @cite{16#3A#...16#3F#}.
13142 Note that this usage is not permitted
13143 in GNAT implementation units (i.e., when @emph{-gnatg} is used).
13145 @item 
13146 A line consisting entirely of minus signs, possibly preceded by blanks, is
13147 permitted. This allows the construction of box comments where lines of minus
13148 signs are used to form the top and bottom of the box.
13150 @item 
13151 A comment that starts and ends with '@cite{--}' is permitted as long as at
13152 least one blank follows the initial '@cite{--}'. Together with the preceding
13153 rule, this allows the construction of box comments, as shown in the following
13154 example:
13156 @example
13157 ---------------------------
13158 -- This is a box comment --
13159 -- with two text lines.  --
13160 ---------------------------
13161 @end example
13162 @end itemize
13163 @end table
13165 @geindex -gnatyC (gcc)
13168 @table @asis
13170 @item @code{-gnatyC}
13172 @emph{Check comments, single space.}
13174 This is identical to @cite{c} except that only one space
13175 is required following the @cite{--} of a comment instead of two.
13176 @end table
13178 @geindex -gnatyd (gcc)
13181 @table @asis
13183 @item @code{-gnatyd}
13185 @emph{Check no DOS line terminators present.}
13187 All lines must be terminated by a single ASCII.LF
13188 character (in particular the DOS line terminator sequence CR/LF is not
13189 allowed).
13190 @end table
13192 @geindex -gnatye (gcc)
13195 @table @asis
13197 @item @code{-gnatye}
13199 @emph{Check end/exit labels.}
13201 Optional labels on @cite{end} statements ending subprograms and on
13202 @cite{exit} statements exiting named loops, are required to be present.
13203 @end table
13205 @geindex -gnatyf (gcc)
13208 @table @asis
13210 @item @code{-gnatyf}
13212 @emph{No form feeds or vertical tabs.}
13214 Neither form feeds nor vertical tab characters are permitted
13215 in the source text.
13216 @end table
13218 @geindex -gnatyg (gcc)
13221 @table @asis
13223 @item @code{-gnatyg}
13225 @emph{GNAT style mode.}
13227 The set of style check switches is set to match that used by the GNAT sources.
13228 This may be useful when developing code that is eventually intended to be
13229 incorporated into GNAT. Currently this is equivalent to @emph{-gnatwydISux})
13230 but additional style switches may be added to this set in the future without
13231 advance notice.
13232 @end table
13234 @geindex -gnatyh (gcc)
13237 @table @asis
13239 @item @code{-gnatyh}
13241 @emph{No horizontal tabs.}
13243 Horizontal tab characters are not permitted in the source text.
13244 Together with the b (no blanks at end of line) check, this
13245 enforces a canonical form for the use of blanks to separate
13246 source tokens.
13247 @end table
13249 @geindex -gnatyi (gcc)
13252 @table @asis
13254 @item @code{-gnatyi}
13256 @emph{Check if-then layout.}
13258 The keyword @cite{then} must appear either on the same
13259 line as corresponding @cite{if}, or on a line on its own, lined
13260 up under the @cite{if}.
13261 @end table
13263 @geindex -gnatyI (gcc)
13266 @table @asis
13268 @item @code{-gnatyI}
13270 @emph{check mode IN keywords.}
13272 Mode @cite{in} (the default mode) is not
13273 allowed to be given explicitly. @cite{in out} is fine,
13274 but not @cite{in} on its own.
13275 @end table
13277 @geindex -gnatyk (gcc)
13280 @table @asis
13282 @item @code{-gnatyk}
13284 @emph{Check keyword casing.}
13286 All keywords must be in lower case (with the exception of keywords
13287 such as @cite{digits} used as attribute names to which this check
13288 does not apply).
13289 @end table
13291 @geindex -gnatyl (gcc)
13294 @table @asis
13296 @item @code{-gnatyl}
13298 @emph{Check layout.}
13300 Layout of statement and declaration constructs must follow the
13301 recommendations in the Ada Reference Manual, as indicated by the
13302 form of the syntax rules. For example an @cite{else} keyword must
13303 be lined up with the corresponding @cite{if} keyword.
13305 There are two respects in which the style rule enforced by this check
13306 option are more liberal than those in the Ada Reference Manual. First
13307 in the case of record declarations, it is permissible to put the
13308 @cite{record} keyword on the same line as the @cite{type} keyword, and
13309 then the @cite{end} in @cite{end record} must line up under @cite{type}.
13310 This is also permitted when the type declaration is split on two lines.
13311 For example, any of the following three layouts is acceptable:
13313 @example
13314 type q is record
13315    a : integer;
13316    b : integer;
13317 end record;
13319 type q is
13320    record
13321       a : integer;
13322       b : integer;
13323    end record;
13325 type q is
13326    record
13327       a : integer;
13328       b : integer;
13329 end record;
13330 @end example
13332 Second, in the case of a block statement, a permitted alternative
13333 is to put the block label on the same line as the @cite{declare} or
13334 @cite{begin} keyword, and then line the @cite{end} keyword up under
13335 the block label. For example both the following are permitted:
13337 @example
13338 Block : declare
13339    A : Integer := 3;
13340 begin
13341    Proc (A, A);
13342 end Block;
13344 Block :
13345    declare
13346       A : Integer := 3;
13347    begin
13348       Proc (A, A);
13349    end Block;
13350 @end example
13352 The same alternative format is allowed for loops. For example, both of
13353 the following are permitted:
13355 @example
13356 Clear : while J < 10 loop
13357    A (J) := 0;
13358 end loop Clear;
13360 Clear :
13361    while J < 10 loop
13362       A (J) := 0;
13363    end loop Clear;
13364 @end example
13365 @end table
13367 @geindex -gnatyLnnn (gcc)
13370 @table @asis
13372 @item @code{-gnatyL}
13374 @emph{Set maximum nesting level.}
13376 The maximum level of nesting of constructs (including subprograms, loops,
13377 blocks, packages, and conditionals) may not exceed the given value
13378 @emph{nnn}. A value of zero disconnects this style check.
13379 @end table
13381 @geindex -gnatym (gcc)
13384 @table @asis
13386 @item @code{-gnatym}
13388 @emph{Check maximum line length.}
13390 The length of source lines must not exceed 79 characters, including
13391 any trailing blanks. The value of 79 allows convenient display on an
13392 80 character wide device or window, allowing for possible special
13393 treatment of 80 character lines. Note that this count is of
13394 characters in the source text. This means that a tab character counts
13395 as one character in this count and a wide character sequence counts as
13396 a single character (however many bytes are needed in the encoding).
13397 @end table
13399 @geindex -gnatyMnnn (gcc)
13402 @table @asis
13404 @item @code{-gnatyM}
13406 @emph{Set maximum line length.}
13408 The length of lines must not exceed the
13409 given value @emph{nnn}. The maximum value that can be specified is 32767.
13410 If neither style option for setting the line length is used, then the
13411 default is 255. This also controls the maximum length of lexical elements,
13412 where the only restriction is that they must fit on a single line.
13413 @end table
13415 @geindex -gnatyn (gcc)
13418 @table @asis
13420 @item @code{-gnatyn}
13422 @emph{Check casing of entities in Standard.}
13424 Any identifier from Standard must be cased
13425 to match the presentation in the Ada Reference Manual (for example,
13426 @cite{Integer} and @cite{ASCII.NUL}).
13427 @end table
13429 @geindex -gnatyN (gcc)
13432 @table @asis
13434 @item @code{-gnatyN}
13436 @emph{Turn off all style checks.}
13438 All style check options are turned off.
13439 @end table
13441 @geindex -gnatyo (gcc)
13444 @table @asis
13446 @item @code{-gnatyo}
13448 @emph{Check order of subprogram bodies.}
13450 All subprogram bodies in a given scope
13451 (e.g., a package body) must be in alphabetical order. The ordering
13452 rule uses normal Ada rules for comparing strings, ignoring casing
13453 of letters, except that if there is a trailing numeric suffix, then
13454 the value of this suffix is used in the ordering (e.g., Junk2 comes
13455 before Junk10).
13456 @end table
13458 @geindex -gnatyO (gcc)
13461 @table @asis
13463 @item @code{-gnatyO}
13465 @emph{Check that overriding subprograms are explicitly marked as such.}
13467 This applies to all subprograms of a derived type that override a primitive
13468 operation of the type, for both tagged and untagged types. In particular,
13469 the declaration of a primitive operation of a type extension that overrides
13470 an inherited operation must carry an overriding indicator. Another case is
13471 the declaration of a function that overrides a predefined operator (such
13472 as an equality operator).
13473 @end table
13475 @geindex -gnatyp (gcc)
13478 @table @asis
13480 @item @code{-gnatyp}
13482 @emph{Check pragma casing.}
13484 Pragma names must be written in mixed case, that is, the
13485 initial letter and any letter following an underscore must be uppercase.
13486 All other letters must be lowercase. An exception is that SPARK_Mode is
13487 allowed as an alternative for Spark_Mode.
13488 @end table
13490 @geindex -gnatyr (gcc)
13493 @table @asis
13495 @item @code{-gnatyr}
13497 @emph{Check references.}
13499 All identifier references must be cased in the same way as the
13500 corresponding declaration. No specific casing style is imposed on
13501 identifiers. The only requirement is for consistency of references
13502 with declarations.
13503 @end table
13505 @geindex -gnatys (gcc)
13508 @table @asis
13510 @item @code{-gnatys}
13512 @emph{Check separate specs.}
13514 Separate declarations ('specs') are required for subprograms (a
13515 body is not allowed to serve as its own declaration). The only
13516 exception is that parameterless library level procedures are
13517 not required to have a separate declaration. This exception covers
13518 the most frequent form of main program procedures.
13519 @end table
13521 @geindex -gnatyS (gcc)
13524 @table @asis
13526 @item @code{-gnatyS}
13528 @emph{Check no statements after then/else.}
13530 No statements are allowed
13531 on the same line as a @cite{then} or @cite{else} keyword following the
13532 keyword in an @cite{if} statement. @cite{or else} and @cite{and then} are not
13533 affected, and a special exception allows a pragma to appear after @cite{else}.
13534 @end table
13536 @geindex -gnatyt (gcc)
13539 @table @asis
13541 @item @code{-gnatyt}
13543 @emph{Check token spacing.}
13545 The following token spacing rules are enforced:
13548 @itemize *
13550 @item 
13551 The keywords @cite{abs} and @cite{not} must be followed by a space.
13553 @item 
13554 The token @cite{=>} must be surrounded by spaces.
13556 @item 
13557 The token @cite{<>} must be preceded by a space or a left parenthesis.
13559 @item 
13560 Binary operators other than @cite{**} must be surrounded by spaces.
13561 There is no restriction on the layout of the @cite{**} binary operator.
13563 @item 
13564 Colon must be surrounded by spaces.
13566 @item 
13567 Colon-equal (assignment, initialization) must be surrounded by spaces.
13569 @item 
13570 Comma must be the first non-blank character on the line, or be
13571 immediately preceded by a non-blank character, and must be followed
13572 by a space.
13574 @item 
13575 If the token preceding a left parenthesis ends with a letter or digit, then
13576 a space must separate the two tokens.
13578 @item 
13579 If the token following a right parenthesis starts with a letter or digit, then
13580 a space must separate the two tokens.
13582 @item 
13583 A right parenthesis must either be the first non-blank character on
13584 a line, or it must be preceded by a non-blank character.
13586 @item 
13587 A semicolon must not be preceded by a space, and must not be followed by
13588 a non-blank character.
13590 @item 
13591 A unary plus or minus may not be followed by a space.
13593 @item 
13594 A vertical bar must be surrounded by spaces.
13595 @end itemize
13597 Exactly one blank (and no other white space) must appear between
13598 a @cite{not} token and a following @cite{in} token.
13599 @end table
13601 @geindex -gnatyu (gcc)
13604 @table @asis
13606 @item @code{-gnatyu}
13608 @emph{Check unnecessary blank lines.}
13610 Unnecessary blank lines are not allowed. A blank line is considered
13611 unnecessary if it appears at the end of the file, or if more than
13612 one blank line occurs in sequence.
13613 @end table
13615 @geindex -gnatyx (gcc)
13618 @table @asis
13620 @item @code{-gnatyx}
13622 @emph{Check extra parentheses.}
13624 Unnecessary extra level of parentheses (C-style) are not allowed
13625 around conditions in @cite{if} statements, @cite{while} statements and
13626 @cite{exit} statements.
13627 @end table
13629 @geindex -gnatyy (gcc)
13632 @table @asis
13634 @item @code{-gnatyy}
13636 @emph{Set all standard style check options.}
13638 This is equivalent to @cite{gnaty3aAbcefhiklmnprst}, that is all checking
13639 options enabled with the exception of @emph{-gnatyB}, @emph{-gnatyd},
13640 @emph{-gnatyI}, @emph{-gnatyLnnn}, @emph{-gnatyo}, @emph{-gnatyO},
13641 @emph{-gnatyS}, @emph{-gnatyu}, and @emph{-gnatyx}.
13642 @end table
13644 @geindex -gnaty- (gcc)
13647 @table @asis
13649 @item @code{-gnaty-}
13651 @emph{Remove style check options.}
13653 This causes any subsequent options in the string to act as canceling the
13654 corresponding style check option. To cancel maximum nesting level control,
13655 use @emph{L} parameter witout any integer value after that, because any
13656 digit following @emph{-} in the parameter string of the @emph{-gnaty}
13657 option will be threated as canceling indentation check. The same is true
13658 for @emph{M} parameter. @emph{y} and @emph{N} parameters are not
13659 allowed after @emph{-}.
13660 @end table
13662 @geindex -gnaty+ (gcc)
13665 @table @asis
13667 @item @code{-gnaty+}
13669 @emph{Enable style check options.}
13671 This causes any subsequent options in the string to enable the corresponding
13672 style check option. That is, it cancels the effect of a previous -,
13673 if any.
13674 @end table
13676 @c end of switch description (leave this comment to ease automatic parsing for
13678 @c GPS
13680 In the above rules, appearing in column one is always permitted, that is,
13681 counts as meeting either a requirement for a required preceding space,
13682 or as meeting a requirement for no preceding space.
13684 Appearing at the end of a line is also always permitted, that is, counts
13685 as meeting either a requirement for a following space, or as meeting
13686 a requirement for no following space.
13688 If any of these style rules is violated, a message is generated giving
13689 details on the violation. The initial characters of such messages are
13690 always '@cite{(style)}'. Note that these messages are treated as warning
13691 messages, so they normally do not prevent the generation of an object
13692 file. The @emph{-gnatwe} switch can be used to treat warning messages,
13693 including style messages, as fatal errors.
13695 The switch @code{-gnaty} on its own (that is not
13696 followed by any letters or digits) is equivalent
13697 to the use of @emph{-gnatyy} as described above, that is all
13698 built-in standard style check options are enabled.
13700 The switch @code{-gnatyN} clears any previously set style checks.
13702 @node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
13703 @anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{f9}@anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{104}
13704 @subsection Run-Time Checks
13707 @geindex Division by zero
13709 @geindex Access before elaboration
13711 @geindex Checks
13712 @geindex division by zero
13714 @geindex Checks
13715 @geindex access before elaboration
13717 @geindex Checks
13718 @geindex stack overflow checking
13720 By default, the following checks are suppressed: stack overflow
13721 checks, and checks for access before elaboration on subprogram
13722 calls. All other checks, including overflow checks, range checks and
13723 array bounds checks, are turned on by default. The following @emph{gcc}
13724 switches refine this default behavior.
13726 @geindex -gnatp (gcc)
13729 @table @asis
13731 @item @code{-gnatp}
13733 @geindex Suppressing checks
13735 @geindex Checks
13736 @geindex suppressing
13738 This switch causes the unit to be compiled
13739 as though @cite{pragma Suppress (All_checks)}
13740 had been present in the source. Validity checks are also eliminated (in
13741 other words @emph{-gnatp} also implies @emph{-gnatVn}.
13742 Use this switch to improve the performance
13743 of the code at the expense of safety in the presence of invalid data or
13744 program bugs.
13746 Note that when checks are suppressed, the compiler is allowed, but not
13747 required, to omit the checking code. If the run-time cost of the
13748 checking code is zero or near-zero, the compiler will generate it even
13749 if checks are suppressed. In particular, if the compiler can prove
13750 that a certain check will necessarily fail, it will generate code to
13751 do an unconditional 'raise', even if checks are suppressed. The
13752 compiler warns in this case. Another case in which checks may not be
13753 eliminated is when they are embedded in certain run time routines such
13754 as math library routines.
13756 Of course, run-time checks are omitted whenever the compiler can prove
13757 that they will not fail, whether or not checks are suppressed.
13759 Note that if you suppress a check that would have failed, program
13760 execution is erroneous, which means the behavior is totally
13761 unpredictable. The program might crash, or print wrong answers, or
13762 do anything else. It might even do exactly what you wanted it to do
13763 (and then it might start failing mysteriously next week or next
13764 year). The compiler will generate code based on the assumption that
13765 the condition being checked is true, which can result in erroneous
13766 execution if that assumption is wrong.
13768 The checks subject to suppression include all the checks defined by the Ada
13769 standard, the additional implementation defined checks @cite{Alignment_Check},
13770 @cite{Duplicated_Tag_Check}, @cite{Predicate_Check}, Container_Checks, Tampering_Check,
13771 and @cite{Validity_Check}, as well as any checks introduced using @cite{pragma Check_Name}. Note that @cite{Atomic_Synchronization} is not automatically
13772 suppressed by use of this option.
13774 If the code depends on certain checks being active, you can use
13775 pragma @cite{Unsuppress} either as a configuration pragma or as
13776 a local pragma to make sure that a specified check is performed
13777 even if @emph{gnatp} is specified.
13779 The @emph{-gnatp} switch has no effect if a subsequent
13780 @emph{-gnat-p} switch appears.
13781 @end table
13783 @geindex -gnat-p (gcc)
13785 @geindex Suppressing checks
13787 @geindex Checks
13788 @geindex suppressing
13790 @geindex Suppress
13793 @table @asis
13795 @item @code{-gnat-p}
13797 This switch cancels the effect of a previous @emph{gnatp} switch.
13798 @end table
13800 @geindex -gnato?? (gcc)
13802 @geindex Overflow checks
13804 @geindex Overflow mode
13806 @geindex Check
13807 @geindex overflow
13810 @table @asis
13812 @item @code{-gnato??}
13814 This switch controls the mode used for computing intermediate
13815 arithmetic integer operations, and also enables overflow checking.
13816 For a full description of overflow mode and checking control, see
13817 the 'Overflow Check Handling in GNAT' appendix in this
13818 User's Guide.
13820 Overflow checks are always enabled by this switch. The argument
13821 controls the mode, using the codes
13824 @table @asis
13826 @item @emph{1 = STRICT}
13828 In STRICT mode, intermediate operations are always done using the
13829 base type, and overflow checking ensures that the result is within
13830 the base type range.
13832 @item @emph{2 = MINIMIZED}
13834 In MINIMIZED mode, overflows in intermediate operations are avoided
13835 where possible by using a larger integer type for the computation
13836 (typically @cite{Long_Long_Integer}). Overflow checking ensures that
13837 the result fits in this larger integer type.
13839 @item @emph{3 = ELIMINATED}
13841 In ELIMINATED mode, overflows in intermediate operations are avoided
13842 by using multi-precision arithmetic. In this case, overflow checking
13843 has no effect on intermediate operations (since overflow is impossible).
13844 @end table
13846 If two digits are present after @emph{-gnato} then the first digit
13847 sets the mode for expressions outside assertions, and the second digit
13848 sets the mode for expressions within assertions. Here assertions is used
13849 in the technical sense (which includes for example precondition and
13850 postcondition expressions).
13852 If one digit is present, the corresponding mode is applicable to both
13853 expressions within and outside assertion expressions.
13855 If no digits are present, the default is to enable overflow checks
13856 and set STRICT mode for both kinds of expressions. This is compatible
13857 with the use of @emph{-gnato} in previous versions of GNAT.
13859 @geindex Machine_Overflows
13861 Note that the @emph{-gnato??} switch does not affect the code generated
13862 for any floating-point operations; it applies only to integer semantics.
13863 For floating-point, GNAT has the @cite{Machine_Overflows}
13864 attribute set to @cite{False} and the normal mode of operation is to
13865 generate IEEE NaN and infinite values on overflow or invalid operations
13866 (such as dividing 0.0 by 0.0).
13868 The reason that we distinguish overflow checking from other kinds of
13869 range constraint checking is that a failure of an overflow check, unlike
13870 for example the failure of a range check, can result in an incorrect
13871 value, but cannot cause random memory destruction (like an out of range
13872 subscript), or a wild jump (from an out of range case value). Overflow
13873 checking is also quite expensive in time and space, since in general it
13874 requires the use of double length arithmetic.
13876 Note again that the default is @emph{-gnato11} (equivalent to @emph{-gnato1}),
13877 so overflow checking is performed in STRICT mode by default.
13878 @end table
13880 @geindex -gnatE (gcc)
13882 @geindex Elaboration checks
13884 @geindex Check
13885 @geindex elaboration
13888 @table @asis
13890 @item @code{-gnatE}
13892 Enables dynamic checks for access-before-elaboration
13893 on subprogram calls and generic instantiations.
13894 Note that @emph{-gnatE} is not necessary for safety, because in the
13895 default mode, GNAT ensures statically that the checks would not fail.
13896 For full details of the effect and use of this switch,
13897 @ref{1c,,Compiling with gcc}.
13898 @end table
13900 @geindex -fstack-check (gcc)
13902 @geindex Stack Overflow Checking
13904 @geindex Checks
13905 @geindex stack overflow checking
13908 @table @asis
13910 @item @code{-fstack-check}
13912 Activates stack overflow checking. For full details of the effect and use of
13913 this switch see @ref{f4,,Stack Overflow Checking}.
13914 @end table
13916 @geindex Unsuppress
13918 The setting of these switches only controls the default setting of the
13919 checks. You may modify them using either @cite{Suppress} (to remove
13920 checks) or @cite{Unsuppress} (to add back suppressed checks) pragmas in
13921 the program source.
13923 @node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
13924 @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}
13925 @subsection Using @emph{gcc} for Syntax Checking
13928 @geindex -gnats (gcc)
13931 @table @asis
13933 @item @code{-gnats}
13935 The @cite{s} stands for 'syntax'.
13937 Run GNAT in syntax checking only mode. For
13938 example, the command
13940 @example
13941 $ gcc -c -gnats x.adb
13942 @end example
13944 compiles file @code{x.adb} in syntax-check-only mode. You can check a
13945 series of files in a single command
13946 , and can use wild cards to specify such a group of files.
13947 Note that you must specify the @emph{-c} (compile
13948 only) flag in addition to the @emph{-gnats} flag.
13950 You may use other switches in conjunction with @emph{-gnats}. In
13951 particular, @emph{-gnatl} and @emph{-gnatv} are useful to control the
13952 format of any generated error messages.
13954 When the source file is empty or contains only empty lines and/or comments,
13955 the output is a warning:
13957 @example
13958 $ gcc -c -gnats -x ada toto.txt
13959 toto.txt:1:01: warning: empty file, contains no compilation units
13961 @end example
13963 Otherwise, the output is simply the error messages, if any. No object file or
13964 ALI file is generated by a syntax-only compilation. Also, no units other
13965 than the one specified are accessed. For example, if a unit @cite{X}
13966 @emph{with}s a unit @cite{Y}, compiling unit @cite{X} in syntax
13967 check only mode does not access the source file containing unit
13968 @cite{Y}.
13970 @geindex Multiple units
13971 @geindex syntax checking
13973 Normally, GNAT allows only a single unit in a source file. However, this
13974 restriction does not apply in syntax-check-only mode, and it is possible
13975 to check a file containing multiple compilation units concatenated
13976 together. This is primarily used by the @cite{gnatchop} utility
13977 (@ref{36,,Renaming Files with gnatchop}).
13978 @end table
13980 @node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
13981 @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}
13982 @subsection Using @emph{gcc} for Semantic Checking
13985 @geindex -gnatc (gcc)
13988 @table @asis
13990 @item @code{-gnatc}
13992 The @cite{c} stands for 'check'.
13993 Causes the compiler to operate in semantic check mode,
13994 with full checking for all illegalities specified in the
13995 Ada Reference Manual, but without generation of any object code
13996 (no object file is generated).
13998 Because dependent files must be accessed, you must follow the GNAT
13999 semantic restrictions on file structuring to operate in this mode:
14002 @itemize *
14004 @item 
14005 The needed source files must be accessible
14006 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
14008 @item 
14009 Each file must contain only one compilation unit.
14011 @item 
14012 The file name and unit name must match (@ref{52,,File Naming Rules}).
14013 @end itemize
14015 The output consists of error messages as appropriate. No object file is
14016 generated. An @code{ALI} file is generated for use in the context of
14017 cross-reference tools, but this file is marked as not being suitable
14018 for binding (since no object file is generated).
14019 The checking corresponds exactly to the notion of
14020 legality in the Ada Reference Manual.
14022 Any unit can be compiled in semantics-checking-only mode, including
14023 units that would not normally be compiled (subunits,
14024 and specifications where a separate body is present).
14025 @end table
14027 @node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
14028 @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}
14029 @subsection Compiling Different Versions of Ada
14032 The switches described in this section allow you to explicitly specify
14033 the version of the Ada language that your programs are written in.
14034 The default mode is Ada 2012,
14035 but you can also specify Ada 95, Ada 2005 mode, or
14036 indicate Ada 83 compatibility mode.
14038 @geindex Compatibility with Ada 83
14040 @geindex -gnat83 (gcc)
14042 @geindex ACVC
14043 @geindex Ada 83 tests
14045 @geindex Ada 83 mode
14048 @table @asis
14050 @item @code{-gnat83} (Ada 83 Compatibility Mode)
14052 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
14053 specifies that the program is to be compiled in Ada 83 mode. With
14054 @emph{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
14055 semantics where this can be done easily.
14056 It is not possible to guarantee this switch does a perfect
14057 job; some subtle tests, such as are
14058 found in earlier ACVC tests (and that have been removed from the ACATS suite
14059 for Ada 95), might not compile correctly.
14060 Nevertheless, this switch may be useful in some circumstances, for example
14061 where, due to contractual reasons, existing code needs to be maintained
14062 using only Ada 83 features.
14064 With few exceptions (most notably the need to use @cite{<>} on
14065 unconstrained 
14066 @geindex Generic formal parameters
14067 generic formal parameters,
14068 the use of the new Ada 95 / Ada 2005
14069 reserved words, and the use of packages
14070 with optional bodies), it is not necessary to specify the
14071 @emph{-gnat83} switch when compiling Ada 83 programs, because, with rare
14072 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
14073 a correct Ada 83 program is usually also a correct program
14074 in these later versions of the language standard. For further information
14075 please refer to the @cite{Compatibility_and_Porting_Guide} chapter in the
14076 @cite{GNAT Reference Manual}.
14077 @end table
14079 @geindex -gnat95 (gcc)
14081 @geindex Ada 95 mode
14084 @table @asis
14086 @item @code{-gnat95} (Ada 95 mode)
14088 This switch directs the compiler to implement the Ada 95 version of the
14089 language.
14090 Since Ada 95 is almost completely upwards
14091 compatible with Ada 83, Ada 83 programs may generally be compiled using
14092 this switch (see the description of the @emph{-gnat83} switch for further
14093 information about Ada 83 mode).
14094 If an Ada 2005 program is compiled in Ada 95 mode,
14095 uses of the new Ada 2005 features will cause error
14096 messages or warnings.
14098 This switch also can be used to cancel the effect of a previous
14099 @emph{-gnat83}, @emph{-gnat05/2005}, or @emph{-gnat12/2012}
14100 switch earlier in the command line.
14101 @end table
14103 @geindex -gnat05 (gcc)
14105 @geindex -gnat2005 (gcc)
14107 @geindex Ada 2005 mode
14110 @table @asis
14112 @item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
14114 This switch directs the compiler to implement the Ada 2005 version of the
14115 language, as documented in the official Ada standards document.
14116 Since Ada 2005 is almost completely upwards
14117 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
14118 may generally be compiled using this switch (see the description of the
14119 @emph{-gnat83} and @emph{-gnat95} switches for further
14120 information).
14121 @end table
14123 @geindex -gnat12 (gcc)
14125 @geindex -gnat2012 (gcc)
14127 @geindex Ada 2012 mode
14130 @table @asis
14132 @item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
14134 This switch directs the compiler to implement the Ada 2012 version of the
14135 language (also the default).
14136 Since Ada 2012 is almost completely upwards
14137 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
14138 Ada 83 and Ada 95 programs
14139 may generally be compiled using this switch (see the description of the
14140 @emph{-gnat83}, @emph{-gnat95}, and @emph{-gnat05/2005} switches
14141 for further information).
14142 @end table
14144 @geindex -gnatX (gcc)
14146 @geindex Ada language extensions
14148 @geindex GNAT extensions
14151 @table @asis
14153 @item @code{-gnatX} (Enable GNAT Extensions)
14155 This switch directs the compiler to implement the latest version of the
14156 language (currently Ada 2012) and also to enable certain GNAT implementation
14157 extensions that are not part of any Ada standard. For a full list of these
14158 extensions, see the GNAT reference manual.
14159 @end table
14161 @node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14162 @anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{10a}@anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{48}
14163 @subsection Character Set Control
14166 @geindex -gnati (gcc)
14169 @table @asis
14171 @item @code{-gnati@emph{c}}
14173 Normally GNAT recognizes the Latin-1 character set in source program
14174 identifiers, as described in the Ada Reference Manual.
14175 This switch causes
14176 GNAT to recognize alternate character sets in identifiers. @cite{c} is a
14177 single character  indicating the character set, as follows:
14180 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14181 @item
14183 @emph{1}
14185 @tab
14187 ISO 8859-1 (Latin-1) identifiers
14189 @item
14191 @emph{2}
14193 @tab
14195 ISO 8859-2 (Latin-2) letters allowed in identifiers
14197 @item
14199 @emph{3}
14201 @tab
14203 ISO 8859-3 (Latin-3) letters allowed in identifiers
14205 @item
14207 @emph{4}
14209 @tab
14211 ISO 8859-4 (Latin-4) letters allowed in identifiers
14213 @item
14215 @emph{5}
14217 @tab
14219 ISO 8859-5 (Cyrillic) letters allowed in identifiers
14221 @item
14223 @emph{9}
14225 @tab
14227 ISO 8859-15 (Latin-9) letters allowed in identifiers
14229 @item
14231 @emph{p}
14233 @tab
14235 IBM PC letters (code page 437) allowed in identifiers
14237 @item
14239 @emph{8}
14241 @tab
14243 IBM PC letters (code page 850) allowed in identifiers
14245 @item
14247 @emph{f}
14249 @tab
14251 Full upper-half codes allowed in identifiers
14253 @item
14255 @emph{n}
14257 @tab
14259 No upper-half codes allowed in identifiers
14261 @item
14263 @emph{w}
14265 @tab
14267 Wide-character codes (that is, codes greater than 255)
14268 allowed in identifiers
14270 @end multitable
14273 See @ref{3e,,Foreign Language Representation} for full details on the
14274 implementation of these character sets.
14275 @end table
14277 @geindex -gnatW (gcc)
14280 @table @asis
14282 @item @code{-gnatW@emph{e}}
14284 Specify the method of encoding for wide characters.
14285 @cite{e} is one of the following:
14288 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14289 @item
14291 @emph{h}
14293 @tab
14295 Hex encoding (brackets coding also recognized)
14297 @item
14299 @emph{u}
14301 @tab
14303 Upper half encoding (brackets encoding also recognized)
14305 @item
14307 @emph{s}
14309 @tab
14311 Shift/JIS encoding (brackets encoding also recognized)
14313 @item
14315 @emph{e}
14317 @tab
14319 EUC encoding (brackets encoding also recognized)
14321 @item
14323 @emph{8}
14325 @tab
14327 UTF-8 encoding (brackets encoding also recognized)
14329 @item
14331 @emph{b}
14333 @tab
14335 Brackets encoding only (default value)
14337 @end multitable
14340 For full details on these encoding
14341 methods see @ref{4e,,Wide_Character Encodings}.
14342 Note that brackets coding is always accepted, even if one of the other
14343 options is specified, so for example @emph{-gnatW8} specifies that both
14344 brackets and UTF-8 encodings will be recognized. The units that are
14345 with'ed directly or indirectly will be scanned using the specified
14346 representation scheme, and so if one of the non-brackets scheme is
14347 used, it must be used consistently throughout the program. However,
14348 since brackets encoding is always recognized, it may be conveniently
14349 used in standard libraries, allowing these libraries to be used with
14350 any of the available coding schemes.
14352 Note that brackets encoding only applies to program text. Within comments,
14353 brackets are considered to be normal graphic characters, and bracket sequences
14354 are never recognized as wide characters.
14356 If no @emph{-gnatW?} parameter is present, then the default
14357 representation is normally Brackets encoding only. However, if the
14358 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14359 byte order mark or BOM for UTF-8), then these three characters are
14360 skipped and the default representation for the file is set to UTF-8.
14362 Note that the wide character representation that is specified (explicitly
14363 or by default) for the main program also acts as the default encoding used
14364 for Wide_Text_IO files if not specifically overridden by a WCEM form
14365 parameter.
14366 @end table
14368 When no @emph{-gnatW?} is specified, then characters (other than wide
14369 characters represented using brackets notation) are treated as 8-bit
14370 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14371 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14372 characters in the range 16#00#..16#1F# are not accepted in program text
14373 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14374 in program text, but allowed and ignored in comments. Note in particular
14375 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14376 as an end of line in this default mode. If your source program contains
14377 instances of the NEL character used as a line terminator,
14378 you must use UTF-8 encoding for the whole
14379 source program. In default mode, all lines must be ended by a standard
14380 end of line sequence (CR, CR/LF, or LF).
14382 Note that the convention of simply accepting all upper half characters in
14383 comments means that programs that use standard ASCII for program text, but
14384 UTF-8 encoding for comments are accepted in default mode, providing that the
14385 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14386 This is a common mode for many programs with foreign language comments.
14388 @node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14389 @anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{10b}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{10c}
14390 @subsection File Naming Control
14393 @geindex -gnatk (gcc)
14396 @table @asis
14398 @item @code{-gnatk@emph{n}}
14400 Activates file name 'krunching'. @cite{n}, a decimal integer in the range
14401 1-999, indicates the maximum allowable length of a file name (not
14402 including the @code{.ads} or @code{.adb} extension). The default is not
14403 to enable file name krunching.
14405 For the source file naming rules, @ref{52,,File Naming Rules}.
14406 @end table
14408 @node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14409 @anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{10d}@anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{10e}
14410 @subsection Subprogram Inlining Control
14413 @geindex -gnatn (gcc)
14416 @table @asis
14418 @item @code{-gnatn[12]}
14420 The @cite{n} here is intended to suggest the first syllable of the
14421 word 'inline'.
14422 GNAT recognizes and processes @cite{Inline} pragmas. However, for the
14423 inlining to actually occur, optimization must be enabled and, in order
14424 to enable inlining of subprograms specified by pragma @cite{Inline},
14425 you must also specify this switch.
14426 In the absence of this switch, GNAT does not attempt
14427 inlining and does not need to access the bodies of
14428 subprograms for which @cite{pragma Inline} is specified if they are not
14429 in the current unit.
14431 You can optionally specify the inlining level: 1 for moderate inlining across
14432 modules, which is a good compromise between compilation times and performances
14433 at run time, or 2 for full inlining across modules, which may bring about
14434 longer compilation times. If no inlining level is specified, the compiler will
14435 pick it based on the optimization level: 1 for @emph{-O1}, @emph{-O2} or
14436 @emph{-Os} and 2 for @emph{-O3}.
14438 If you specify this switch the compiler will access these bodies,
14439 creating an extra source dependency for the resulting object file, and
14440 where possible, the call will be inlined.
14441 For further details on when inlining is possible
14442 see @ref{10f,,Inlining of Subprograms}.
14443 @end table
14445 @geindex -gnatN (gcc)
14448 @table @asis
14450 @item @code{-gnatN}
14452 This switch activates front-end inlining which also
14453 generates additional dependencies.
14455 When using a gcc-based back end (in practice this means using any version
14456 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
14457 @emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
14458 Historically front end inlining was more extensive than the gcc back end
14459 inlining, but that is no longer the case.
14460 @end table
14462 @node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14463 @anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{110}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{111}
14464 @subsection Auxiliary Output Control
14467 @geindex -gnatt (gcc)
14469 @geindex Writing internal trees
14471 @geindex Internal trees
14472 @geindex writing to file
14475 @table @asis
14477 @item @code{-gnatt}
14479 Causes GNAT to write the internal tree for a unit to a file (with the
14480 extension @code{.adt}.
14481 This not normally required, but is used by separate analysis tools.
14482 Typically
14483 these tools do the necessary compilations automatically, so you should
14484 not have to specify this switch in normal operation.
14485 Note that the combination of switches @emph{-gnatct}
14486 generates a tree in the form required by ASIS applications.
14487 @end table
14489 @geindex -gnatu (gcc)
14492 @table @asis
14494 @item @code{-gnatu}
14496 Print a list of units required by this compilation on @code{stdout}.
14497 The listing includes all units on which the unit being compiled depends
14498 either directly or indirectly.
14499 @end table
14501 @geindex -pass-exit-codes (gcc)
14504 @table @asis
14506 @item @code{-pass-exit-codes}
14508 If this switch is not used, the exit code returned by @emph{gcc} when
14509 compiling multiple files indicates whether all source files have
14510 been successfully used to generate object files or not.
14512 When @emph{-pass-exit-codes} is used, @emph{gcc} exits with an extended
14513 exit status and allows an integrated development environment to better
14514 react to a compilation failure. Those exit status are:
14517 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14518 @item
14520 @emph{5}
14522 @tab
14524 There was an error in at least one source file.
14526 @item
14528 @emph{3}
14530 @tab
14532 At least one source file did not generate an object file.
14534 @item
14536 @emph{2}
14538 @tab
14540 The compiler died unexpectedly (internal error for example).
14542 @item
14544 @emph{0}
14546 @tab
14548 An object file has been generated for every source file.
14550 @end multitable
14552 @end table
14554 @node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
14555 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{112}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{113}
14556 @subsection Debugging Control
14559 @quotation
14561 @geindex Debugging options
14562 @end quotation
14564 @geindex -gnatd (gcc)
14567 @table @asis
14569 @item @code{-gnatd@emph{x}}
14571 Activate internal debugging switches. @cite{x} is a letter or digit, or
14572 string of letters or digits, which specifies the type of debugging
14573 outputs desired. Normally these are used only for internal development
14574 or system debugging purposes. You can find full documentation for these
14575 switches in the body of the @cite{Debug} unit in the compiler source
14576 file @code{debug.adb}.
14577 @end table
14579 @geindex -gnatG (gcc)
14582 @table @asis
14584 @item @code{-gnatG[=@emph{nn}]}
14586 This switch causes the compiler to generate auxiliary output containing
14587 a pseudo-source listing of the generated expanded code. Like most Ada
14588 compilers, GNAT works by first transforming the high level Ada code into
14589 lower level constructs. For example, tasking operations are transformed
14590 into calls to the tasking run-time routines. A unique capability of GNAT
14591 is to list this expanded code in a form very close to normal Ada source.
14592 This is very useful in understanding the implications of various Ada
14593 usage on the efficiency of the generated code. There are many cases in
14594 Ada (e.g., the use of controlled types), where simple Ada statements can
14595 generate a lot of run-time code. By using @emph{-gnatG} you can identify
14596 these cases, and consider whether it may be desirable to modify the coding
14597 approach to improve efficiency.
14599 The optional parameter @cite{nn} if present after -gnatG specifies an
14600 alternative maximum line length that overrides the normal default of 72.
14601 This value is in the range 40-999999, values less than 40 being silently
14602 reset to 40. The equal sign is optional.
14604 The format of the output is very similar to standard Ada source, and is
14605 easily understood by an Ada programmer. The following special syntactic
14606 additions correspond to low level features used in the generated code that
14607 do not have any exact analogies in pure Ada source form. The following
14608 is a partial list of these special constructions. See the spec
14609 of package @cite{Sprint} in file @code{sprint.ads} for a full list.
14611 @geindex -gnatL (gcc)
14613 If the switch @emph{-gnatL} is used in conjunction with
14614 @emph{-gnatG}, then the original source lines are interspersed
14615 in the expanded source (as comment lines with the original line number).
14618 @table @asis
14620 @item @code{new @emph{xxx} [storage_pool = @emph{yyy}]}
14622 Shows the storage pool being used for an allocator.
14624 @item @code{at end @emph{procedure-name};}
14626 Shows the finalization (cleanup) procedure for a scope.
14628 @item @code{(if @emph{expr} then @emph{expr} else @emph{expr})}
14630 Conditional expression equivalent to the @cite{x?y:z} construction in C.
14632 @item @code{@emph{target}^(@emph{source})}
14634 A conversion with floating-point truncation instead of rounding.
14636 @item @code{@emph{target}?(@emph{source})}
14638 A conversion that bypasses normal Ada semantic checking. In particular
14639 enumeration types and fixed-point types are treated simply as integers.
14641 @item @code{@emph{target}?^(@emph{source})}
14643 Combines the above two cases.
14644 @end table
14646 @code{@emph{x} #/ @emph{y}}
14648 @code{@emph{x} #mod @emph{y}}
14650 @code{@emph{x} # @emph{y}}
14653 @table @asis
14655 @item @code{@emph{x} #rem @emph{y}}
14657 A division or multiplication of fixed-point values which are treated as
14658 integers without any kind of scaling.
14660 @item @code{free @emph{expr} [storage_pool = @emph{xxx}]}
14662 Shows the storage pool associated with a @cite{free} statement.
14664 @item @code{[subtype or type declaration]}
14666 Used to list an equivalent declaration for an internally generated
14667 type that is referenced elsewhere in the listing.
14669 @item @code{freeze @emph{type-name} [@emph{actions}]}
14671 Shows the point at which @cite{type-name} is frozen, with possible
14672 associated actions to be performed at the freeze point.
14674 @item @code{reference @emph{itype}}
14676 Reference (and hence definition) to internal type @cite{itype}.
14678 @item @code{@emph{function-name}! (@emph{arg}, @emph{arg}, @emph{arg})}
14680 Intrinsic function call.
14682 @item @code{@emph{label-name} : label}
14684 Declaration of label @cite{labelname}.
14686 @item @code{#$ @emph{subprogram-name}}
14688 An implicit call to a run-time support routine
14689 (to meet the requirement of H.3.1(9) in a
14690 convenient manner).
14692 @item @code{@emph{expr} && @emph{expr} && @emph{expr} ... && @emph{expr}}
14694 A multiple concatenation (same effect as @cite{expr} & @cite{expr} &
14695 @cite{expr}, but handled more efficiently).
14697 @item @code{[constraint_error]}
14699 Raise the @cite{Constraint_Error} exception.
14701 @item @code{@emph{expression}'reference}
14703 A pointer to the result of evaluating @{expression@}.
14705 @item @code{@emph{target-type}!(@emph{source-expression})}
14707 An unchecked conversion of @cite{source-expression} to @cite{target-type}.
14709 @item @code{[@emph{numerator}/@emph{denominator}]}
14711 Used to represent internal real literals (that) have no exact
14712 representation in base 2-16 (for example, the result of compile time
14713 evaluation of the expression 1.0/27.0).
14714 @end table
14715 @end table
14717 @geindex -gnatD (gcc)
14720 @table @asis
14722 @item @code{-gnatD[=nn]}
14724 When used in conjunction with @emph{-gnatG}, this switch causes
14725 the expanded source, as described above for
14726 @emph{-gnatG} to be written to files with names
14727 @code{xxx.dg}, where @code{xxx} is the normal file name,
14728 instead of to the standard output file. For
14729 example, if the source file name is @code{hello.adb}, then a file
14730 @code{hello.adb.dg} will be written.  The debugging
14731 information generated by the @emph{gcc} @emph{-g} switch
14732 will refer to the generated @code{xxx.dg} file. This allows
14733 you to do source level debugging using the generated code which is
14734 sometimes useful for complex code, for example to find out exactly
14735 which part of a complex construction raised an exception. This switch
14736 also suppress generation of cross-reference information (see
14737 @emph{-gnatx}) since otherwise the cross-reference information
14738 would refer to the @code{.dg} file, which would cause
14739 confusion since this is not the original source file.
14741 Note that @emph{-gnatD} actually implies @emph{-gnatG}
14742 automatically, so it is not necessary to give both options.
14743 In other words @emph{-gnatD} is equivalent to @emph{-gnatDG}).
14745 @geindex -gnatL (gcc)
14747 If the switch @emph{-gnatL} is used in conjunction with
14748 @emph{-gnatDG}, then the original source lines are interspersed
14749 in the expanded source (as comment lines with the original line number).
14751 The optional parameter @cite{nn} if present after -gnatD specifies an
14752 alternative maximum line length that overrides the normal default of 72.
14753 This value is in the range 40-999999, values less than 40 being silently
14754 reset to 40. The equal sign is optional.
14755 @end table
14757 @geindex -gnatr (gcc)
14759 @geindex pragma Restrictions
14762 @table @asis
14764 @item @code{-gnatr}
14766 This switch causes pragma Restrictions to be treated as Restriction_Warnings
14767 so that violation of restrictions causes warnings rather than illegalities.
14768 This is useful during the development process when new restrictions are added
14769 or investigated. The switch also causes pragma Profile to be treated as
14770 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
14771 restriction warnings rather than restrictions.
14772 @end table
14774 @geindex -gnatR (gcc)
14777 @table @asis
14779 @item @code{-gnatR[0|1|2|3[s]]}
14781 This switch controls output from the compiler of a listing showing
14782 representation information for declared types and objects. For
14783 @emph{-gnatR0}, no information is output (equivalent to omitting
14784 the @emph{-gnatR} switch). For @emph{-gnatR1} (which is the default,
14785 so @emph{-gnatR} with no parameter has the same effect), size and alignment
14786 information is listed for declared array and record types. For
14787 @emph{-gnatR2}, size and alignment information is listed for all
14788 declared types and objects. The @cite{Linker_Section} is also listed for any
14789 entity for which the @cite{Linker_Section} is set explicitly or implicitly (the
14790 latter case occurs for objects of a type for which a @cite{Linker_Section}
14791 is set).
14793 Finally @emph{-gnatR3} includes symbolic
14794 expressions for values that are computed at run time for
14795 variant records. These symbolic expressions have a mostly obvious
14796 format with #n being used to represent the value of the n'th
14797 discriminant. See source files @code{repinfo.ads/adb} in the
14798 @cite{GNAT} sources for full details on the format of @emph{-gnatR3}
14799 output. If the switch is followed by an s (e.g., @emph{-gnatR2s}), then
14800 the output is to a file with the name @code{file.rep} where
14801 file is the name of the corresponding source file.
14803 @item @code{-gnatRm[s]}
14805 This form of the switch controls output of subprogram conventions
14806 and parameter passing mechanisms for all subprograms. A following
14807 @cite{s} means output to a file as described above.
14809 Note that it is possible for record components to have zero size. In
14810 this case, the component clause uses an obvious extension of permitted
14811 Ada syntax, for example @cite{at 0 range 0 .. -1}.
14813 Representation information requires that code be generated (since it is the
14814 code generator that lays out complex data structures). If an attempt is made
14815 to output representation information when no code is generated, for example
14816 when a subunit is compiled on its own, then no information can be generated
14817 and the compiler outputs a message to this effect.
14818 @end table
14820 @geindex -gnatS (gcc)
14823 @table @asis
14825 @item @code{-gnatS}
14827 The use of the switch @emph{-gnatS} for an
14828 Ada compilation will cause the compiler to output a
14829 representation of package Standard in a form very
14830 close to standard Ada. It is not quite possible to
14831 do this entirely in standard Ada (since new
14832 numeric base types cannot be created in standard
14833 Ada), but the output is easily
14834 readable to any Ada programmer, and is useful to
14835 determine the characteristics of target dependent
14836 types in package Standard.
14837 @end table
14839 @geindex -gnatx (gcc)
14842 @table @asis
14844 @item @code{-gnatx}
14846 Normally the compiler generates full cross-referencing information in
14847 the @code{ALI} file. This information is used by a number of tools,
14848 including @cite{gnatfind} and @cite{gnatxref}. The @emph{-gnatx} switch
14849 suppresses this information. This saves some space and may slightly
14850 speed up compilation, but means that these tools cannot be used.
14851 @end table
14853 @node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
14854 @anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{114}@anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{115}
14855 @subsection Exception Handling Control
14858 GNAT uses two methods for handling exceptions at run-time. The
14859 @cite{setjmp/longjmp} method saves the context when entering
14860 a frame with an exception handler. Then when an exception is
14861 raised, the context can be restored immediately, without the
14862 need for tracing stack frames. This method provides very fast
14863 exception propagation, but introduces significant overhead for
14864 the use of exception handlers, even if no exception is raised.
14866 The other approach is called 'zero cost' exception handling.
14867 With this method, the compiler builds static tables to describe
14868 the exception ranges. No dynamic code is required when entering
14869 a frame containing an exception handler. When an exception is
14870 raised, the tables are used to control a back trace of the
14871 subprogram invocation stack to locate the required exception
14872 handler. This method has considerably poorer performance for
14873 the propagation of exceptions, but there is no overhead for
14874 exception handlers if no exception is raised. Note that in this
14875 mode and in the context of mixed Ada and C/C++ programming,
14876 to propagate an exception through a C/C++ code, the C/C++ code
14877 must be compiled with the @emph{-funwind-tables} GCC's
14878 option.
14880 The following switches may be used to control which of the
14881 two exception handling methods is used.
14883 @geindex --RTS=sjlj (gnatmake)
14886 @table @asis
14888 @item @code{--RTS=sjlj}
14890 This switch causes the setjmp/longjmp run-time (when available) to be used
14891 for exception handling. If the default
14892 mechanism for the target is zero cost exceptions, then
14893 this switch can be used to modify this default, and must be
14894 used for all units in the partition.
14895 This option is rarely used. One case in which it may be
14896 advantageous is if you have an application where exception
14897 raising is common and the overall performance of the
14898 application is improved by favoring exception propagation.
14899 @end table
14901 @geindex --RTS=zcx (gnatmake)
14903 @geindex Zero Cost Exceptions
14906 @table @asis
14908 @item @code{--RTS=zcx}
14910 This switch causes the zero cost approach to be used
14911 for exception handling. If this is the default mechanism for the
14912 target (see below), then this switch is unneeded. If the default
14913 mechanism for the target is setjmp/longjmp exceptions, then
14914 this switch can be used to modify this default, and must be
14915 used for all units in the partition.
14916 This option can only be used if the zero cost approach
14917 is available for the target in use, otherwise it will generate an error.
14918 @end table
14920 The same option @emph{--RTS} must be used both for @emph{gcc}
14921 and @emph{gnatbind}. Passing this option to @emph{gnatmake}
14922 (@ref{dc,,Switches for gnatmake}) will ensure the required consistency
14923 through the compilation and binding steps.
14925 @node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
14926 @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}
14927 @subsection Units to Sources Mapping Files
14930 @geindex -gnatem (gcc)
14933 @table @asis
14935 @item @code{-gnatem=@emph{path}}
14937 A mapping file is a way to communicate to the compiler two mappings:
14938 from unit names to file names (without any directory information) and from
14939 file names to path names (with full directory information). These mappings
14940 are used by the compiler to short-circuit the path search.
14942 The use of mapping files is not required for correct operation of the
14943 compiler, but mapping files can improve efficiency, particularly when
14944 sources are read over a slow network connection. In normal operation,
14945 you need not be concerned with the format or use of mapping files,
14946 and the @emph{-gnatem} switch is not a switch that you would use
14947 explicitly. It is intended primarily for use by automatic tools such as
14948 @emph{gnatmake} running under the project file facility. The
14949 description here of the format of mapping files is provided
14950 for completeness and for possible use by other tools.
14952 A mapping file is a sequence of sets of three lines. In each set, the
14953 first line is the unit name, in lower case, with @cite{%s} appended
14954 for specs and @cite{%b} appended for bodies; the second line is the
14955 file name; and the third line is the path name.
14957 Example:
14959 @example
14960 main%b
14961 main.2.ada
14962 /gnat/project1/sources/main.2.ada
14963 @end example
14965 When the switch @emph{-gnatem} is specified, the compiler will
14966 create in memory the two mappings from the specified file. If there is
14967 any problem (nonexistent file, truncated file or duplicate entries),
14968 no mapping will be created.
14970 Several @emph{-gnatem} switches may be specified; however, only the
14971 last one on the command line will be taken into account.
14973 When using a project file, @emph{gnatmake} creates a temporary
14974 mapping file and communicates it to the compiler using this switch.
14975 @end table
14977 @node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
14978 @anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{117}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{118}
14979 @subsection Code Generation Control
14982 The GCC technology provides a wide range of target dependent
14983 @code{-m} switches for controlling
14984 details of code generation with respect to different versions of
14985 architectures. This includes variations in instruction sets (e.g.,
14986 different members of the power pc family), and different requirements
14987 for optimal arrangement of instructions (e.g., different members of
14988 the x86 family). The list of available @emph{-m} switches may be
14989 found in the GCC documentation.
14991 Use of these @emph{-m} switches may in some cases result in improved
14992 code performance.
14994 The GNAT technology is tested and qualified without any
14995 @code{-m} switches,
14996 so generally the most reliable approach is to avoid the use of these
14997 switches. However, we generally expect most of these switches to work
14998 successfully with GNAT, and many customers have reported successful
14999 use of these options.
15001 Our general advice is to avoid the use of @emph{-m} switches unless
15002 special needs lead to requirements in this area. In particular,
15003 there is no point in using @emph{-m} switches to improve performance
15004 unless you actually see a performance improvement.
15006 @node Binding with gnatbind,Linking with gnatlink,Compiler Switches,Building Executable Programs with GNAT
15007 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{1d}@anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{119}
15008 @section Binding with @cite{gnatbind}
15011 @geindex gnatbind
15013 This chapter describes the GNAT binder, @cite{gnatbind}, which is used
15014 to bind compiled GNAT objects.
15016 Note: to invoke @cite{gnatbind} with a project file, use the @cite{gnat}
15017 driver (see @emph{The_GNAT_Driver_and_Project_Files}).
15019 The @cite{gnatbind} program performs four separate functions:
15022 @itemize *
15024 @item 
15025 Checks that a program is consistent, in accordance with the rules in
15026 Chapter 10 of the Ada Reference Manual. In particular, error
15027 messages are generated if a program uses inconsistent versions of a
15028 given unit.
15030 @item 
15031 Checks that an acceptable order of elaboration exists for the program
15032 and issues an error message if it cannot find an order of elaboration
15033 that satisfies the rules in Chapter 10 of the Ada Language Manual.
15035 @item 
15036 Generates a main program incorporating the given elaboration order.
15037 This program is a small Ada package (body and spec) that
15038 must be subsequently compiled
15039 using the GNAT compiler. The necessary compilation step is usually
15040 performed automatically by @emph{gnatlink}. The two most important
15041 functions of this program
15042 are to call the elaboration routines of units in an appropriate order
15043 and to call the main program.
15045 @item 
15046 Determines the set of object files required by the given main program.
15047 This information is output in the forms of comments in the generated program,
15048 to be read by the @emph{gnatlink} utility used to link the Ada application.
15049 @end itemize
15051 @menu
15052 * Running gnatbind:: 
15053 * Switches for gnatbind:: 
15054 * Command-Line Access:: 
15055 * Search Paths for gnatbind:: 
15056 * Examples of gnatbind Usage:: 
15058 @end menu
15060 @node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
15061 @anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{11a}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{11b}
15062 @subsection Running @cite{gnatbind}
15065 The form of the @cite{gnatbind} command is
15067 @example
15068 $ gnatbind [`switches`] `mainprog`[.ali] [`switches`]
15069 @end example
15071 where @code{mainprog.adb} is the Ada file containing the main program
15072 unit body. @cite{gnatbind} constructs an Ada
15073 package in two files whose names are
15074 @code{b~mainprog.ads}, and @code{b~mainprog.adb}.
15075 For example, if given the
15076 parameter @code{hello.ali}, for a main program contained in file
15077 @code{hello.adb}, the binder output files would be @code{b~hello.ads}
15078 and @code{b~hello.adb}.
15080 When doing consistency checking, the binder takes into consideration
15081 any source files it can locate. For example, if the binder determines
15082 that the given main program requires the package @cite{Pack}, whose
15083 @code{.ALI}
15084 file is @code{pack.ali} and whose corresponding source spec file is
15085 @code{pack.ads}, it attempts to locate the source file @code{pack.ads}
15086 (using the same search path conventions as previously described for the
15087 @emph{gcc} command). If it can locate this source file, it checks that
15088 the time stamps
15089 or source checksums of the source and its references to in @code{ALI} files
15090 match. In other words, any @code{ALI} files that mentions this spec must have
15091 resulted from compiling this version of the source file (or in the case
15092 where the source checksums match, a version close enough that the
15093 difference does not matter).
15095 @geindex Source files
15096 @geindex use by binder
15098 The effect of this consistency checking, which includes source files, is
15099 that the binder ensures that the program is consistent with the latest
15100 version of the source files that can be located at bind time. Editing a
15101 source file without compiling files that depend on the source file cause
15102 error messages to be generated by the binder.
15104 For example, suppose you have a main program @code{hello.adb} and a
15105 package @cite{P}, from file @code{p.ads} and you perform the following
15106 steps:
15109 @itemize *
15111 @item 
15112 Enter @cite{gcc -c hello.adb} to compile the main program.
15114 @item 
15115 Enter @cite{gcc -c p.ads} to compile package @cite{P}.
15117 @item 
15118 Edit file @code{p.ads}.
15120 @item 
15121 Enter @cite{gnatbind hello}.
15122 @end itemize
15124 At this point, the file @code{p.ali} contains an out-of-date time stamp
15125 because the file @code{p.ads} has been edited. The attempt at binding
15126 fails, and the binder generates the following error messages:
15128 @example
15129 error: "hello.adb" must be recompiled ("p.ads" has been modified)
15130 error: "p.ads" has been modified and must be recompiled
15131 @end example
15133 Now both files must be recompiled as indicated, and then the bind can
15134 succeed, generating a main program. You need not normally be concerned
15135 with the contents of this file, but for reference purposes a sample
15136 binder output file is given in @ref{e,,Example of Binder Output File}.
15138 In most normal usage, the default mode of @emph{gnatbind} which is to
15139 generate the main package in Ada, as described in the previous section.
15140 In particular, this means that any Ada programmer can read and understand
15141 the generated main program. It can also be debugged just like any other
15142 Ada code provided the @emph{-g} switch is used for
15143 @emph{gnatbind} and @emph{gnatlink}.
15145 @node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
15146 @anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{11c}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{11d}
15147 @subsection Switches for @emph{gnatbind}
15150 The following switches are available with @cite{gnatbind}; details will
15151 be presented in subsequent sections.
15153 @geindex --version (gnatbind)
15156 @table @asis
15158 @item @code{--version}
15160 Display Copyright and version, then exit disregarding all other options.
15161 @end table
15163 @geindex --help (gnatbind)
15166 @table @asis
15168 @item @code{--help}
15170 If @emph{--version} was not used, display usage, then exit disregarding
15171 all other options.
15172 @end table
15174 @geindex -a (gnatbind)
15177 @table @asis
15179 @item @code{-a}
15181 Indicates that, if supported by the platform, the adainit procedure should
15182 be treated as an initialisation routine by the linker (a constructor). This
15183 is intended to be used by the Project Manager to automatically initialize
15184 shared Stand-Alone Libraries.
15185 @end table
15187 @geindex -aO (gnatbind)
15190 @table @asis
15192 @item @code{-aO}
15194 Specify directory to be searched for ALI files.
15195 @end table
15197 @geindex -aI (gnatbind)
15200 @table @asis
15202 @item @code{-aI}
15204 Specify directory to be searched for source file.
15205 @end table
15207 @geindex -A (gnatbind)
15210 @table @asis
15212 @item @code{-A[=@emph{filename}]}
15214 Output ALI list (to standard output or to the named file).
15215 @end table
15217 @geindex -b (gnatbind)
15220 @table @asis
15222 @item @code{-b}
15224 Generate brief messages to @code{stderr} even if verbose mode set.
15225 @end table
15227 @geindex -c (gnatbind)
15230 @table @asis
15232 @item @code{-c}
15234 Check only, no generation of binder output file.
15235 @end table
15237 @geindex -dnn[k|m] (gnatbind)
15240 @table @asis
15242 @item @code{-d@emph{nn}[k|m]}
15244 This switch can be used to change the default task stack size value
15245 to a specified size @cite{nn}, which is expressed in bytes by default, or
15246 in kilobytes when suffixed with @cite{k} or in megabytes when suffixed
15247 with @cite{m}.
15248 In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15249 in effect, to completing all task specs with
15251 @example
15252 pragma Storage_Size (nn);
15253 @end example
15255 When they do not already have such a pragma.
15256 @end table
15258 @geindex -D (gnatbind)
15261 @table @asis
15263 @item @code{-D@emph{nn}[k|m]}
15265 This switch can be used to change the default secondary stack size value
15266 to a specified size @cite{nn}, which is expressed in bytes by default, or
15267 in kilobytes when suffixed with @cite{k} or in megabytes when suffixed
15268 with @cite{m}.
15270 The secondary stack is used to deal with functions that return a variable
15271 sized result, for example a function returning an unconstrained
15272 String. There are two ways in which this secondary stack is allocated.
15274 For most targets, the secondary stack is growing on demand and is allocated
15275 as a chain of blocks in the heap. The -D option is not very
15276 relevant. It only give some control over the size of the allocated
15277 blocks (whose size is the minimum of the default secondary stack size value,
15278 and the actual size needed for the current allocation request).
15280 For certain targets, notably VxWorks 653,
15281 the secondary stack is allocated by carving off a fixed ratio chunk of the
15282 primary task stack. The -D option is used to define the
15283 size of the environment task's secondary stack.
15284 @end table
15286 @geindex -e (gnatbind)
15289 @table @asis
15291 @item @code{-e}
15293 Output complete list of elaboration-order dependencies.
15294 @end table
15296 @geindex -Ea (gnatbind)
15299 @table @asis
15301 @item @code{-Ea}
15303 Store tracebacks in exception occurrences when the target supports it.
15304 The "a" is for "address"; tracebacks will contain hexadecimal addresses,
15305 unless symbolic tracebacks are enabled.
15307 See also the packages @cite{GNAT.Traceback} and
15308 @cite{GNAT.Traceback.Symbolic} for more information.
15309 Note that on x86 ports, you must not use @emph{-fomit-frame-pointer}
15310 @emph{gcc} option.
15311 @end table
15313 @geindex -Es (gnatbind)
15316 @table @asis
15318 @item @code{-Es}
15320 Store tracebacks in exception occurrences when the target supports it.
15321 The "s" is for "symbolic"; symbolic tracebacks are enabled.
15322 @end table
15324 @geindex -E (gnatbind)
15327 @table @asis
15329 @item @code{-E}
15331 Currently the same as @cite{-Ea}.
15332 @end table
15334 @geindex -F (gnatbind)
15337 @table @asis
15339 @item @code{-F}
15341 Force the checks of elaboration flags. @emph{gnatbind} does not normally
15342 generate checks of elaboration flags for the main executable, except when
15343 a Stand-Alone Library is used. However, there are cases when this cannot be
15344 detected by gnatbind. An example is importing an interface of a Stand-Alone
15345 Library through a pragma Import and only specifying through a linker switch
15346 this Stand-Alone Library. This switch is used to guarantee that elaboration
15347 flag checks are generated.
15348 @end table
15350 @geindex -h (gnatbind)
15353 @table @asis
15355 @item @code{-h}
15357 Output usage (help) information.
15359 @geindex -H32 (gnatbind)
15361 @item @code{-H32}
15363 Use 32-bit allocations for @cite{__gnat_malloc} (and thus for access types).
15364 For further details see @ref{11e,,Dynamic Allocation Control}.
15366 @geindex -H64 (gnatbind)
15368 @geindex __gnat_malloc
15370 @item @code{-H64}
15372 Use 64-bit allocations for @cite{__gnat_malloc} (and thus for access types).
15373 For further details see @ref{11e,,Dynamic Allocation Control}.
15375 @geindex -I (gnatbind)
15377 @item @code{-I}
15379 Specify directory to be searched for source and ALI files.
15381 @geindex -I- (gnatbind)
15383 @item @code{-I-}
15385 Do not look for sources in the current directory where @cite{gnatbind} was
15386 invoked, and do not look for ALI files in the directory containing the
15387 ALI file named in the @cite{gnatbind} command line.
15389 @geindex -l (gnatbind)
15391 @item @code{-l}
15393 Output chosen elaboration order.
15395 @geindex -L (gnatbind)
15397 @item @code{-L@emph{xxx}}
15399 Bind the units for library building. In this case the adainit and
15400 adafinal procedures (@ref{b4,,Binding with Non-Ada Main Programs})
15401 are renamed to @cite{xxx`init and `xxx`final. Implies -n. (:ref:`GNAT_and_Libraries}, for more details.)
15403 @geindex -M (gnatbind)
15405 @item @code{-M@emph{xyz}}
15407 Rename generated main program from main to xyz. This option is
15408 supported on cross environments only.
15410 @geindex -m (gnatbind)
15412 @item @code{-m@emph{n}}
15414 Limit number of detected errors or warnings to @cite{n}, where @cite{n} is
15415 in the range 1..999999. The default value if no switch is
15416 given is 9999. If the number of warnings reaches this limit, then a
15417 message is output and further warnings are suppressed, the bind
15418 continues in this case. If the number of errors reaches this
15419 limit, then a message is output and the bind is abandoned.
15420 A value of zero means that no limit is enforced. The equal
15421 sign is optional.
15423 @geindex -n (gnatbind)
15425 @item @code{-n}
15427 No main program.
15429 @geindex -nostdinc (gnatbind)
15431 @item @code{-nostdinc}
15433 Do not look for sources in the system default directory.
15435 @geindex -nostdlib (gnatbind)
15437 @item @code{-nostdlib}
15439 Do not look for library files in the system default directory.
15441 @geindex --RTS (gnatbind)
15443 @item @code{--RTS=@emph{rts-path}}
15445 Specifies the default location of the runtime library. Same meaning as the
15446 equivalent @emph{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
15448 @geindex -o (gnatbind)
15450 @item @code{-o @emph{file}}
15452 Name the output file @cite{file} (default is @code{b~`xxx}.adb`).
15453 Note that if this option is used, then linking must be done manually,
15454 gnatlink cannot be used.
15456 @geindex -O (gnatbind)
15458 @item @code{-O[=@emph{filename}]}
15460 Output object list (to standard output or to the named file).
15462 @geindex -p (gnatbind)
15464 @item @code{-p}
15466 Pessimistic (worst-case) elaboration order.
15468 @geindex -P (gnatbind)
15470 @item @code{-P}
15472 Generate binder file suitable for CodePeer.
15474 @geindex -R (gnatbind)
15476 @item @code{-R}
15478 Output closure source list, which includes all non-run-time units that are
15479 included in the bind.
15481 @geindex -Ra (gnatbind)
15483 @item @code{-Ra}
15485 Like @emph{-R} but the list includes run-time units.
15487 @geindex -s (gnatbind)
15489 @item @code{-s}
15491 Require all source files to be present.
15493 @geindex -S (gnatbind)
15495 @item @code{-S@emph{xxx}}
15497 Specifies the value to be used when detecting uninitialized scalar
15498 objects with pragma Initialize_Scalars.
15499 The @cite{xxx} string specified with the switch is one of:
15502 @itemize *
15504 @item 
15505 @code{in} for an invalid value.
15507 If zero is invalid for the discrete type in question,
15508 then the scalar value is set to all zero bits.
15509 For signed discrete types, the largest possible negative value of
15510 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15511 For unsigned discrete types, the underlying scalar value is set to all
15512 one bits. For floating-point types, a NaN value is set
15513 (see body of package System.Scalar_Values for exact values).
15515 @item 
15516 @code{lo} for low value.
15518 If zero is invalid for the discrete type in question,
15519 then the scalar value is set to all zero bits.
15520 For signed discrete types, the largest possible negative value of
15521 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15522 For unsigned discrete types, the underlying scalar value is set to all
15523 zero bits. For floating-point, a small value is set
15524 (see body of package System.Scalar_Values for exact values).
15526 @item 
15527 @code{hi} for high value.
15529 If zero is invalid for the discrete type in question,
15530 then the scalar value is set to all one bits.
15531 For signed discrete types, the largest possible positive value of
15532 the underlying scalar is set (i.e. a zero bit followed by all one bits).
15533 For unsigned discrete types, the underlying scalar value is set to all
15534 one bits. For floating-point, a large value is set
15535 (see body of package System.Scalar_Values for exact values).
15537 @item 
15538 @cite{xx} for hex value (two hex digits).
15540 The underlying scalar is set to a value consisting of repeated bytes, whose
15541 value corresponds to the given value. For example if @code{BF} is given,
15542 then a 32-bit scalar value will be set to the bit patterm @code{16#BFBFBFBF#}.
15543 @end itemize
15545 @geindex GNAT_INIT_SCALARS
15547 In addition, you can specify @emph{-Sev} to indicate that the value is
15548 to be set at run time. In this case, the program will look for an environment
15549 variable of the form @code{GNAT_INIT_SCALARS=@emph{yy}}, where @cite{yy} is one
15550 of @emph{in/lo/hi/`xx*` with the same meanings as above.
15551 If no environment variable is found, or if it does not have a valid value,
15552 then the default is *in} (invalid values).
15553 @end table
15555 @geindex -static (gnatbind)
15558 @table @asis
15560 @item @code{-static}
15562 Link against a static GNAT run time.
15564 @geindex -shared (gnatbind)
15566 @item @code{-shared}
15568 Link against a shared GNAT run time when available.
15570 @geindex -t (gnatbind)
15572 @item @code{-t}
15574 Tolerate time stamp and other consistency errors.
15576 @geindex -T (gnatbind)
15578 @item @code{-T@emph{n}}
15580 Set the time slice value to @cite{n} milliseconds. If the system supports
15581 the specification of a specific time slice value, then the indicated value
15582 is used. If the system does not support specific time slice values, but
15583 does support some general notion of round-robin scheduling, then any
15584 nonzero value will activate round-robin scheduling.
15586 A value of zero is treated specially. It turns off time
15587 slicing, and in addition, indicates to the tasking run time that the
15588 semantics should match as closely as possible the Annex D
15589 requirements of the Ada RM, and in particular sets the default
15590 scheduling policy to @cite{FIFO_Within_Priorities}.
15592 @geindex -u (gnatbind)
15594 @item @code{-u@emph{n}}
15596 Enable dynamic stack usage, with @cite{n} results stored and displayed
15597 at program termination. A result is generated when a task
15598 terminates. Results that can't be stored are displayed on the fly, at
15599 task termination. This option is currently not supported on Itanium
15600 platforms. (See @ref{11f,,Dynamic Stack Usage Analysis} for details.)
15602 @geindex -v (gnatbind)
15604 @item @code{-v}
15606 Verbose mode. Write error messages, header, summary output to
15607 @code{stdout}.
15609 @geindex -V (gnatbind)
15611 @item @code{-V@emph{key}=@emph{value}}
15613 Store the given association of @cite{key} to @cite{value} in the bind environment.
15614 Values stored this way can be retrieved at run time using
15615 @cite{GNAT.Bind_Environment}.
15617 @geindex -w (gnatbind)
15619 @item @code{-w@emph{x}}
15621 Warning mode; @cite{x} = s/e for suppress/treat as error.
15623 @geindex -Wx (gnatbind)
15625 @item @code{-Wx@emph{e}}
15627 Override default wide character encoding for standard Text_IO files.
15629 @geindex -x (gnatbind)
15631 @item @code{-x}
15633 Exclude source files (check object consistency only).
15635 @geindex -Xnnn (gnatbind)
15637 @item @code{-X@emph{nnn}}
15639 Set default exit status value, normally 0 for POSIX compliance.
15641 @geindex -y (gnatbind)
15643 @item @code{-y}
15645 Enable leap seconds support in @cite{Ada.Calendar} and its children.
15647 @geindex -z (gnatbind)
15649 @item @code{-z}
15651 No main subprogram.
15652 @end table
15654 You may obtain this listing of switches by running @cite{gnatbind} with
15655 no arguments.
15657 @menu
15658 * Consistency-Checking Modes:: 
15659 * Binder Error Message Control:: 
15660 * Elaboration Control:: 
15661 * Output Control:: 
15662 * Dynamic Allocation Control:: 
15663 * Binding with Non-Ada Main Programs:: 
15664 * Binding Programs with No Main Subprogram:: 
15666 @end menu
15668 @node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
15669 @anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{120}@anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{121}
15670 @subsubsection Consistency-Checking Modes
15673 As described earlier, by default @cite{gnatbind} checks
15674 that object files are consistent with one another and are consistent
15675 with any source files it can locate. The following switches control binder
15676 access to sources.
15678 @quotation
15680 @geindex -s (gnatbind)
15681 @end quotation
15684 @table @asis
15686 @item @code{-s}
15688 Require source files to be present. In this mode, the binder must be
15689 able to locate all source files that are referenced, in order to check
15690 their consistency. In normal mode, if a source file cannot be located it
15691 is simply ignored. If you specify this switch, a missing source
15692 file is an error.
15694 @geindex -Wx (gnatbind)
15696 @item @code{-Wx@emph{e}}
15698 Override default wide character encoding for standard Text_IO files.
15699 Normally the default wide character encoding method used for standard
15700 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
15701 the main source input (see description of switch
15702 @emph{-gnatWx} for the compiler). The
15703 use of this switch for the binder (which has the same set of
15704 possible arguments) overrides this default as specified.
15706 @geindex -x (gnatbind)
15708 @item @code{-x}
15710 Exclude source files. In this mode, the binder only checks that ALI
15711 files are consistent with one another. Source files are not accessed.
15712 The binder runs faster in this mode, and there is still a guarantee that
15713 the resulting program is self-consistent.
15714 If a source file has been edited since it was last compiled, and you
15715 specify this switch, the binder will not detect that the object
15716 file is out of date with respect to the source file. Note that this is the
15717 mode that is automatically used by @emph{gnatmake} because in this
15718 case the checking against sources has already been performed by
15719 @emph{gnatmake} in the course of compilation (i.e., before binding).
15720 @end table
15722 @node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
15723 @anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{122}@anchor{gnat_ugn/building_executable_programs_with_gnat binder-error-message-control}@anchor{123}
15724 @subsubsection Binder Error Message Control
15727 The following switches provide control over the generation of error
15728 messages from the binder:
15730 @quotation
15732 @geindex -v (gnatbind)
15733 @end quotation
15736 @table @asis
15738 @item @code{-v}
15740 Verbose mode. In the normal mode, brief error messages are generated to
15741 @code{stderr}. If this switch is present, a header is written
15742 to @code{stdout} and any error messages are directed to @code{stdout}.
15743 All that is written to @code{stderr} is a brief summary message.
15745 @geindex -b (gnatbind)
15747 @item @code{-b}
15749 Generate brief error messages to @code{stderr} even if verbose mode is
15750 specified. This is relevant only when used with the
15751 @emph{-v} switch.
15753 @geindex -m (gnatbind)
15755 @item @code{-m@emph{n}}
15757 Limits the number of error messages to @cite{n}, a decimal integer in the
15758 range 1-999. The binder terminates immediately if this limit is reached.
15760 @geindex -M (gnatbind)
15762 @item @code{-M@emph{xxx}}
15764 Renames the generated main program from @cite{main} to @cite{xxx}.
15765 This is useful in the case of some cross-building environments, where
15766 the actual main program is separate from the one generated
15767 by @cite{gnatbind}.
15769 @geindex -ws (gnatbind)
15771 @geindex Warnings
15773 @item @code{-ws}
15775 Suppress all warning messages.
15777 @geindex -we (gnatbind)
15779 @item @code{-we}
15781 Treat any warning messages as fatal errors.
15783 @geindex -t (gnatbind)
15785 @geindex Time stamp checks
15786 @geindex in binder
15788 @geindex Binder consistency checks
15790 @geindex Consistency checks
15791 @geindex in binder
15793 @item @code{-t}
15795 The binder performs a number of consistency checks including:
15798 @itemize *
15800 @item 
15801 Check that time stamps of a given source unit are consistent
15803 @item 
15804 Check that checksums of a given source unit are consistent
15806 @item 
15807 Check that consistent versions of @cite{GNAT} were used for compilation
15809 @item 
15810 Check consistency of configuration pragmas as required
15811 @end itemize
15813 Normally failure of such checks, in accordance with the consistency
15814 requirements of the Ada Reference Manual, causes error messages to be
15815 generated which abort the binder and prevent the output of a binder
15816 file and subsequent link to obtain an executable.
15818 The @emph{-t} switch converts these error messages
15819 into warnings, so that
15820 binding and linking can continue to completion even in the presence of such
15821 errors. The result may be a failed link (due to missing symbols), or a
15822 non-functional executable which has undefined semantics.
15824 @cartouche
15825 @quotation Note 
15826 This means that @emph{-t} should be used only in unusual situations,
15827 with extreme care.
15828 @end quotation
15829 @end cartouche
15830 @end table
15832 @node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
15833 @anchor{gnat_ugn/building_executable_programs_with_gnat id36}@anchor{124}@anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{125}
15834 @subsubsection Elaboration Control
15837 The following switches provide additional control over the elaboration
15838 order. For full details see @ref{f,,Elaboration Order Handling in GNAT}.
15840 @quotation
15842 @geindex -p (gnatbind)
15843 @end quotation
15846 @table @asis
15848 @item @code{-p}
15850 Normally the binder attempts to choose an elaboration order that is
15851 likely to minimize the likelihood of an elaboration order error resulting
15852 in raising a @cite{Program_Error} exception. This switch reverses the
15853 action of the binder, and requests that it deliberately choose an order
15854 that is likely to maximize the likelihood of an elaboration error.
15855 This is useful in ensuring portability and avoiding dependence on
15856 accidental fortuitous elaboration ordering.
15858 Normally it only makes sense to use the @emph{-p}
15859 switch if dynamic
15860 elaboration checking is used (@emph{-gnatE} switch used for compilation).
15861 This is because in the default static elaboration mode, all necessary
15862 @cite{Elaborate} and @cite{Elaborate_All} pragmas are implicitly inserted.
15863 These implicit pragmas are still respected by the binder in
15864 @emph{-p} mode, so a
15865 safe elaboration order is assured.
15867 Note that @emph{-p} is not intended for
15868 production use; it is more for debugging/experimental use.
15869 @end table
15871 @node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
15872 @anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{126}@anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{127}
15873 @subsubsection Output Control
15876 The following switches allow additional control over the output
15877 generated by the binder.
15879 @quotation
15881 @geindex -c (gnatbind)
15882 @end quotation
15885 @table @asis
15887 @item @code{-c}
15889 Check only. Do not generate the binder output file. In this mode the
15890 binder performs all error checks but does not generate an output file.
15892 @geindex -e (gnatbind)
15894 @item @code{-e}
15896 Output complete list of elaboration-order dependencies, showing the
15897 reason for each dependency. This output can be rather extensive but may
15898 be useful in diagnosing problems with elaboration order. The output is
15899 written to @code{stdout}.
15901 @geindex -h (gnatbind)
15903 @item @code{-h}
15905 Output usage information. The output is written to @code{stdout}.
15907 @geindex -K (gnatbind)
15909 @item @code{-K}
15911 Output linker options to @code{stdout}. Includes library search paths,
15912 contents of pragmas Ident and Linker_Options, and libraries added
15913 by @cite{gnatbind}.
15915 @geindex -l (gnatbind)
15917 @item @code{-l}
15919 Output chosen elaboration order. The output is written to @code{stdout}.
15921 @geindex -O (gnatbind)
15923 @item @code{-O}
15925 Output full names of all the object files that must be linked to provide
15926 the Ada component of the program. The output is written to @code{stdout}.
15927 This list includes the files explicitly supplied and referenced by the user
15928 as well as implicitly referenced run-time unit files. The latter are
15929 omitted if the corresponding units reside in shared libraries. The
15930 directory names for the run-time units depend on the system configuration.
15932 @geindex -o (gnatbind)
15934 @item @code{-o @emph{file}}
15936 Set name of output file to @cite{file} instead of the normal
15937 @code{b~`mainprog}.adb` default. Note that @cite{file} denote the Ada
15938 binder generated body filename.
15939 Note that if this option is used, then linking must be done manually.
15940 It is not possible to use gnatlink in this case, since it cannot locate
15941 the binder file.
15943 @geindex -r (gnatbind)
15945 @item @code{-r}
15947 Generate list of @cite{pragma Restrictions} that could be applied to
15948 the current unit. This is useful for code audit purposes, and also may
15949 be used to improve code generation in some cases.
15950 @end table
15952 @node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
15953 @anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{11e}@anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{128}
15954 @subsubsection Dynamic Allocation Control
15957 The heap control switches -- @emph{-H32} and @emph{-H64} --
15958 determine whether dynamic allocation uses 32-bit or 64-bit memory.
15959 They only affect compiler-generated allocations via @cite{__gnat_malloc};
15960 explicit calls to @cite{malloc} and related functions from the C
15961 run-time library are unaffected.
15964 @table @asis
15966 @item @code{-H32}
15968 Allocate memory on 32-bit heap
15970 @item @code{-H64}
15972 Allocate memory on 64-bit heap.  This is the default
15973 unless explicitly overridden by a @cite{'Size} clause on the access type.
15974 @end table
15976 These switches are only effective on VMS platforms.
15978 @node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
15979 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-non-ada-main-programs}@anchor{b4}@anchor{gnat_ugn/building_executable_programs_with_gnat id39}@anchor{129}
15980 @subsubsection Binding with Non-Ada Main Programs
15983 The description so far has assumed that the main
15984 program is in Ada, and that the task of the binder is to generate a
15985 corresponding function @cite{main} that invokes this Ada main
15986 program. GNAT also supports the building of executable programs where
15987 the main program is not in Ada, but some of the called routines are
15988 written in Ada and compiled using GNAT (@ref{44,,Mixed Language Programming}).
15989 The following switch is used in this situation:
15991 @quotation
15993 @geindex -n (gnatbind)
15994 @end quotation
15997 @table @asis
15999 @item @code{-n}
16001 No main program. The main program is not in Ada.
16002 @end table
16004 In this case, most of the functions of the binder are still required,
16005 but instead of generating a main program, the binder generates a file
16006 containing the following callable routines:
16008 @quotation
16010 @geindex adainit
16013 @table @asis
16015 @item @emph{adainit}
16017 You must call this routine to initialize the Ada part of the program by
16018 calling the necessary elaboration routines. A call to @cite{adainit} is
16019 required before the first call to an Ada subprogram.
16021 Note that it is assumed that the basic execution environment must be setup
16022 to be appropriate for Ada execution at the point where the first Ada
16023 subprogram is called. In particular, if the Ada code will do any
16024 floating-point operations, then the FPU must be setup in an appropriate
16025 manner. For the case of the x86, for example, full precision mode is
16026 required. The procedure GNAT.Float_Control.Reset may be used to ensure
16027 that the FPU is in the right state.
16028 @end table
16030 @geindex adafinal
16033 @table @asis
16035 @item @emph{adafinal}
16037 You must call this routine to perform any library-level finalization
16038 required by the Ada subprograms. A call to @cite{adafinal} is required
16039 after the last call to an Ada subprogram, and before the program
16040 terminates.
16041 @end table
16042 @end quotation
16044 @geindex -n (gnatbind)
16046 @geindex Binder
16047 @geindex multiple input files
16049 If the @emph{-n} switch
16050 is given, more than one ALI file may appear on
16051 the command line for @cite{gnatbind}. The normal @emph{closure}
16052 calculation is performed for each of the specified units. Calculating
16053 the closure means finding out the set of units involved by tracing
16054 @emph{with} references. The reason it is necessary to be able to
16055 specify more than one ALI file is that a given program may invoke two or
16056 more quite separate groups of Ada units.
16058 The binder takes the name of its output file from the last specified ALI
16059 file, unless overridden by the use of the @emph{-o file}.
16061 @geindex -o (gnatbind)
16063 The output is an Ada unit in source form that can be compiled with GNAT.
16064 This compilation occurs automatically as part of the @emph{gnatlink}
16065 processing.
16067 Currently the GNAT run time requires a FPU using 80 bits mode
16068 precision. Under targets where this is not the default it is required to
16069 call GNAT.Float_Control.Reset before using floating point numbers (this
16070 include float computation, float input and output) in the Ada code. A
16071 side effect is that this could be the wrong mode for the foreign code
16072 where floating point computation could be broken after this call.
16074 @node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
16075 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-programs-with-no-main-subprogram}@anchor{12a}@anchor{gnat_ugn/building_executable_programs_with_gnat id40}@anchor{12b}
16076 @subsubsection Binding Programs with No Main Subprogram
16079 It is possible to have an Ada program which does not have a main
16080 subprogram. This program will call the elaboration routines of all the
16081 packages, then the finalization routines.
16083 The following switch is used to bind programs organized in this manner:
16085 @quotation
16087 @geindex -z (gnatbind)
16088 @end quotation
16091 @table @asis
16093 @item @code{-z}
16095 Normally the binder checks that the unit name given on the command line
16096 corresponds to a suitable main subprogram. When this switch is used,
16097 a list of ALI files can be given, and the execution of the program
16098 consists of elaboration of these units in an appropriate order. Note
16099 that the default wide character encoding method for standard Text_IO
16100 files is always set to Brackets if this switch is set (you can use
16101 the binder switch
16102 @emph{-Wx} to override this default).
16103 @end table
16105 @node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
16106 @anchor{gnat_ugn/building_executable_programs_with_gnat id41}@anchor{12c}@anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{12d}
16107 @subsection Command-Line Access
16110 The package @cite{Ada.Command_Line} provides access to the command-line
16111 arguments and program name. In order for this interface to operate
16112 correctly, the two variables
16114 @example
16115 int gnat_argc;
16116 char **gnat_argv;
16117 @end example
16119 @geindex gnat_argv
16121 @geindex gnat_argc
16123 are declared in one of the GNAT library routines. These variables must
16124 be set from the actual @cite{argc} and @cite{argv} values passed to the
16125 main program. With no @emph{n} present, @cite{gnatbind}
16126 generates the C main program to automatically set these variables.
16127 If the @emph{n} switch is used, there is no automatic way to
16128 set these variables. If they are not set, the procedures in
16129 @cite{Ada.Command_Line} will not be available, and any attempt to use
16130 them will raise @cite{Constraint_Error}. If command line access is
16131 required, your main program must set @cite{gnat_argc} and
16132 @cite{gnat_argv} from the @cite{argc} and @cite{argv} values passed to
16135 @node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
16136 @anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-for-gnatbind}@anchor{8c}@anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{12e}
16137 @subsection Search Paths for @cite{gnatbind}
16140 The binder takes the name of an ALI file as its argument and needs to
16141 locate source files as well as other ALI files to verify object consistency.
16143 For source files, it follows exactly the same search rules as @emph{gcc}
16144 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
16145 directories searched are:
16148 @itemize *
16150 @item 
16151 The directory containing the ALI file named in the command line, unless
16152 the switch @emph{-I-} is specified.
16154 @item 
16155 All directories specified by @emph{-I}
16156 switches on the @cite{gnatbind}
16157 command line, in the order given.
16159 @geindex ADA_PRJ_OBJECTS_FILE
16161 @item 
16162 Each of the directories listed in the text file whose name is given
16163 by the 
16164 @geindex ADA_PRJ_OBJECTS_FILE
16165 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16166 @code{ADA_PRJ_OBJECTS_FILE} environment variable.
16168 @geindex ADA_PRJ_OBJECTS_FILE
16169 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16170 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
16171 driver when project files are used. It should not normally be set
16172 by other means.
16174 @geindex ADA_OBJECTS_PATH
16176 @item 
16177 Each of the directories listed in the value of the
16178 @geindex ADA_OBJECTS_PATH
16179 @geindex environment variable; ADA_OBJECTS_PATH
16180 @code{ADA_OBJECTS_PATH} environment variable.
16181 Construct this value
16182 exactly as the 
16183 @geindex PATH
16184 @geindex environment variable; PATH
16185 @code{PATH} environment variable: a list of directory
16186 names separated by colons (semicolons when working with the NT version
16187 of GNAT).
16189 @item 
16190 The content of the @code{ada_object_path} file which is part of the GNAT
16191 installation tree and is used to store standard libraries such as the
16192 GNAT Run Time Library (RTL) unless the switch @emph{-nostdlib} is
16193 specified. See @ref{87,,Installing a library}
16194 @end itemize
16196 @geindex -I (gnatbind)
16198 @geindex -aI (gnatbind)
16200 @geindex -aO (gnatbind)
16202 In the binder the switch @emph{-I}
16203 is used to specify both source and
16204 library file paths. Use @emph{-aI}
16205 instead if you want to specify
16206 source paths only, and @emph{-aO}
16207 if you want to specify library paths
16208 only. This means that for the binder
16209 @code{-I@emph{dir}} is equivalent to
16210 @code{-aI@emph{dir}}
16211 @code{-aO`@emph{dir}}.
16212 The binder generates the bind file (a C language source file) in the
16213 current working directory.
16215 @geindex Ada
16217 @geindex System
16219 @geindex Interfaces
16221 @geindex GNAT
16223 The packages @cite{Ada}, @cite{System}, and @cite{Interfaces} and their
16224 children make up the GNAT Run-Time Library, together with the package
16225 GNAT and its children, which contain a set of useful additional
16226 library functions provided by GNAT. The sources for these units are
16227 needed by the compiler and are kept together in one directory. The ALI
16228 files and object files generated by compiling the RTL are needed by the
16229 binder and the linker and are kept together in one directory, typically
16230 different from the directory containing the sources. In a normal
16231 installation, you need not specify these directory names when compiling
16232 or binding. Either the environment variables or the built-in defaults
16233 cause these files to be found.
16235 Besides simplifying access to the RTL, a major use of search paths is
16236 in compiling sources from multiple directories. This can make
16237 development environments much more flexible.
16239 @node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16240 @anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatbind-usage}@anchor{12f}@anchor{gnat_ugn/building_executable_programs_with_gnat id43}@anchor{130}
16241 @subsection Examples of @cite{gnatbind} Usage
16244 Here are some examples of @cite{gnatbind} invovations:
16246 @quotation
16248 @example
16249 gnatbind hello
16250 @end example
16252 The main program @cite{Hello} (source program in @code{hello.adb}) is
16253 bound using the standard switch settings. The generated main program is
16254 @code{b~hello.adb}. This is the normal, default use of the binder.
16256 @example
16257 gnatbind hello -o mainprog.adb
16258 @end example
16260 The main program @cite{Hello} (source program in @code{hello.adb}) is
16261 bound using the standard switch settings. The generated main program is
16262 @code{mainprog.adb} with the associated spec in
16263 @code{mainprog.ads}. Note that you must specify the body here not the
16264 spec. Note that if this option is used, then linking must be done manually,
16265 since gnatlink will not be able to find the generated file.
16266 @end quotation
16268 @node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16269 @anchor{gnat_ugn/building_executable_programs_with_gnat id44}@anchor{131}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{1e}
16270 @section Linking with @emph{gnatlink}
16273 @geindex gnatlink
16275 This chapter discusses @emph{gnatlink}, a tool that links
16276 an Ada program and builds an executable file. This utility
16277 invokes the system linker (via the @emph{gcc} command)
16278 with a correct list of object files and library references.
16279 @emph{gnatlink} automatically determines the list of files and
16280 references for the Ada part of a program. It uses the binder file
16281 generated by the @emph{gnatbind} to determine this list.
16283 Note: to invoke @cite{gnatlink} with a project file, use the @cite{gnat}
16284 driver (see @emph{The_GNAT_Driver_and_Project_Files}).
16286 @menu
16287 * Running gnatlink:: 
16288 * Switches for gnatlink:: 
16290 @end menu
16292 @node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16293 @anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{132}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{133}
16294 @subsection Running @emph{gnatlink}
16297 The form of the @emph{gnatlink} command is
16299 @example
16300 $ gnatlink [`switches`] `mainprog`[.ali]
16301            [`non-Ada objects`] [`linker options`]
16302 @end example
16304 The arguments of @emph{gnatlink} (switches, main @code{ALI} file,
16305 non-Ada objects
16306 or linker options) may be in any order, provided that no non-Ada object may
16307 be mistaken for a main @code{ALI} file.
16308 Any file name @code{F} without the @code{.ali}
16309 extension will be taken as the main @code{ALI} file if a file exists
16310 whose name is the concatenation of @code{F} and @code{.ali}.
16312 @code{mainprog.ali} references the ALI file of the main program.
16313 The @code{.ali} extension of this file can be omitted. From this
16314 reference, @emph{gnatlink} locates the corresponding binder file
16315 @code{b~mainprog.adb} and, using the information in this file along
16316 with the list of non-Ada objects and linker options, constructs a
16317 linker command file to create the executable.
16319 The arguments other than the @emph{gnatlink} switches and the main
16320 @code{ALI} file are passed to the linker uninterpreted.
16321 They typically include the names of
16322 object files for units written in other languages than Ada and any library
16323 references required to resolve references in any of these foreign language
16324 units, or in @cite{Import} pragmas in any Ada units.
16326 @cite{linker options} is an optional list of linker specific
16327 switches.
16328 The default linker called by gnatlink is @emph{gcc} which in
16329 turn calls the appropriate system linker.
16331 One useful option for the linker is @emph{-s}: it reduces the size of the
16332 executable by removing all symbol table and relocation information from the
16333 executable.
16335 Standard options for the linker such as @emph{-lmy_lib} or
16336 @emph{-Ldir} can be added as is.
16337 For options that are not recognized by
16338 @emph{gcc} as linker options, use the @emph{gcc} switches
16339 @emph{-Xlinker} or @emph{-Wl,}.
16341 Refer to the GCC documentation for
16342 details.
16344 Here is an example showing how to generate a linker map:
16346 @example
16347 $ gnatlink my_prog -Wl,-Map,MAPFILE
16348 @end example
16350 Using @cite{linker options} it is possible to set the program stack and
16351 heap size.
16352 See @ref{134,,Setting Stack Size from gnatlink} and
16353 @ref{135,,Setting Heap Size from gnatlink}.
16355 @emph{gnatlink} determines the list of objects required by the Ada
16356 program and prepends them to the list of objects passed to the linker.
16357 @emph{gnatlink} also gathers any arguments set by the use of
16358 @cite{pragma Linker_Options} and adds them to the list of arguments
16359 presented to the linker.
16361 @node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
16362 @anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{136}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{137}
16363 @subsection Switches for @emph{gnatlink}
16366 The following switches are available with the @emph{gnatlink} utility:
16368 @geindex --version (gnatlink)
16371 @table @asis
16373 @item @code{--version}
16375 Display Copyright and version, then exit disregarding all other options.
16376 @end table
16378 @geindex --help (gnatlink)
16381 @table @asis
16383 @item @code{--help}
16385 If @emph{--version} was not used, display usage, then exit disregarding
16386 all other options.
16387 @end table
16389 @geindex Command line length
16391 @geindex -f (gnatlink)
16394 @table @asis
16396 @item @code{-f}
16398 On some targets, the command line length is limited, and @emph{gnatlink}
16399 will generate a separate file for the linker if the list of object files
16400 is too long.
16401 The @emph{-f} switch forces this file
16402 to be generated even if
16403 the limit is not exceeded. This is useful in some cases to deal with
16404 special situations where the command line length is exceeded.
16405 @end table
16407 @geindex Debugging information
16408 @geindex including
16410 @geindex -g (gnatlink)
16413 @table @asis
16415 @item @code{-g}
16417 The option to include debugging information causes the Ada bind file (in
16418 other words, @code{b~mainprog.adb}) to be compiled with @emph{-g}.
16419 In addition, the binder does not delete the @code{b~mainprog.adb},
16420 @code{b~mainprog.o} and @code{b~mainprog.ali} files.
16421 Without @emph{-g}, the binder removes these files by default.
16422 @end table
16424 @geindex -n (gnatlink)
16427 @table @asis
16429 @item @code{-n}
16431 Do not compile the file generated by the binder. This may be used when
16432 a link is rerun with different options, but there is no need to recompile
16433 the binder file.
16434 @end table
16436 @geindex -v (gnatlink)
16439 @table @asis
16441 @item @code{-v}
16443 Verbose mode. Causes additional information to be output, including a full
16444 list of the included object files.
16445 This switch option is most useful when you want
16446 to see what set of object files are being used in the link step.
16447 @end table
16449 @geindex -v -v (gnatlink)
16452 @table @asis
16454 @item @code{-v -v}
16456 Very verbose mode. Requests that the compiler operate in verbose mode when
16457 it compiles the binder file, and that the system linker run in verbose mode.
16458 @end table
16460 @geindex -o (gnatlink)
16463 @table @asis
16465 @item @code{-o @emph{exec-name}}
16467 @cite{exec-name} specifies an alternate name for the generated
16468 executable program. If this switch is omitted, the executable has the same
16469 name as the main unit. For example, @cite{gnatlink try.ali} creates
16470 an executable called @code{try}.
16471 @end table
16473 @geindex -b (gnatlink)
16476 @table @asis
16478 @item @code{-b @emph{target}}
16480 Compile your program to run on @cite{target}, which is the name of a
16481 system configuration. You must have a GNAT cross-compiler built if
16482 @cite{target} is not the same as your host system.
16483 @end table
16485 @geindex -B (gnatlink)
16488 @table @asis
16490 @item @code{-B@emph{dir}}
16492 Load compiler executables (for example, @cite{gnat1}, the Ada compiler)
16493 from @cite{dir} instead of the default location. Only use this switch
16494 when multiple versions of the GNAT compiler are available.
16495 See the @cite{Directory Options} section in @cite{The_GNU_Compiler_Collection}
16496 for further details. You would normally use the @emph{-b} or
16497 @emph{-V} switch instead.
16498 @end table
16500 @geindex -M (gnatlink)
16503 @table @asis
16505 @item @code{-M}
16507 When linking an executable, create a map file. The name of the map file
16508 has the same name as the executable with extension ".map".
16509 @end table
16511 @geindex -M= (gnatlink)
16514 @table @asis
16516 @item @code{-M=@emph{mapfile}}
16518 When linking an executable, create a map file. The name of the map file is
16519 @cite{mapfile}.
16520 @end table
16522 @geindex --GCC=compiler_name (gnatlink)
16525 @table @asis
16527 @item @code{--GCC=@emph{compiler_name}}
16529 Program used for compiling the binder file. The default is
16530 @code{gcc}. You need to use quotes around @cite{compiler_name} if
16531 @cite{compiler_name} contains spaces or other separator characters.
16532 As an example @code{--GCC="foo -x -y"} will instruct @emph{gnatlink} to
16533 use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
16534 inserted after your command name. Thus in the above example the compiler
16535 command that will be used by @emph{gnatlink} will be @code{foo -c -x -y}.
16536 A limitation of this syntax is that the name and path name of the executable
16537 itself must not include any embedded spaces. If the compiler executable is
16538 different from the default one (gcc or <prefix>-gcc), then the back-end
16539 switches in the ALI file are not used to compile the binder generated source.
16540 For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
16541 switches will be used for @code{--GCC="gcc -gnatv"}. If several
16542 @code{--GCC=compiler_name} are used, only the last @cite{compiler_name}
16543 is taken into account. However, all the additional switches are also taken
16544 into account. Thus,
16545 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
16546 @code{--GCC="bar -x -y -z -t"}.
16547 @end table
16549 @geindex --LINK= (gnatlink)
16552 @table @asis
16554 @item @code{--LINK=@emph{name}}
16556 @cite{name} is the name of the linker to be invoked. This is especially
16557 useful in mixed language programs since languages such as C++ require
16558 their own linker to be used. When this switch is omitted, the default
16559 name for the linker is @emph{gcc}. When this switch is used, the
16560 specified linker is called instead of @emph{gcc} with exactly the same
16561 parameters that would have been passed to @emph{gcc} so if the desired
16562 linker requires different parameters it is necessary to use a wrapper
16563 script that massages the parameters before invoking the real linker. It
16564 may be useful to control the exact invocation by using the verbose
16565 switch.
16566 @end table
16568 @node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
16569 @anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{138}@anchor{gnat_ugn/building_executable_programs_with_gnat using-the-gnu-make-utility}@anchor{1f}
16570 @section Using the GNU @cite{make} Utility
16573 @geindex make (GNU)
16574 @geindex GNU make
16576 This chapter offers some examples of makefiles that solve specific
16577 problems. It does not explain how to write a makefile, nor does it try to replace the
16578 @emph{gnatmake} utility (@ref{1b,,Building with gnatmake}).
16580 All the examples in this section are specific to the GNU version of
16581 make. Although @emph{make} is a standard utility, and the basic language
16582 is the same, these examples use some advanced features found only in
16583 @cite{GNU make}.
16585 @menu
16586 * Using gnatmake in a Makefile:: 
16587 * Automatically Creating a List of Directories:: 
16588 * Generating the Command Line Switches:: 
16589 * Overcoming Command Line Length Limits:: 
16591 @end menu
16593 @node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
16594 @anchor{gnat_ugn/building_executable_programs_with_gnat using-gnatmake-in-a-makefile}@anchor{139}@anchor{gnat_ugn/building_executable_programs_with_gnat id48}@anchor{13a}
16595 @subsection Using gnatmake in a Makefile
16598 @c index makefile (GNU make)
16600 Complex project organizations can be handled in a very powerful way by
16601 using GNU make combined with gnatmake. For instance, here is a Makefile
16602 which allows you to build each subsystem of a big project into a separate
16603 shared library. Such a makefile allows you to significantly reduce the link
16604 time of very big applications while maintaining full coherence at
16605 each step of the build process.
16607 The list of dependencies are handled automatically by
16608 @emph{gnatmake}. The Makefile is simply used to call gnatmake in each of
16609 the appropriate directories.
16611 Note that you should also read the example on how to automatically
16612 create the list of directories
16613 (@ref{13b,,Automatically Creating a List of Directories})
16614 which might help you in case your project has a lot of subdirectories.
16616 @example
16617 ## This Makefile is intended to be used with the following directory
16618 ## configuration:
16619 ##  - The sources are split into a series of csc (computer software components)
16620 ##    Each of these csc is put in its own directory.
16621 ##    Their name are referenced by the directory names.
16622 ##    They will be compiled into shared library (although this would also work
16623 ##    with static libraries
16624 ##  - The main program (and possibly other packages that do not belong to any
16625 ##    csc is put in the top level directory (where the Makefile is).
16626 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16627 ##                    \\_ second_csc (sources) __ lib (will contain the library)
16628 ##                    \\_ ...
16629 ## Although this Makefile is build for shared library, it is easy to modify
16630 ## to build partial link objects instead (modify the lines with -shared and
16631 ## gnatlink below)
16633 ## With this makefile, you can change any file in the system or add any new
16634 ## file, and everything will be recompiled correctly (only the relevant shared
16635 ## objects will be recompiled, and the main program will be re-linked).
16637 # The list of computer software component for your project. This might be
16638 # generated automatically.
16639 CSC_LIST=aa bb cc
16641 # Name of the main program (no extension)
16642 MAIN=main
16644 # If we need to build objects with -fPIC, uncomment the following line
16645 #NEED_FPIC=-fPIC
16647 # The following variable should give the directory containing libgnat.so
16648 # You can get this directory through 'gnatls -v'. This is usually the last
16649 # directory in the Object_Path.
16650 GLIB=...
16652 # The directories for the libraries
16653 # (This macro expands the list of CSC to the list of shared libraries, you
16654 # could simply use the expanded form:
16655 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16656 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16658 $@{MAIN@}: objects $@{LIB_DIR@}
16659     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16660     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16662 objects::
16663     # recompile the sources
16664     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16666 # Note: In a future version of GNAT, the following commands will be simplified
16667 # by a new tool, gnatmlib
16668 $@{LIB_DIR@}:
16669     mkdir -p $@{dir $@@ @}
16670     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16671     cd $@{dir $@@ @} && cp -f ../*.ali .
16673 # The dependencies for the modules
16674 # Note that we have to force the expansion of *.o, since in some cases
16675 # make won't be able to do it itself.
16676 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16677 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16678 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16680 # Make sure all of the shared libraries are in the path before starting the
16681 # program
16682 run::
16683     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16685 clean::
16686     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16687     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16688     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16689     $@{RM@} *.o *.ali $@{MAIN@}
16690 @end example
16692 @node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
16693 @anchor{gnat_ugn/building_executable_programs_with_gnat automatically-creating-a-list-of-directories}@anchor{13b}@anchor{gnat_ugn/building_executable_programs_with_gnat id49}@anchor{13c}
16694 @subsection Automatically Creating a List of Directories
16697 In most makefiles, you will have to specify a list of directories, and
16698 store it in a variable. For small projects, it is often easier to
16699 specify each of them by hand, since you then have full control over what
16700 is the proper order for these directories, which ones should be
16701 included.
16703 However, in larger projects, which might involve hundreds of
16704 subdirectories, it might be more convenient to generate this list
16705 automatically.
16707 The example below presents two methods. The first one, although less
16708 general, gives you more control over the list. It involves wildcard
16709 characters, that are automatically expanded by @emph{make}. Its
16710 shortcoming is that you need to explicitly specify some of the
16711 organization of your project, such as for instance the directory tree
16712 depth, whether some directories are found in a separate tree, etc.
16714 The second method is the most general one. It requires an external
16715 program, called @emph{find}, which is standard on all Unix systems. All
16716 the directories found under a given root directory will be added to the
16717 list.
16719 @example
16720 # The examples below are based on the following directory hierarchy:
16721 # All the directories can contain any number of files
16722 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16723 #                       ->  ab
16724 #                       ->  ac
16725 #                ->  b  ->  ba  ->  baa
16726 #                       ->  bb
16727 #                       ->  bc
16728 # This Makefile creates a variable called DIRS, that can be reused any time
16729 # you need this list (see the other examples in this section)
16731 # The root of your project's directory hierarchy
16732 ROOT_DIRECTORY=.
16734 ####
16735 # First method: specify explicitly the list of directories
16736 # This allows you to specify any subset of all the directories you need.
16737 ####
16739 DIRS := a/aa/ a/ab/ b/ba/
16741 ####
16742 # Second method: use wildcards
16743 # Note that the argument(s) to wildcard below should end with a '/'.
16744 # Since wildcards also return file names, we have to filter them out
16745 # to avoid duplicate directory names.
16746 # We thus use make's `dir` and `sort` functions.
16747 # It sets DIRs to the following value (note that the directories aaa and baa
16748 # are not given, unless you change the arguments to wildcard).
16749 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16750 ####
16752 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16753                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16755 ####
16756 # Third method: use an external program
16757 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16758 # This is the most complete command: it sets DIRs to the following value:
16759 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16760 ####
16762 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16763 @end example
16765 @node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
16766 @anchor{gnat_ugn/building_executable_programs_with_gnat id50}@anchor{13d}@anchor{gnat_ugn/building_executable_programs_with_gnat generating-the-command-line-switches}@anchor{13e}
16767 @subsection Generating the Command Line Switches
16770 Once you have created the list of directories as explained in the
16771 previous section (@ref{13b,,Automatically Creating a List of Directories}),
16772 you can easily generate the command line arguments to pass to gnatmake.
16774 For the sake of completeness, this example assumes that the source path
16775 is not the same as the object path, and that you have two separate lists
16776 of directories.
16778 @example
16779 # see "Automatically creating a list of directories" to create
16780 # these variables
16781 SOURCE_DIRS=
16782 OBJECT_DIRS=
16784 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16785 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16787 all:
16788         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16789 @end example
16791 @node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
16792 @anchor{gnat_ugn/building_executable_programs_with_gnat overcoming-command-line-length-limits}@anchor{13f}@anchor{gnat_ugn/building_executable_programs_with_gnat id51}@anchor{140}
16793 @subsection Overcoming Command Line Length Limits
16796 One problem that might be encountered on big projects is that many
16797 operating systems limit the length of the command line. It is thus hard to give
16798 gnatmake the list of source and object directories.
16800 This example shows how you can set up environment variables, which will
16801 make @emph{gnatmake} behave exactly as if the directories had been
16802 specified on the command line, but have a much higher length limit (or
16803 even none on most systems).
16805 It assumes that you have created a list of directories in your Makefile,
16806 using one of the methods presented in
16807 @ref{13b,,Automatically Creating a List of Directories}.
16808 For the sake of completeness, we assume that the object
16809 path (where the ALI files are found) is different from the sources patch.
16811 Note a small trick in the Makefile below: for efficiency reasons, we
16812 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16813 expanded immediately by @cite{make}. This way we overcome the standard
16814 make behavior which is to expand the variables only when they are
16815 actually used.
16817 On Windows, if you are using the standard Windows command shell, you must
16818 replace colons with semicolons in the assignments to these variables.
16820 @example
16821 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
16822 # This is the same thing as putting the -I arguments on the command line.
16823 # (the equivalent of using -aI on the command line would be to define
16824 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
16825 # You can of course have different values for these variables.
16827 # Note also that we need to keep the previous values of these variables, since
16828 # they might have been set before running 'make' to specify where the GNAT
16829 # library is installed.
16831 # see "Automatically creating a list of directories" to create these
16832 # variables
16833 SOURCE_DIRS=
16834 OBJECT_DIRS=
16836 empty:=
16837 space:=$@{empty@} $@{empty@}
16838 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16839 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16840 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16841 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
16842 export ADA_INCLUDE_PATH
16843 export ADA_OBJECTS_PATH
16845 all:
16846         gnatmake main_unit
16847 @end example
16849 @node GNAT Utility Programs,GNAT and Program Execution,Building Executable Programs with GNAT,Top
16850 @anchor{gnat_ugn/gnat_utility_programs doc}@anchor{141}@anchor{gnat_ugn/gnat_utility_programs gnat-utility-programs}@anchor{b}@anchor{gnat_ugn/gnat_utility_programs id1}@anchor{142}
16851 @chapter GNAT Utility Programs
16854 This chapter describes a number of utility programs:
16858 @itemize *
16860 @item 
16861 @ref{20,,The File Cleanup Utility gnatclean}
16863 @item 
16864 @ref{21,,The GNAT Library Browser gnatls}
16866 @item 
16867 @ref{22,,The Cross-Referencing Tools gnatxref and gnatfind}
16869 @item 
16870 @ref{23,,The Ada to HTML Converter gnathtml}
16871 @end itemize
16873 Other GNAT utilities are described elsewhere in this manual:
16876 @itemize *
16878 @item 
16879 @ref{59,,Handling Arbitrary File Naming Conventions with gnatname}
16881 @item 
16882 @ref{63,,File Name Krunching with gnatkr}
16884 @item 
16885 @ref{36,,Renaming Files with gnatchop}
16887 @item 
16888 @ref{17,,Preprocessing with gnatprep}
16889 @end itemize
16891 @menu
16892 * The File Cleanup Utility gnatclean:: 
16893 * The GNAT Library Browser gnatls:: 
16894 * The Cross-Referencing Tools gnatxref and gnatfind:: 
16895 * The Ada to HTML Converter gnathtml:: 
16897 @end menu
16899 @node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
16900 @anchor{gnat_ugn/gnat_utility_programs id2}@anchor{143}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{20}
16901 @section The File Cleanup Utility @emph{gnatclean}
16904 @geindex File cleanup tool
16906 @geindex gnatclean
16908 @cite{gnatclean} is a tool that allows the deletion of files produced by the
16909 compiler, binder and linker, including ALI files, object files, tree files,
16910 expanded source files, library files, interface copy source files, binder
16911 generated files and executable files.
16913 @menu
16914 * Running gnatclean:: 
16915 * Switches for gnatclean:: 
16917 @end menu
16919 @node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
16920 @anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{144}@anchor{gnat_ugn/gnat_utility_programs id3}@anchor{145}
16921 @subsection Running @cite{gnatclean}
16924 The @cite{gnatclean} command has the form:
16926 @quotation
16928 @example
16929 $ gnatclean switches `names`
16930 @end example
16931 @end quotation
16933 where @cite{names} is a list of source file names. Suffixes @code{.ads} and
16934 @code{adb} may be omitted. If a project file is specified using switch
16935 @code{-P}, then @cite{names} may be completely omitted.
16937 In normal mode, @cite{gnatclean} delete the files produced by the compiler and,
16938 if switch @cite{-c} is not specified, by the binder and
16939 the linker. In informative-only mode, specified by switch
16940 @cite{-n}, the list of files that would have been deleted in
16941 normal mode is listed, but no file is actually deleted.
16943 @node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
16944 @anchor{gnat_ugn/gnat_utility_programs id4}@anchor{146}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{147}
16945 @subsection Switches for @cite{gnatclean}
16948 @cite{gnatclean} recognizes the following switches:
16950 @geindex --version (gnatclean)
16953 @table @asis
16955 @item @code{--version}
16957 Display Copyright and version, then exit disregarding all other options.
16958 @end table
16960 @geindex --help (gnatclean)
16963 @table @asis
16965 @item @code{--help}
16967 If @emph{--version} was not used, display usage, then exit disregarding
16968 all other options.
16970 @item @code{--subdirs=@emph{subdir}}
16972 Actual object directory of each project file is the subdirectory subdir of the
16973 object directory specified or defaulted in the project file.
16975 @item @code{--unchecked-shared-lib-imports}
16977 By default, shared library projects are not allowed to import static library
16978 projects. When this switch is used on the command line, this restriction is
16979 relaxed.
16980 @end table
16982 @geindex -c (gnatclean)
16985 @table @asis
16987 @item @code{-c}
16989 Only attempt to delete the files produced by the compiler, not those produced
16990 by the binder or the linker. The files that are not to be deleted are library
16991 files, interface copy files, binder generated files and executable files.
16992 @end table
16994 @geindex -D (gnatclean)
16997 @table @asis
16999 @item @code{-D @emph{dir}}
17001 Indicate that ALI and object files should normally be found in directory @cite{dir}.
17002 @end table
17004 @geindex -F (gnatclean)
17007 @table @asis
17009 @item @code{-F}
17011 When using project files, if some errors or warnings are detected during
17012 parsing and verbose mode is not in effect (no use of switch
17013 -v), then error lines start with the full path name of the project
17014 file, rather than its simple file name.
17015 @end table
17017 @geindex -h (gnatclean)
17020 @table @asis
17022 @item @code{-h}
17024 Output a message explaining the usage of @cite{gnatclean}.
17025 @end table
17027 @geindex -n (gnatclean)
17030 @table @asis
17032 @item @code{-n}
17034 Informative-only mode. Do not delete any files. Output the list of the files
17035 that would have been deleted if this switch was not specified.
17036 @end table
17038 @geindex -P (gnatclean)
17041 @table @asis
17043 @item @code{-P@emph{project}}
17045 Use project file @cite{project}. Only one such switch can be used.
17046 When cleaning a project file, the files produced by the compilation of the
17047 immediate sources or inherited sources of the project files are to be
17048 deleted. This is not depending on the presence or not of executable names
17049 on the command line.
17050 @end table
17052 @geindex -q (gnatclean)
17055 @table @asis
17057 @item @code{-q}
17059 Quiet output. If there are no errors, do not output anything, except in
17060 verbose mode (switch -v) or in informative-only mode
17061 (switch -n).
17062 @end table
17064 @geindex -r (gnatclean)
17067 @table @asis
17069 @item @code{-r}
17071 When a project file is specified (using switch -P),
17072 clean all imported and extended project files, recursively. If this switch
17073 is not specified, only the files related to the main project file are to be
17074 deleted. This switch has no effect if no project file is specified.
17075 @end table
17077 @geindex -v (gnatclean)
17080 @table @asis
17082 @item @code{-v}
17084 Verbose mode.
17085 @end table
17087 @geindex -vP (gnatclean)
17090 @table @asis
17092 @item @code{-vP@emph{x}}
17094 Indicates the verbosity of the parsing of GNAT project files.
17095 @ref{de,,Switches Related to Project Files}.
17096 @end table
17098 @geindex -X (gnatclean)
17101 @table @asis
17103 @item @code{-X@emph{name}=@emph{value}}
17105 Indicates that external variable @cite{name} has the value @cite{value}.
17106 The Project Manager will use this value for occurrences of
17107 @cite{external(name)} when parsing the project file.
17108 @ref{de,,Switches Related to Project Files}.
17109 @end table
17111 @geindex -aO (gnatclean)
17114 @table @asis
17116 @item @code{-aO@emph{dir}}
17118 When searching for ALI and object files, look in directory @cite{dir}.
17119 @end table
17121 @geindex -I (gnatclean)
17124 @table @asis
17126 @item @code{-I@emph{dir}}
17128 Equivalent to @code{-aO@emph{dir}}.
17129 @end table
17131 @geindex -I- (gnatclean)
17133 @geindex Source files
17134 @geindex suppressing search
17137 @table @asis
17139 @item @code{-I-}
17141 Do not look for ALI or object files in the directory
17142 where @cite{gnatclean} was invoked.
17143 @end table
17145 @node The GNAT Library Browser gnatls,The Cross-Referencing Tools gnatxref and gnatfind,The File Cleanup Utility gnatclean,GNAT Utility Programs
17146 @anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{21}@anchor{gnat_ugn/gnat_utility_programs id5}@anchor{148}
17147 @section The GNAT Library Browser @cite{gnatls}
17150 @geindex Library browser
17152 @geindex gnatls
17154 @cite{gnatls} is a tool that outputs information about compiled
17155 units. It gives the relationship between objects, unit names and source
17156 files. It can also be used to check the source dependencies of a unit
17157 as well as various characteristics.
17159 Note: to invoke @cite{gnatls} with a project file, use the @cite{gnat}
17160 driver (see @emph{The_GNAT_Driver_and_Project_Files}).
17162 @menu
17163 * Running gnatls:: 
17164 * Switches for gnatls:: 
17165 * Example of gnatls Usage:: 
17167 @end menu
17169 @node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
17170 @anchor{gnat_ugn/gnat_utility_programs id6}@anchor{149}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{14a}
17171 @subsection Running @cite{gnatls}
17174 The @cite{gnatls} command has the form
17176 @quotation
17178 @example
17179 $ gnatls switches `object_or_ali_file`
17180 @end example
17181 @end quotation
17183 The main argument is the list of object or @code{ali} files
17184 (see @ref{42,,The Ada Library Information Files})
17185 for which information is requested.
17187 In normal mode, without additional option, @cite{gnatls} produces a
17188 four-column listing. Each line represents information for a specific
17189 object. The first column gives the full path of the object, the second
17190 column gives the name of the principal unit in this object, the third
17191 column gives the status of the source and the fourth column gives the
17192 full path of the source representing this unit.
17193 Here is a simple example of use:
17195 @quotation
17197 @example
17198 $ gnatls *.o
17199 ./demo1.o            demo1            DIF demo1.adb
17200 ./demo2.o            demo2             OK demo2.adb
17201 ./hello.o            h1                OK hello.adb
17202 ./instr-child.o      instr.child      MOK instr-child.adb
17203 ./instr.o            instr             OK instr.adb
17204 ./tef.o              tef              DIF tef.adb
17205 ./text_io_example.o  text_io_example   OK text_io_example.adb
17206 ./tgef.o             tgef             DIF tgef.adb
17207 @end example
17208 @end quotation
17210 The first line can be interpreted as follows: the main unit which is
17211 contained in
17212 object file @code{demo1.o} is demo1, whose main source is in
17213 @code{demo1.adb}. Furthermore, the version of the source used for the
17214 compilation of demo1 has been modified (DIF). Each source file has a status
17215 qualifier which can be:
17218 @table @asis
17220 @item @emph{OK (unchanged)}
17222 The version of the source file used for the compilation of the
17223 specified unit corresponds exactly to the actual source file.
17225 @item @emph{MOK (slightly modified)}
17227 The version of the source file used for the compilation of the
17228 specified unit differs from the actual source file but not enough to
17229 require recompilation. If you use gnatmake with the qualifier
17230 @emph{-m (minimal recompilation)}, a file marked
17231 MOK will not be recompiled.
17233 @item @emph{DIF (modified)}
17235 No version of the source found on the path corresponds to the source
17236 used to build this object.
17238 @item @emph{??? (file not found)}
17240 No source file was found for this unit.
17242 @item @emph{HID (hidden,  unchanged version not first on PATH)}
17244 The version of the source that corresponds exactly to the source used
17245 for compilation has been found on the path but it is hidden by another
17246 version of the same source that has been modified.
17247 @end table
17249 @node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
17250 @anchor{gnat_ugn/gnat_utility_programs id7}@anchor{14b}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{14c}
17251 @subsection Switches for @cite{gnatls}
17254 @cite{gnatls} recognizes the following switches:
17256 @geindex --version (gnatls)
17259 @table @asis
17261 @item @code{--version}
17263 Display Copyright and version, then exit disregarding all other options.
17264 @end table
17266 @geindex --help (gnatls)
17269 @table @asis
17271 @item @code{*--help}
17273 If @emph{--version} was not used, display usage, then exit disregarding
17274 all other options.
17275 @end table
17277 @geindex -a (gnatls)
17280 @table @asis
17282 @item @code{-a}
17284 Consider all units, including those of the predefined Ada library.
17285 Especially useful with @emph{-d}.
17286 @end table
17288 @geindex -d (gnatls)
17291 @table @asis
17293 @item @code{-d}
17295 List sources from which specified units depend on.
17296 @end table
17298 @geindex -h (gnatls)
17301 @table @asis
17303 @item @code{-h}
17305 Output the list of options.
17306 @end table
17308 @geindex -o (gnatls)
17311 @table @asis
17313 @item @code{-o}
17315 Only output information about object files.
17316 @end table
17318 @geindex -s (gnatls)
17321 @table @asis
17323 @item @code{-s}
17325 Only output information about source files.
17326 @end table
17328 @geindex -u (gnatls)
17331 @table @asis
17333 @item @code{-u}
17335 Only output information about compilation units.
17336 @end table
17338 @geindex -files (gnatls)
17341 @table @asis
17343 @item @code{-files=@emph{file}}
17345 Take as arguments the files listed in text file @cite{file}.
17346 Text file @cite{file} may contain empty lines that are ignored.
17347 Each nonempty line should contain the name of an existing file.
17348 Several such switches may be specified simultaneously.
17349 @end table
17351 @geindex -aO (gnatls)
17353 @geindex -aI (gnatls)
17355 @geindex -I (gnatls)
17357 @geindex -I- (gnatls)
17360 @table @asis
17362 @item @code{-aO@emph{dir}}, @code{-aI@emph{dir}}, @code{-I@emph{dir}}, @code{-I-}, @code{-nostdinc}
17364 Source path manipulation. Same meaning as the equivalent @emph{gnatmake}
17365 flags (@ref{dc,,Switches for gnatmake}).
17366 @end table
17368 @geindex -aP (gnatls)
17371 @table @asis
17373 @item @code{-aP@emph{dir}}
17375 Add @cite{dir} at the beginning of the project search dir.
17376 @end table
17378 @geindex --RTS (gnatls)
17381 @table @asis
17383 @item @code{--RTS=@emph{rts-path}`}
17385 Specifies the default location of the runtime library. Same meaning as the
17386 equivalent @emph{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
17387 @end table
17389 @geindex -v (gnatls)
17392 @table @asis
17394 @item @code{-v}
17396 Verbose mode. Output the complete source, object and project paths. Do not use
17397 the default column layout but instead use long format giving as much as
17398 information possible on each requested units, including special
17399 characteristics such as:
17402 @itemize *
17404 @item 
17405 @emph{Preelaborable}: The unit is preelaborable in the Ada sense.
17407 @item 
17408 @emph{No_Elab_Code}:  No elaboration code has been produced by the compiler for this unit.
17410 @item 
17411 @emph{Pure}: The unit is pure in the Ada sense.
17413 @item 
17414 @emph{Elaborate_Body}: The unit contains a pragma Elaborate_Body.
17416 @item 
17417 @emph{Remote_Types}: The unit contains a pragma Remote_Types.
17419 @item 
17420 @emph{Shared_Passive}: The unit contains a pragma Shared_Passive.
17422 @item 
17423 @emph{Predefined}: This unit is part of the predefined environment and cannot be modified
17424 by the user.
17426 @item 
17427 @emph{Remote_Call_Interface}: The unit contains a pragma Remote_Call_Interface.
17428 @end itemize
17429 @end table
17431 @node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
17432 @anchor{gnat_ugn/gnat_utility_programs id8}@anchor{14d}@anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{14e}
17433 @subsection Example of @cite{gnatls} Usage
17436 Example of using the verbose switch. Note how the source and
17437 object paths are affected by the -I switch.
17439 @quotation
17441 @example
17442 $ gnatls -v -I.. demo1.o
17444 GNATLS 5.03w (20041123-34)
17445 Copyright 1997-2004 Free Software Foundation, Inc.
17447 Source Search Path:
17448    <Current_Directory>
17449    ../
17450    /home/comar/local/adainclude/
17452 Object Search Path:
17453    <Current_Directory>
17454    ../
17455    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17457 Project Search Path:
17458    <Current_Directory>
17459    /home/comar/local/lib/gnat/
17461 ./demo1.o
17462    Unit =>
17463      Name   => demo1
17464      Kind   => subprogram body
17465      Flags  => No_Elab_Code
17466      Source => demo1.adb    modified
17467 @end example
17468 @end quotation
17470 The following is an example of use of the dependency list.
17471 Note the use of the -s switch
17472 which gives a straight list of source files. This can be useful for
17473 building specialized scripts.
17475 @quotation
17477 @example
17478 $ gnatls -d demo2.o
17479 ./demo2.o   demo2        OK demo2.adb
17480                          OK gen_list.ads
17481                          OK gen_list.adb
17482                          OK instr.ads
17483                          OK instr-child.ads
17485 $ gnatls -d -s -a demo1.o
17486 demo1.adb
17487 /home/comar/local/adainclude/ada.ads
17488 /home/comar/local/adainclude/a-finali.ads
17489 /home/comar/local/adainclude/a-filico.ads
17490 /home/comar/local/adainclude/a-stream.ads
17491 /home/comar/local/adainclude/a-tags.ads
17492 gen_list.ads
17493 gen_list.adb
17494 /home/comar/local/adainclude/gnat.ads
17495 /home/comar/local/adainclude/g-io.ads
17496 instr.ads
17497 /home/comar/local/adainclude/system.ads
17498 /home/comar/local/adainclude/s-exctab.ads
17499 /home/comar/local/adainclude/s-finimp.ads
17500 /home/comar/local/adainclude/s-finroo.ads
17501 /home/comar/local/adainclude/s-secsta.ads
17502 /home/comar/local/adainclude/s-stalib.ads
17503 /home/comar/local/adainclude/s-stoele.ads
17504 /home/comar/local/adainclude/s-stratt.ads
17505 /home/comar/local/adainclude/s-tasoli.ads
17506 /home/comar/local/adainclude/s-unstyp.ads
17507 /home/comar/local/adainclude/unchconv.ads
17508 @end example
17509 @end quotation
17511 @node The Cross-Referencing Tools gnatxref and gnatfind,The Ada to HTML Converter gnathtml,The GNAT Library Browser gnatls,GNAT Utility Programs
17512 @anchor{gnat_ugn/gnat_utility_programs the-cross-referencing-tools-gnatxref-and-gnatfind}@anchor{22}@anchor{gnat_ugn/gnat_utility_programs id9}@anchor{14f}
17513 @section The Cross-Referencing Tools @cite{gnatxref} and @cite{gnatfind}
17516 @geindex gnatxref
17518 @geindex gnatfind
17520 The compiler generates cross-referencing information (unless
17521 you set the @code{-gnatx} switch), which are saved in the @code{.ali} files.
17522 This information indicates where in the source each entity is declared and
17523 referenced. Note that entities in package Standard are not included, but
17524 entities in all other predefined units are included in the output.
17526 Before using any of these two tools, you need to compile successfully your
17527 application, so that GNAT gets a chance to generate the cross-referencing
17528 information.
17530 The two tools @cite{gnatxref} and @cite{gnatfind} take advantage of this
17531 information to provide the user with the capability to easily locate the
17532 declaration and references to an entity. These tools are quite similar,
17533 the difference being that @cite{gnatfind} is intended for locating
17534 definitions and/or references to a specified entity or entities, whereas
17535 @cite{gnatxref} is oriented to generating a full report of all
17536 cross-references.
17538 To use these tools, you must not compile your application using the
17539 @emph{-gnatx} switch on the @emph{gnatmake} command line
17540 (see @ref{1b,,Building with gnatmake}). Otherwise, cross-referencing
17541 information will not be generated.
17543 Note: to invoke @cite{gnatxref} or @cite{gnatfind} with a project file,
17544 use the @cite{gnat} driver (see @emph{The_GNAT_Driver_and_Project_Files}).
17546 @menu
17547 * gnatxref Switches:: 
17548 * gnatfind Switches:: 
17549 * Project Files for gnatxref and gnatfind:: 
17550 * Regular Expressions in gnatfind and gnatxref:: 
17551 * Examples of gnatxref Usage:: 
17552 * Examples of gnatfind Usage:: 
17554 @end menu
17556 @node gnatxref Switches,gnatfind Switches,,The Cross-Referencing Tools gnatxref and gnatfind
17557 @anchor{gnat_ugn/gnat_utility_programs id10}@anchor{150}@anchor{gnat_ugn/gnat_utility_programs gnatxref-switches}@anchor{151}
17558 @subsection @cite{gnatxref} Switches
17561 The command invocation for @cite{gnatxref} is:
17563 @quotation
17565 @example
17566 $ gnatxref [`switches`] `sourcefile1` [`sourcefile2` ...]
17567 @end example
17568 @end quotation
17570 where
17573 @table @asis
17575 @item @emph{sourcefile1} [, @emph{sourcefile2} ...]
17577 identify the source files for which a report is to be generated. The
17578 'with'ed units will be processed too. You must provide at least one file.
17580 These file names are considered to be regular expressions, so for instance
17581 specifying @code{source*.adb} is the same as giving every file in the current
17582 directory whose name starts with @code{source} and whose extension is
17583 @code{adb}.
17585 You shouldn't specify any directory name, just base names. @emph{gnatxref}
17586 and @emph{gnatfind} will be able to locate these files by themselves using
17587 the source path. If you specify directories, no result is produced.
17588 @end table
17590 The following switches are available for @emph{gnatxref}:
17592 @geindex --version (gnatxref)
17595 @table @asis
17597 @item @code{-version}
17599 Display Copyright and version, then exit disregarding all other options.
17600 @end table
17602 @geindex --help (gnatxref)
17605 @table @asis
17607 @item @code{-help}
17609 If @emph{--version} was not used, display usage, then exit disregarding
17610 all other options.
17611 @end table
17613 @geindex -a (gnatxref)
17616 @table @asis
17618 @item @code{a}
17620 If this switch is present, @cite{gnatfind} and @cite{gnatxref} will parse
17621 the read-only files found in the library search path. Otherwise, these files
17622 will be ignored. This option can be used to protect Gnat sources or your own
17623 libraries from being parsed, thus making @cite{gnatfind} and @cite{gnatxref}
17624 much faster, and their output much smaller. Read-only here refers to access
17625 or permissions status in the file system for the current user.
17626 @end table
17628 @geindex -aIDIR (gnatxref)
17631 @table @asis
17633 @item @code{aI@emph{DIR}}
17635 When looking for source files also look in directory DIR. The order in which
17636 source file search is undertaken is the same as for @emph{gnatmake}.
17637 @end table
17639 @geindex -aODIR (gnatxref)
17642 @table @asis
17644 @item @code{aO@emph{DIR}}
17646 When searching for library and object files, look in directory
17647 DIR. The order in which library files are searched is the same as for
17648 @emph{gnatmake}.
17649 @end table
17651 @geindex -nostdinc (gnatxref)
17654 @table @asis
17656 @item @code{nostdinc}
17658 Do not look for sources in the system default directory.
17659 @end table
17661 @geindex -nostdlib (gnatxref)
17664 @table @asis
17666 @item @code{nostdlib}
17668 Do not look for library files in the system default directory.
17669 @end table
17671 @geindex --ext (gnatxref)
17674 @table @asis
17676 @item @code{-ext=@emph{extension}}
17678 Specify an alternate ali file extension. The default is @cite{ali} and other
17679 extensions (e.g. @cite{gli} for C/C++ sources when using @emph{-fdump-xref})
17680 may be specified via this switch. Note that if this switch overrides the
17681 default, which means that only the new extension will be considered.
17682 @end table
17684 @geindex --RTS (gnatxref)
17687 @table @asis
17689 @item @code{-RTS=@emph{rts-path}}
17691 Specifies the default location of the runtime library. Same meaning as the
17692 equivalent @emph{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
17693 @end table
17695 @geindex -d (gnatxref)
17698 @table @asis
17700 @item @code{d}
17702 If this switch is set @cite{gnatxref} will output the parent type
17703 reference for each matching derived types.
17704 @end table
17706 @geindex -f (gnatxref)
17709 @table @asis
17711 @item @code{f}
17713 If this switch is set, the output file names will be preceded by their
17714 directory (if the file was found in the search path). If this switch is
17715 not set, the directory will not be printed.
17716 @end table
17718 @geindex -g (gnatxref)
17721 @table @asis
17723 @item @code{g}
17725 If this switch is set, information is output only for library-level
17726 entities, ignoring local entities. The use of this switch may accelerate
17727 @cite{gnatfind} and @cite{gnatxref}.
17728 @end table
17730 @geindex -IDIR (gnatxref)
17733 @table @asis
17735 @item @code{I@emph{DIR}}
17737 Equivalent to @code{-aODIR -aIDIR}.
17738 @end table
17740 @geindex -pFILE (gnatxref)
17743 @table @asis
17745 @item @code{p@emph{FILE}}
17747 Specify a project file to use (see the @emph{GNAT_Project_Manager}
17748 chapter in the @emph{GPRbuild User's Guide}).
17749 If you need to use the @code{.gpr}
17750 project files, you should use gnatxref through the GNAT driver
17751 (@emph{gnat xref -Pproject}).
17753 By default, @cite{gnatxref} and @cite{gnatfind} will try to locate a
17754 project file in the current directory.
17756 If a project file is either specified or found by the tools, then the content
17757 of the source directory and object directory lines are added as if they
17758 had been specified respectively by @code{-aI}
17759 and @code{-aO}.
17761 @item @code{u}
17763 Output only unused symbols. This may be really useful if you give your
17764 main compilation unit on the command line, as @cite{gnatxref} will then
17765 display every unused entity and 'with'ed package.
17767 @item @code{v}
17769 Instead of producing the default output, @cite{gnatxref} will generate a
17770 @code{tags} file that can be used by vi. For examples how to use this
17771 feature, see @ref{152,,Examples of gnatxref Usage}. The tags file is output
17772 to the standard output, thus you will have to redirect it to a file.
17773 @end table
17775 All these switches may be in any order on the command line, and may even
17776 appear after the file names. They need not be separated by spaces, thus
17777 you can say @code{gnatxref -ag} instead of @code{gnatxref -a -g}.
17779 @node gnatfind Switches,Project Files for gnatxref and gnatfind,gnatxref Switches,The Cross-Referencing Tools gnatxref and gnatfind
17780 @anchor{gnat_ugn/gnat_utility_programs id11}@anchor{153}@anchor{gnat_ugn/gnat_utility_programs gnatfind-switches}@anchor{154}
17781 @subsection @cite{gnatfind} Switches
17784 The command invocation for @cite{gnatfind} is:
17786 @quotation
17788 @example
17789 $ gnatfind [`switches`] `pattern`[:`sourcefile`[:`line`[:`column`]]]
17790       [`file1` `file2` ...]
17791 @end example
17792 @end quotation
17794 with the following iterpretation of the command arguments:
17797 @table @asis
17799 @item @emph{pattern}
17801 An entity will be output only if it matches the regular expression found
17802 in @cite{pattern}, see @ref{155,,Regular Expressions in gnatfind and gnatxref}.
17804 Omitting the pattern is equivalent to specifying @code{*}, which
17805 will match any entity. Note that if you do not provide a pattern, you
17806 have to provide both a sourcefile and a line.
17808 Entity names are given in Latin-1, with uppercase/lowercase equivalence
17809 for matching purposes. At the current time there is no support for
17810 8-bit codes other than Latin-1, or for wide characters in identifiers.
17812 @item @emph{sourcefile}
17814 @cite{gnatfind} will look for references, bodies or declarations
17815 of symbols referenced in @code{sourcefile}, at line @cite{line}
17816 and column @cite{column}. See @ref{156,,Examples of gnatfind Usage}
17817 for syntax examples.
17819 @item @emph{line}
17821 A decimal integer identifying the line number containing
17822 the reference to the entity (or entities) to be located.
17824 @item @emph{column}
17826 A decimal integer identifying the exact location on the
17827 line of the first character of the identifier for the
17828 entity reference. Columns are numbered from 1.
17830 @item @emph{file1 file2 ...}
17832 The search will be restricted to these source files. If none are given, then
17833 the search will be conducted for every library file in the search path.
17834 These files must appear only after the pattern or sourcefile.
17836 These file names are considered to be regular expressions, so for instance
17837 specifying @code{source*.adb} is the same as giving every file in the current
17838 directory whose name starts with @code{source} and whose extension is
17839 @code{adb}.
17841 The location of the spec of the entity will always be displayed, even if it
17842 isn't in one of @code{file1}, @code{file2}, ... The
17843 occurrences of the entity in the separate units of the ones given on the
17844 command line will also be displayed.
17846 Note that if you specify at least one file in this part, @cite{gnatfind} may
17847 sometimes not be able to find the body of the subprograms.
17848 @end table
17850 At least one of 'sourcefile' or 'pattern' has to be present on
17851 the command line.
17853 The following switches are available:
17855 @geindex --version (gnatfind)
17858 @table @asis
17860 @item @code{--version}
17862 Display Copyright and version, then exit disregarding all other options.
17863 @end table
17865 @geindex --help (gnatfind)
17868 @table @asis
17870 @item @code{-help}
17872 If @emph{--version} was not used, display usage, then exit disregarding
17873 all other options.
17874 @end table
17876 @geindex -a (gnatfind)
17879 @table @asis
17881 @item @code{a}
17883 If this switch is present, @cite{gnatfind} and @cite{gnatxref} will parse
17884 the read-only files found in the library search path. Otherwise, these files
17885 will be ignored. This option can be used to protect Gnat sources or your own
17886 libraries from being parsed, thus making @cite{gnatfind} and @cite{gnatxref}
17887 much faster, and their output much smaller. Read-only here refers to access
17888 or permission status in the file system for the current user.
17889 @end table
17891 @geindex -aIDIR (gnatfind)
17894 @table @asis
17896 @item @code{aI@emph{DIR}}
17898 When looking for source files also look in directory DIR. The order in which
17899 source file search is undertaken is the same as for @emph{gnatmake}.
17900 @end table
17902 @geindex -aODIR (gnatfind)
17905 @table @asis
17907 @item @code{aO@emph{DIR}}
17909 When searching for library and object files, look in directory
17910 DIR. The order in which library files are searched is the same as for
17911 @emph{gnatmake}.
17912 @end table
17914 @geindex -nostdinc (gnatfind)
17917 @table @asis
17919 @item @code{nostdinc}
17921 Do not look for sources in the system default directory.
17922 @end table
17924 @geindex -nostdlib (gnatfind)
17927 @table @asis
17929 @item @code{nostdlib}
17931 Do not look for library files in the system default directory.
17932 @end table
17934 @geindex --ext (gnatfind)
17937 @table @asis
17939 @item @code{-ext=@emph{extension}}
17941 Specify an alternate ali file extension. The default is @cite{ali} and other
17942 extensions (e.g. @cite{gli} for C/C++ sources when using @emph{-fdump-xref})
17943 may be specified via this switch. Note that if this switch overrides the
17944 default, which means that only the new extension will be considered.
17945 @end table
17947 @geindex --RTS (gnatfind)
17950 @table @asis
17952 @item @code{-RTS=@emph{rts-path}}
17954 Specifies the default location of the runtime library. Same meaning as the
17955 equivalent @emph{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
17956 @end table
17958 @geindex -d (gnatfind)
17961 @table @asis
17963 @item @code{d}
17965 If this switch is set, then @cite{gnatfind} will output the parent type
17966 reference for each matching derived types.
17967 @end table
17969 @geindex -e (gnatfind)
17972 @table @asis
17974 @item @code{e}
17976 By default, @cite{gnatfind} accept the simple regular expression set for
17977 @cite{pattern}. If this switch is set, then the pattern will be
17978 considered as full Unix-style regular expression.
17979 @end table
17981 @geindex -f (gnatfind)
17984 @table @asis
17986 @item @code{f}
17988 If this switch is set, the output file names will be preceded by their
17989 directory (if the file was found in the search path). If this switch is
17990 not set, the directory will not be printed.
17991 @end table
17993 @geindex -g (gnatfind)
17996 @table @asis
17998 @item @code{g}
18000 If this switch is set, information is output only for library-level
18001 entities, ignoring local entities. The use of this switch may accelerate
18002 @cite{gnatfind} and @cite{gnatxref}.
18003 @end table
18005 @geindex -IDIR (gnatfind)
18008 @table @asis
18010 @item @code{I@emph{DIR}}
18012 Equivalent to @code{-aODIR -aIDIR}.
18013 @end table
18015 @geindex -pFILE (gnatfind)
18018 @table @asis
18020 @item @code{p@emph{FILE}}
18022 Specify a project file (see the @emph{GNAT_Project_Manager} chapter in the
18023 @emph{GPRbuild User's Guide}).
18024 By default, @cite{gnatxref} and @cite{gnatfind} will try to locate a
18025 project file in the current directory.
18027 If a project file is either specified or found by the tools, then the content
18028 of the source directory and object directory lines are added as if they
18029 had been specified respectively by @code{-aI} and
18030 @code{-aO}.
18031 @end table
18033 @geindex -r (gnatfind)
18036 @table @asis
18038 @item @code{r}
18040 By default, @cite{gnatfind} will output only the information about the
18041 declaration, body or type completion of the entities. If this switch is
18042 set, the @cite{gnatfind} will locate every reference to the entities in
18043 the files specified on the command line (or in every file in the search
18044 path if no file is given on the command line).
18045 @end table
18047 @geindex -s (gnatfind)
18050 @table @asis
18052 @item @code{s}
18054 If this switch is set, then @cite{gnatfind} will output the content
18055 of the Ada source file lines were the entity was found.
18056 @end table
18058 @geindex -t (gnatfind)
18061 @table @asis
18063 @item @code{t}
18065 If this switch is set, then @cite{gnatfind} will output the type hierarchy for
18066 the specified type. It act like -d option but recursively from parent
18067 type to parent type. When this switch is set it is not possible to
18068 specify more than one file.
18069 @end table
18071 All these switches may be in any order on the command line, and may even
18072 appear after the file names. They need not be separated by spaces, thus
18073 you can say @code{gnatxref -ag} instead of
18074 @code{gnatxref -a -g}.
18076 As stated previously, gnatfind will search in every directory in the
18077 search path. You can force it to look only in the current directory if
18078 you specify @cite{*} at the end of the command line.
18080 @node Project Files for gnatxref and gnatfind,Regular Expressions in gnatfind and gnatxref,gnatfind Switches,The Cross-Referencing Tools gnatxref and gnatfind
18081 @anchor{gnat_ugn/gnat_utility_programs project-files-for-gnatxref-and-gnatfind}@anchor{157}@anchor{gnat_ugn/gnat_utility_programs id12}@anchor{158}
18082 @subsection Project Files for @emph{gnatxref} and @emph{gnatfind}
18085 Project files allow a programmer to specify how to compile its
18086 application, where to find sources, etc.  These files are used
18087 primarily by GPS, but they can also be used
18088 by the two tools @cite{gnatxref} and @cite{gnatfind}.
18090 A project file name must end with @code{.gpr}. If a single one is
18091 present in the current directory, then @cite{gnatxref} and @cite{gnatfind} will
18092 extract the information from it. If multiple project files are found, none of
18093 them is read, and you have to use the @code{-p} switch to specify the one
18094 you want to use.
18096 The following lines can be included, even though most of them have default
18097 values which can be used in most cases.
18098 The lines can be entered in any order in the file.
18099 Except for @code{src_dir} and @code{obj_dir}, you can only have one instance of
18100 each line. If you have multiple instances, only the last one is taken into
18101 account.
18104 @itemize *
18106 @item 
18108 @table @asis
18110 @item @emph{src_dir=DIR}
18112 [default: @cite{"./"}].
18113 Specifies a directory where to look for source files. Multiple @cite{src_dir}
18114 lines can be specified and they will be searched in the order they
18115 are specified.
18116 @end table
18118 @item 
18120 @table @asis
18122 @item @emph{obj_dir=DIR}
18124 [default: @cite{"./"}].
18125 Specifies a directory where to look for object and library files. Multiple
18126 @cite{obj_dir} lines can be specified, and they will be searched in the order
18127 they are specified
18128 @end table
18130 @item 
18132 @table @asis
18134 @item @emph{comp_opt=SWITCHES}
18136 [default: @cite{""}].
18137 Creates a variable which can be referred to subsequently by using
18138 the @cite{$@{comp_opt@}} notation. This is intended to store the default
18139 switches given to @emph{gnatmake} and @emph{gcc}.
18140 @end table
18142 @item 
18144 @table @asis
18146 @item @emph{bind_opt=SWITCHES}
18148 [default: @cite{""}].
18149 Creates a variable which can be referred to subsequently by using
18150 the @code{$@emph{bind_opt}} notation. This is intended to store the default
18151 switches given to @emph{gnatbind}.
18152 @end table
18154 @item 
18156 @table @asis
18158 @item @emph{link_opt=SWITCHES}
18160 [default: @cite{""}].
18161 Creates a variable which can be referred to subsequently by using
18162 the @code{$@emph{link_opt}} notation. This is intended to store the default
18163 switches given to @emph{gnatlink}.
18164 @end table
18166 @item 
18168 @table @asis
18170 @item @emph{main=EXECUTABLE}
18172 [default: @cite{""}].
18173 Specifies the name of the executable for the application. This variable can
18174 be referred to in the following lines by using the @code{@emph{$@{main}} notation.
18175 @end table
18177 @item 
18179 @table @asis
18181 @item @emph{comp_cmd=COMMAND}
18183 [default: @cite{"gcc -c -I$@{src_dir@} -g -gnatq"}].
18184 Specifies the command used to compile a single file in the application.
18185 @end table
18187 @item 
18189 @table @asis
18191 @item @emph{make_cmd=COMMAND}
18193 [default: @cite{"gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"}].
18194 Specifies the command used to recompile the whole application.
18195 @end table
18197 @item 
18199 @table @asis
18201 @item @emph{run_cmd=COMMAND}
18203 [default: @cite{"$@{main@}"}].
18204 Specifies the command used to run the application.
18205 @end table
18207 @item 
18209 @table @asis
18211 @item @emph{debug_cmd=COMMAND}
18213 [default: @cite{"gdb $@{main@}"}].
18214 Specifies the command used to debug the application
18215 @end table
18216 @end itemize
18218 @emph{gnatxref} and @emph{gnatfind} only take into account the
18219 @cite{src_dir} and @cite{obj_dir} lines, and ignore the others.
18221 @node Regular Expressions in gnatfind and gnatxref,Examples of gnatxref Usage,Project Files for gnatxref and gnatfind,The Cross-Referencing Tools gnatxref and gnatfind
18222 @anchor{gnat_ugn/gnat_utility_programs id13}@anchor{159}@anchor{gnat_ugn/gnat_utility_programs regular-expressions-in-gnatfind-and-gnatxref}@anchor{155}
18223 @subsection Regular Expressions in @cite{gnatfind} and @cite{gnatxref}
18226 As specified in the section about @emph{gnatfind}, the pattern can be a
18227 regular expression. Two kinds of regular expressions
18228 are recognized:
18231 @itemize *
18233 @item 
18235 @table @asis
18237 @item @emph{Globbing pattern}
18239 These are the most common regular expression. They are the same as are
18240 generally used in a Unix shell command line, or in a DOS session.
18242 Here is a more formal grammar:
18244 @example
18245 regexp ::= term
18246 term   ::= elmt            -- matches elmt
18247 term   ::= elmt elmt       -- concatenation (elmt then elmt)
18248 term   ::= *               -- any string of 0 or more characters
18249 term   ::= ?               -- matches any character
18250 term   ::= [char @{char@}]   -- matches any character listed
18251 term   ::= [char - char]   -- matches any character in range
18252 @end example
18253 @end table
18255 @item 
18257 @table @asis
18259 @item @emph{Full regular expression}
18261 The second set of regular expressions is much more powerful. This is the
18262 type of regular expressions recognized by utilities such as @code{grep}.
18264 The following is the form of a regular expression, expressed in same BNF
18265 style as is found in the Ada Reference Manual:
18267 @example
18268 regexp ::= term @{| term@}   -- alternation (term or term ...)
18270 term ::= item @{item@}       -- concatenation (item then item)
18272 item ::= elmt              -- match elmt
18273 item ::= elmt *            -- zero or more elmt's
18274 item ::= elmt +            -- one or more elmt's
18275 item ::= elmt ?            -- matches elmt or nothing
18277 elmt ::= nschar            -- matches given character
18278 elmt ::= [nschar @{nschar@}]   -- matches any character listed
18279 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
18280 elmt ::= [char - char]     -- matches chars in given range
18281 elmt ::= \\ char            -- matches given character
18282 elmt ::= .                 -- matches any single character
18283 elmt ::= ( regexp )        -- parens used for grouping
18285 char ::= any character, including special characters
18286 nschar ::= any character except ()[].*+?^
18287 @end example
18289 Here are a few examples:
18291 @quotation
18294 @table @asis
18296 @item @code{abcde|fghi}
18298 will match any of the two strings @code{abcde} and @code{fghi},
18300 @item @code{abc*d}
18302 will match any string like @code{abd}, @code{abcd}, @code{abccd},
18303 @code{abcccd}, and so on,
18305 @item @code{[a-z]+}
18307 will match any string which has only lowercase characters in it (and at
18308 least one character.
18309 @end table
18310 @end quotation
18311 @end table
18312 @end itemize
18314 @node Examples of gnatxref Usage,Examples of gnatfind Usage,Regular Expressions in gnatfind and gnatxref,The Cross-Referencing Tools gnatxref and gnatfind
18315 @anchor{gnat_ugn/gnat_utility_programs examples-of-gnatxref-usage}@anchor{152}@anchor{gnat_ugn/gnat_utility_programs id14}@anchor{15a}
18316 @subsection Examples of @cite{gnatxref} Usage
18319 @menu
18320 * General Usage:: 
18321 * Using gnatxref with vi:: 
18323 @end menu
18325 @node General Usage,Using gnatxref with vi,,Examples of gnatxref Usage
18326 @anchor{gnat_ugn/gnat_utility_programs general-usage}@anchor{15b}
18327 @subsubsection General Usage
18330 For the following examples, we will consider the following units:
18332 @quotation
18334 @example
18335 main.ads:
18336 1: with Bar;
18337 2: package Main is
18338 3:     procedure Foo (B : in Integer);
18339 4:     C : Integer;
18340 5: private
18341 6:     D : Integer;
18342 7: end Main;
18344 main.adb:
18345 1: package body Main is
18346 2:     procedure Foo (B : in Integer) is
18347 3:     begin
18348 4:        C := B;
18349 5:        D := B;
18350 6:        Bar.Print (B);
18351 7:        Bar.Print (C);
18352 8:     end Foo;
18353 9: end Main;
18355 bar.ads:
18356 1: package Bar is
18357 2:     procedure Print (B : Integer);
18358 3: end bar;
18359 @end example
18360 @end quotation
18362 The first thing to do is to recompile your application (for instance, in
18363 that case just by doing a @code{gnatmake main}, so that GNAT generates
18364 the cross-referencing information.
18365 You can then issue any of the following commands:
18367 @quotation
18370 @itemize *
18372 @item 
18373 @code{gnatxref main.adb}
18374 @cite{gnatxref} generates cross-reference information for main.adb
18375 and every unit 'with'ed by main.adb.
18377 The output would be:
18379 @quotation
18381 @example
18382 B                                                      Type: Integer
18383   Decl: bar.ads           2:22
18384 B                                                      Type: Integer
18385   Decl: main.ads          3:20
18386   Body: main.adb          2:20
18387   Ref:  main.adb          4:13     5:13     6:19
18388 Bar                                                    Type: Unit
18389   Decl: bar.ads           1:9
18390   Ref:  main.adb          6:8      7:8
18391        main.ads           1:6
18392 C                                                      Type: Integer
18393   Decl: main.ads          4:5
18394   Modi: main.adb          4:8
18395   Ref:  main.adb          7:19
18396 D                                                      Type: Integer
18397   Decl: main.ads          6:5
18398   Modi: main.adb          5:8
18399 Foo                                                    Type: Unit
18400   Decl: main.ads          3:15
18401   Body: main.adb          2:15
18402 Main                                                    Type: Unit
18403   Decl: main.ads          2:9
18404   Body: main.adb          1:14
18405 Print                                                   Type: Unit
18406   Decl: bar.ads           2:15
18407   Ref:  main.adb          6:12     7:12
18408 @end example
18409 @end quotation
18411 This shows that the entity @cite{Main} is declared in main.ads, line 2, column 9,
18412 its body is in main.adb, line 1, column 14 and is not referenced any where.
18414 The entity @cite{Print} is declared in bar.ads, line 2, column 15 and it
18415 is referenced in main.adb, line 6 column 12 and line 7 column 12.
18417 @item 
18418 @code{gnatxref package1.adb package2.ads}
18419 @cite{gnatxref} will generates cross-reference information for
18420 package1.adb, package2.ads and any other package 'with'ed by any
18421 of these.
18422 @end itemize
18423 @end quotation
18425 @node Using gnatxref with vi,,General Usage,Examples of gnatxref Usage
18426 @anchor{gnat_ugn/gnat_utility_programs using-gnatxref-with-vi}@anchor{15c}
18427 @subsubsection Using gnatxref with vi
18430 @cite{gnatxref} can generate a tags file output, which can be used
18431 directly from @emph{vi}. Note that the standard version of @emph{vi}
18432 will not work properly with overloaded symbols. Consider using another
18433 free implementation of @emph{vi}, such as @emph{vim}.
18435 @quotation
18437 @example
18438 $ gnatxref -v gnatfind.adb > tags
18439 @end example
18440 @end quotation
18442 The following command will generate the tags file for @cite{gnatfind} itself
18443 (if the sources are in the search path!):
18445 @quotation
18447 @example
18448 $ gnatxref -v gnatfind.adb > tags
18449 @end example
18450 @end quotation
18452 From @emph{vi}, you can then use the command @code{:tag @emph{entity}}
18453 (replacing @cite{entity} by whatever you are looking for), and vi will
18454 display a new file with the corresponding declaration of entity.
18456 @node Examples of gnatfind Usage,,Examples of gnatxref Usage,The Cross-Referencing Tools gnatxref and gnatfind
18457 @anchor{gnat_ugn/gnat_utility_programs id15}@anchor{15d}@anchor{gnat_ugn/gnat_utility_programs examples-of-gnatfind-usage}@anchor{156}
18458 @subsection Examples of @cite{gnatfind} Usage
18462 @itemize *
18464 @item 
18465 @code{gnatfind -f xyz:main.adb}
18466 Find declarations for all entities xyz referenced at least once in
18467 main.adb. The references are search in every library file in the search
18468 path.
18470 The directories will be printed as well (as the @code{-f}
18471 switch is set)
18473 The output will look like:
18475 @quotation
18477 @example
18478 directory/main.ads:106:14: xyz <= declaration
18479 directory/main.adb:24:10: xyz <= body
18480 directory/foo.ads:45:23: xyz <= declaration
18481 @end example
18482 @end quotation
18484 I.e., one of the entities xyz found in main.adb is declared at
18485 line 12 of main.ads (and its body is in main.adb), and another one is
18486 declared at line 45 of foo.ads
18488 @item 
18489 @code{gnatfind -fs xyz:main.adb}
18490 This is the same command as the previous one, but @cite{gnatfind} will
18491 display the content of the Ada source file lines.
18493 The output will look like:
18495 @example
18496 directory/main.ads:106:14: xyz <= declaration
18497    procedure xyz;
18498 directory/main.adb:24:10: xyz <= body
18499    procedure xyz is
18500 directory/foo.ads:45:23: xyz <= declaration
18501    xyz : Integer;
18502 @end example
18504 This can make it easier to find exactly the location your are looking
18505 for.
18507 @item 
18508 @code{gnatfind -r "*x*":main.ads:123 foo.adb}
18509 Find references to all entities containing an x that are
18510 referenced on line 123 of main.ads.
18511 The references will be searched only in main.ads and foo.adb.
18513 @item 
18514 @code{gnatfind main.ads:123}
18515 Find declarations and bodies for all entities that are referenced on
18516 line 123 of main.ads.
18518 This is the same as @code{gnatfind "*":main.adb:123`}
18520 @item 
18521 @code{gnatfind mydir/main.adb:123:45}
18522 Find the declaration for the entity referenced at column 45 in
18523 line 123 of file main.adb in directory mydir. Note that it
18524 is usual to omit the identifier name when the column is given,
18525 since the column position identifies a unique reference.
18527 The column has to be the beginning of the identifier, and should not
18528 point to any character in the middle of the identifier.
18529 @end itemize
18531 @node The Ada to HTML Converter gnathtml,,The Cross-Referencing Tools gnatxref and gnatfind,GNAT Utility Programs
18532 @anchor{gnat_ugn/gnat_utility_programs the-ada-to-html-converter-gnathtml}@anchor{23}@anchor{gnat_ugn/gnat_utility_programs id16}@anchor{15e}
18533 @section The Ada to HTML Converter @cite{gnathtml}
18536 @geindex gnathtml
18538 @emph{gnathtml} is a Perl script that allows Ada source files to be browsed using
18539 standard Web browsers. For installation information, see @ref{15f,,Installing gnathtml}.
18541 Ada reserved keywords are highlighted in a bold font and Ada comments in
18542 a blue font. Unless your program was compiled with the gcc @emph{-gnatx}
18543 switch to suppress the generation of cross-referencing information, user
18544 defined variables and types will appear in a different color; you will
18545 be able to click on any identifier and go to its declaration.
18547 @menu
18548 * Invoking gnathtml:: 
18549 * Installing gnathtml:: 
18551 @end menu
18553 @node Invoking gnathtml,Installing gnathtml,,The Ada to HTML Converter gnathtml
18554 @anchor{gnat_ugn/gnat_utility_programs invoking-gnathtml}@anchor{160}@anchor{gnat_ugn/gnat_utility_programs id17}@anchor{161}
18555 @subsection Invoking @emph{gnathtml}
18558 The command line is as follows:
18560 @quotation
18562 @example
18563 $ perl gnathtml.pl [`switches`] `ada-files`
18564 @end example
18565 @end quotation
18567 You can specify as many Ada files as you want. @cite{gnathtml} will generate
18568 an html file for every ada file, and a global file called @code{index.htm}.
18569 This file is an index of every identifier defined in the files.
18571 The following switches are available:
18573 @geindex -83 (gnathtml)
18576 @table @asis
18578 @item @code{83}
18580 Only the Ada 83 subset of keywords will be highlighted.
18581 @end table
18583 @geindex -cc (gnathtml)
18586 @table @asis
18588 @item @code{cc @emph{color}}
18590 This option allows you to change the color used for comments. The default
18591 value is green. The color argument can be any name accepted by html.
18592 @end table
18594 @geindex -d (gnathtml)
18597 @table @asis
18599 @item @code{d}
18601 If the Ada files depend on some other files (for instance through
18602 @cite{with} clauses, the latter files will also be converted to html.
18603 Only the files in the user project will be converted to html, not the files
18604 in the run-time library itself.
18605 @end table
18607 @geindex -D (gnathtml)
18610 @table @asis
18612 @item @code{D}
18614 This command is the same as @emph{-d} above, but @emph{gnathtml} will
18615 also look for files in the run-time library, and generate html files for them.
18616 @end table
18618 @geindex -ext (gnathtml)
18621 @table @asis
18623 @item @code{ext @emph{extension}}
18625 This option allows you to change the extension of the generated HTML files.
18626 If you do not specify an extension, it will default to @code{htm}.
18627 @end table
18629 @geindex -f (gnathtml)
18632 @table @asis
18634 @item @code{f}
18636 By default, gnathtml will generate html links only for global entities
18637 ('with'ed units, global variables and types,...).  If you specify
18638 @emph{-f} on the command line, then links will be generated for local
18639 entities too.
18640 @end table
18642 @geindex -l (gnathtml)
18645 @table @asis
18647 @item @code{l @emph{number}}
18649 If this switch is provided and @cite{number} is not 0, then
18650 @cite{gnathtml} will number the html files every @cite{number} line.
18651 @end table
18653 @geindex -I (gnathtml)
18656 @table @asis
18658 @item @code{I @emph{dir}}
18660 Specify a directory to search for library files (@code{.ALI} files) and
18661 source files. You can provide several -I switches on the command line,
18662 and the directories will be parsed in the order of the command line.
18663 @end table
18665 @geindex -o (gnathtml)
18668 @table @asis
18670 @item @code{o @emph{dir}}
18672 Specify the output directory for html files. By default, gnathtml will
18673 saved the generated html files in a subdirectory named @code{html/}.
18674 @end table
18676 @geindex -p (gnathtml)
18679 @table @asis
18681 @item @code{p @emph{file}}
18683 If you are using Emacs and the most recent Emacs Ada mode, which provides
18684 a full Integrated Development Environment for compiling, checking,
18685 running and debugging applications, you may use @code{.gpr} files
18686 to give the directories where Emacs can find sources and object files.
18688 Using this switch, you can tell gnathtml to use these files.
18689 This allows you to get an html version of your application, even if it
18690 is spread over multiple directories.
18691 @end table
18693 @geindex -sc (gnathtml)
18696 @table @asis
18698 @item @code{sc @emph{color}}
18700 This switch allows you to change the color used for symbol
18701 definitions.
18702 The default value is red. The color argument can be any name accepted by html.
18703 @end table
18705 @geindex -t (gnathtml)
18708 @table @asis
18710 @item @code{t @emph{file}}
18712 This switch provides the name of a file. This file contains a list of
18713 file names to be converted, and the effect is exactly as though they had
18714 appeared explicitly on the command line. This
18715 is the recommended way to work around the command line length limit on some
18716 systems.
18717 @end table
18719 @node Installing gnathtml,,Invoking gnathtml,The Ada to HTML Converter gnathtml
18720 @anchor{gnat_ugn/gnat_utility_programs installing-gnathtml}@anchor{15f}@anchor{gnat_ugn/gnat_utility_programs id18}@anchor{162}
18721 @subsection Installing @cite{gnathtml}
18724 @cite{Perl} needs to be installed on your machine to run this script.
18725 @cite{Perl} is freely available for almost every architecture and
18726 operating system via the Internet.
18728 On Unix systems, you  may want to modify  the  first line of  the script
18729 @cite{gnathtml},  to explicitly  specify  where Perl
18730 is located. The syntax of this line is:
18732 @quotation
18734 @example
18735 #!full_path_name_to_perl
18736 @end example
18737 @end quotation
18739 Alternatively, you may run the script using the following command line:
18741 @quotation
18743 @example
18744 $ perl gnathtml.pl [`switches`] `files`
18745 @end example
18746 @end quotation
18748 @c -- +---------------------------------------------------------------------+
18750 @c -- | The following sections are present only in the PRO and GPL editions |
18752 @c -- +---------------------------------------------------------------------+
18761 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
18763 @node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
18764 @anchor{gnat_ugn/gnat_and_program_execution gnat-and-program-execution}@anchor{c}@anchor{gnat_ugn/gnat_and_program_execution doc}@anchor{163}@anchor{gnat_ugn/gnat_and_program_execution id1}@anchor{164}
18765 @chapter GNAT and Program Execution
18768 This chapter covers several topics:
18771 @itemize *
18773 @item 
18774 @ref{165,,Running and Debugging Ada Programs}
18776 @item 
18777 @ref{166,,Code Coverage and Profiling}
18779 @item 
18780 @ref{167,,Improving Performance}
18782 @item 
18783 @ref{168,,Overflow Check Handling in GNAT}
18785 @item 
18786 @ref{169,,Performing Dimensionality Analysis in GNAT}
18788 @item 
18789 @ref{16a,,Stack Related Facilities}
18791 @item 
18792 @ref{16b,,Memory Management Issues}
18793 @end itemize
18795 @menu
18796 * Running and Debugging Ada Programs:: 
18797 * Code Coverage and Profiling:: 
18798 * Improving Performance:: 
18799 * Overflow Check Handling in GNAT:: 
18800 * Performing Dimensionality Analysis in GNAT:: 
18801 * Stack Related Facilities:: 
18802 * Memory Management Issues:: 
18804 @end menu
18806 @node Running and Debugging Ada Programs,Code Coverage and Profiling,,GNAT and Program Execution
18807 @anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{165}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{24}
18808 @section Running and Debugging Ada Programs
18811 @geindex Debugging
18813 This section discusses how to debug Ada programs.
18815 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18818 @itemize *
18820 @item 
18821 The illegality may be a violation of the static semantics of Ada. In
18822 that case GNAT diagnoses the constructs in the program that are illegal.
18823 It is then a straightforward matter for the user to modify those parts of
18824 the program.
18826 @item 
18827 The illegality may be a violation of the dynamic semantics of Ada. In
18828 that case the program compiles and executes, but may generate incorrect
18829 results, or may terminate abnormally with some exception.
18831 @item 
18832 When presented with a program that contains convoluted errors, GNAT
18833 itself may terminate abnormally without providing full diagnostics on
18834 the incorrect user program.
18835 @end itemize
18837 @geindex Debugger
18839 @geindex gdb
18841 @menu
18842 * The GNAT Debugger GDB:: 
18843 * Running GDB:: 
18844 * Introduction to GDB Commands:: 
18845 * Using Ada Expressions:: 
18846 * Calling User-Defined Subprograms:: 
18847 * Using the next Command in a Function:: 
18848 * Stopping When Ada Exceptions Are Raised:: 
18849 * Ada Tasks:: 
18850 * Debugging Generic Units:: 
18851 * Remote Debugging with gdbserver:: 
18852 * GNAT Abnormal Termination or Failure to Terminate:: 
18853 * Naming Conventions for GNAT Source Files:: 
18854 * Getting Internal Debugging Information:: 
18855 * Stack Traceback:: 
18857 @end menu
18859 @node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
18860 @anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{16c}@anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{16d}
18861 @subsection The GNAT Debugger GDB
18864 @cite{GDB} is a general purpose, platform-independent debugger that
18865 can be used to debug mixed-language programs compiled with @emph{gcc},
18866 and in particular is capable of debugging Ada programs compiled with
18867 GNAT. The latest versions of @cite{GDB} are Ada-aware and can handle
18868 complex Ada data structures.
18870 See @cite{Debugging with GDB},
18871 for full details on the usage of @cite{GDB}, including a section on
18872 its usage on programs. This manual should be consulted for full
18873 details. The section that follows is a brief introduction to the
18874 philosophy and use of @cite{GDB}.
18876 When GNAT programs are compiled, the compiler optionally writes debugging
18877 information into the generated object file, including information on
18878 line numbers, and on declared types and variables. This information is
18879 separate from the generated code. It makes the object files considerably
18880 larger, but it does not add to the size of the actual executable that
18881 will be loaded into memory, and has no impact on run-time performance. The
18882 generation of debug information is triggered by the use of the
18883 -g switch in the @emph{gcc} or @emph{gnatmake} command
18884 used to carry out the compilations. It is important to emphasize that
18885 the use of these options does not change the generated code.
18887 The debugging information is written in standard system formats that
18888 are used by many tools, including debuggers and profilers. The format
18889 of the information is typically designed to describe C types and
18890 semantics, but GNAT implements a translation scheme which allows full
18891 details about Ada types and variables to be encoded into these
18892 standard C formats. Details of this encoding scheme may be found in
18893 the file exp_dbug.ads in the GNAT source distribution. However, the
18894 details of this encoding are, in general, of no interest to a user,
18895 since @cite{GDB} automatically performs the necessary decoding.
18897 When a program is bound and linked, the debugging information is
18898 collected from the object files, and stored in the executable image of
18899 the program. Again, this process significantly increases the size of
18900 the generated executable file, but it does not increase the size of
18901 the executable program itself. Furthermore, if this program is run in
18902 the normal manner, it runs exactly as if the debug information were
18903 not present, and takes no more actual memory.
18905 However, if the program is run under control of @cite{GDB}, the
18906 debugger is activated.  The image of the program is loaded, at which
18907 point it is ready to run.  If a run command is given, then the program
18908 will run exactly as it would have if @cite{GDB} were not present. This
18909 is a crucial part of the @cite{GDB} design philosophy.  @cite{GDB} is
18910 entirely non-intrusive until a breakpoint is encountered.  If no
18911 breakpoint is ever hit, the program will run exactly as it would if no
18912 debugger were present. When a breakpoint is hit, @cite{GDB} accesses
18913 the debugging information and can respond to user commands to inspect
18914 variables, and more generally to report on the state of execution.
18916 @node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
18917 @anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{16e}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{16f}
18918 @subsection Running GDB
18921 This section describes how to initiate the debugger.
18923 The debugger can be launched from a @cite{GPS} menu or
18924 directly from the command line. The description below covers the latter use.
18925 All the commands shown can be used in the @cite{GPS} debug console window,
18926 but there are usually more GUI-based ways to achieve the same effect.
18928 The command to run @cite{GDB} is
18930 @quotation
18932 @example
18933 $ gdb program
18934 @end example
18935 @end quotation
18937 where @cite{program} is the name of the executable file. This
18938 activates the debugger and results in a prompt for debugger commands.
18939 The simplest command is simply @cite{run}, which causes the program to run
18940 exactly as if the debugger were not present. The following section
18941 describes some of the additional commands that can be given to @cite{GDB}.
18943 @node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
18944 @anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{170}@anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{171}
18945 @subsection Introduction to GDB Commands
18948 @cite{GDB} contains a large repertoire of commands.
18949 See @cite{Debugging with GDB} for extensive documentation on the use
18950 of these commands, together with examples of their use. Furthermore,
18951 the command @emph{help} invoked from within GDB activates a simple help
18952 facility which summarizes the available commands and their options.
18953 In this section we summarize a few of the most commonly
18954 used commands to give an idea of what @cite{GDB} is about. You should create
18955 a simple program with debugging information and experiment with the use of
18956 these @cite{GDB} commands on the program as you read through the
18957 following section.
18960 @itemize *
18962 @item 
18964 @table @asis
18966 @item @emph{set args `arguments`}
18968 The @cite{arguments} list above is a list of arguments to be passed to
18969 the program on a subsequent run command, just as though the arguments
18970 had been entered on a normal invocation of the program. The @cite{set args}
18971 command is not needed if the program does not require arguments.
18972 @end table
18974 @item 
18976 @table @asis
18978 @item @emph{run}
18980 The @cite{run} command causes execution of the program to start from
18981 the beginning. If the program is already running, that is to say if
18982 you are currently positioned at a breakpoint, then a prompt will ask
18983 for confirmation that you want to abandon the current execution and
18984 restart.
18985 @end table
18987 @item 
18989 @table @asis
18991 @item @emph{breakpoint `location`}
18993 The breakpoint command sets a breakpoint, that is to say a point at which
18994 execution will halt and @cite{GDB} will await further
18995 commands. @cite{location} is
18996 either a line number within a file, given in the format @cite{file:linenumber},
18997 or it is the name of a subprogram. If you request that a breakpoint be set on
18998 a subprogram that is overloaded, a prompt will ask you to specify on which of
18999 those subprograms you want to breakpoint. You can also
19000 specify that all of them should be breakpointed. If the program is run
19001 and execution encounters the breakpoint, then the program
19002 stops and @cite{GDB} signals that the breakpoint was encountered by
19003 printing the line of code before which the program is halted.
19004 @end table
19006 @item 
19008 @table @asis
19010 @item @emph{catch exception `name`}
19012 This command causes the program execution to stop whenever exception
19013 @cite{name} is raised.  If @cite{name} is omitted, then the execution is
19014 suspended when any exception is raised.
19015 @end table
19017 @item 
19019 @table @asis
19021 @item @emph{print `expression`}
19023 This will print the value of the given expression. Most simple
19024 Ada expression formats are properly handled by @cite{GDB}, so the expression
19025 can contain function calls, variables, operators, and attribute references.
19026 @end table
19028 @item 
19030 @table @asis
19032 @item @emph{continue}
19034 Continues execution following a breakpoint, until the next breakpoint or the
19035 termination of the program.
19036 @end table
19038 @item 
19040 @table @asis
19042 @item @emph{step}
19044 Executes a single line after a breakpoint. If the next statement
19045 is a subprogram call, execution continues into (the first statement of)
19046 the called subprogram.
19047 @end table
19049 @item 
19051 @table @asis
19053 @item @emph{next}
19055 Executes a single line. If this line is a subprogram call, executes and
19056 returns from the call.
19057 @end table
19059 @item 
19061 @table @asis
19063 @item @emph{list}
19065 Lists a few lines around the current source location. In practice, it
19066 is usually more convenient to have a separate edit window open with the
19067 relevant source file displayed. Successive applications of this command
19068 print subsequent lines. The command can be given an argument which is a
19069 line number, in which case it displays a few lines around the specified one.
19070 @end table
19072 @item 
19074 @table @asis
19076 @item @emph{backtrace}
19078 Displays a backtrace of the call chain. This command is typically
19079 used after a breakpoint has occurred, to examine the sequence of calls that
19080 leads to the current breakpoint. The display includes one line for each
19081 activation record (frame) corresponding to an active subprogram.
19082 @end table
19084 @item 
19086 @table @asis
19088 @item @emph{up}
19090 At a breakpoint, @cite{GDB} can display the values of variables local
19091 to the current frame. The command @cite{up} can be used to
19092 examine the contents of other active frames, by moving the focus up
19093 the stack, that is to say from callee to caller, one frame at a time.
19094 @end table
19096 @item 
19098 @table @asis
19100 @item @emph{down}
19102 Moves the focus of @cite{GDB} down from the frame currently being
19103 examined to the frame of its callee (the reverse of the previous command),
19104 @end table
19106 @item 
19108 @table @asis
19110 @item @emph{frame `n`}
19112 Inspect the frame with the given number. The value 0 denotes the frame
19113 of the current breakpoint, that is to say the top of the call stack.
19114 @end table
19116 @item 
19118 @table @asis
19120 @item @emph{kill}
19122 Kills the child process in which the program is running under GDB.
19123 This may be useful for several purposes:
19126 @itemize *
19128 @item 
19129 It allows you to recompile and relink your program, since on many systems
19130 you cannot regenerate an executable file while it is running in a process.
19132 @item 
19133 You can run your program outside the debugger, on systems that do not
19134 permit executing a program outside GDB while breakpoints are set
19135 within GDB.
19137 @item 
19138 It allows you to debug a core dump rather than a running process.
19139 @end itemize
19140 @end table
19141 @end itemize
19143 The above list is a very short introduction to the commands that
19144 @cite{GDB} provides. Important additional capabilities, including conditional
19145 breakpoints, the ability to execute command sequences on a breakpoint,
19146 the ability to debug at the machine instruction level and many other
19147 features are described in detail in @cite{Debugging with GDB}.
19148 Note that most commands can be abbreviated
19149 (for example, c for continue, bt for backtrace).
19151 @node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
19152 @anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{172}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{173}
19153 @subsection Using Ada Expressions
19156 @geindex Ada expressions (in gdb)
19158 @cite{GDB} supports a fairly large subset of Ada expression syntax, with some
19159 extensions. The philosophy behind the design of this subset is
19161 @quotation
19164 @itemize *
19166 @item 
19167 That @cite{GDB} should provide basic literals and access to operations for
19168 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19169 leaving more sophisticated computations to subprograms written into the
19170 program (which therefore may be called from @cite{GDB}).
19172 @item 
19173 That type safety and strict adherence to Ada language restrictions
19174 are not particularly relevant in a debugging context.
19176 @item 
19177 That brevity is important to the @cite{GDB} user.
19178 @end itemize
19179 @end quotation
19181 Thus, for brevity, the debugger acts as if there were
19182 implicit @cite{with} and @cite{use} clauses in effect for all user-written
19183 packages, thus making it unnecessary to fully qualify most names with
19184 their packages, regardless of context. Where this causes ambiguity,
19185 @cite{GDB} asks the user's intent.
19187 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
19189 @node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
19190 @anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{174}@anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{175}
19191 @subsection Calling User-Defined Subprograms
19194 An important capability of @cite{GDB} is the ability to call user-defined
19195 subprograms while debugging. This is achieved simply by entering
19196 a subprogram call statement in the form:
19198 @quotation
19200 @example
19201 call subprogram-name (parameters)
19202 @end example
19203 @end quotation
19205 The keyword @cite{call} can be omitted in the normal case where the
19206 @cite{subprogram-name} does not coincide with any of the predefined
19207 @cite{GDB} commands.
19209 The effect is to invoke the given subprogram, passing it the
19210 list of parameters that is supplied. The parameters can be expressions and
19211 can include variables from the program being debugged. The
19212 subprogram must be defined
19213 at the library level within your program, and @cite{GDB} will call the
19214 subprogram within the environment of your program execution (which
19215 means that the subprogram is free to access or even modify variables
19216 within your program).
19218 The most important use of this facility is in allowing the inclusion of
19219 debugging routines that are tailored to particular data structures
19220 in your program. Such debugging routines can be written to provide a suitably
19221 high-level description of an abstract type, rather than a low-level dump
19222 of its physical layout. After all, the standard
19223 @cite{GDB print} command only knows the physical layout of your
19224 types, not their abstract meaning. Debugging routines can provide information
19225 at the desired semantic level and are thus enormously useful.
19227 For example, when debugging GNAT itself, it is crucial to have access to
19228 the contents of the tree nodes used to represent the program internally.
19229 But tree nodes are represented simply by an integer value (which in turn
19230 is an index into a table of nodes).
19231 Using the @cite{print} command on a tree node would simply print this integer
19232 value, which is not very useful. But the PN routine (defined in file
19233 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19234 a useful high level representation of the tree node, which includes the
19235 syntactic category of the node, its position in the source, the integers
19236 that denote descendant nodes and parent node, as well as varied
19237 semantic information. To study this example in more detail, you might want to
19238 look at the body of the PN procedure in the stated file.
19240 Another useful application of this capability is to deal with situations of
19241 complex data which are not handled suitably by GDB. For example, if you specify
19242 Convention Fortran for a multi-dimensional array, GDB does not know that
19243 the ordering of array elements has been switched and will not properly
19244 address the array elements. In such a case, instead of trying to print the
19245 elements directly from GDB, you can write a callable procedure that prints
19246 the elements in the desired format.
19248 @node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
19249 @anchor{gnat_ugn/gnat_and_program_execution using-the-next-command-in-a-function}@anchor{176}@anchor{gnat_ugn/gnat_and_program_execution id8}@anchor{177}
19250 @subsection Using the @emph{next} Command in a Function
19253 When you use the @cite{next} command in a function, the current source
19254 location will advance to the next statement as usual. A special case
19255 arises in the case of a @cite{return} statement.
19257 Part of the code for a return statement is the 'epilogue' of the function.
19258 This is the code that returns to the caller. There is only one copy of
19259 this epilogue code, and it is typically associated with the last return
19260 statement in the function if there is more than one return. In some
19261 implementations, this epilogue is associated with the first statement
19262 of the function.
19264 The result is that if you use the @cite{next} command from a return
19265 statement that is not the last return statement of the function you
19266 may see a strange apparent jump to the last return statement or to
19267 the start of the function. You should simply ignore this odd jump.
19268 The value returned is always that from the first return statement
19269 that was stepped through.
19271 @node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
19272 @anchor{gnat_ugn/gnat_and_program_execution stopping-when-ada-exceptions-are-raised}@anchor{178}@anchor{gnat_ugn/gnat_and_program_execution id9}@anchor{179}
19273 @subsection Stopping When Ada Exceptions Are Raised
19276 @geindex Exceptions (in gdb)
19278 You can set catchpoints that stop the program execution when your program
19279 raises selected exceptions.
19282 @itemize *
19284 @item 
19286 @table @asis
19288 @item @emph{catch exception}
19290 Set a catchpoint that stops execution whenever (any task in the) program
19291 raises any exception.
19292 @end table
19294 @item 
19296 @table @asis
19298 @item @emph{catch exception `name`}
19300 Set a catchpoint that stops execution whenever (any task in the) program
19301 raises the exception @cite{name}.
19302 @end table
19304 @item 
19306 @table @asis
19308 @item @emph{catch exception unhandled}
19310 Set a catchpoint that stops executing whenever (any task in the) program
19311 raises an exception for which there is no handler.
19312 @end table
19314 @item 
19316 @table @asis
19318 @item @emph{info exceptions}, @emph{info exceptions `regexp`}
19320 The @cite{info exceptions} command permits the user to examine all defined
19321 exceptions within Ada programs. With a regular expression, @cite{regexp}, as
19322 argument, prints out only those exceptions whose name matches @cite{regexp}.
19323 @end table
19324 @end itemize
19326 @geindex Tasks (in gdb)
19328 @node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
19329 @anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{17a}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{17b}
19330 @subsection Ada Tasks
19333 @cite{GDB} allows the following task-related commands:
19336 @itemize *
19338 @item 
19340 @table @asis
19342 @item @emph{info tasks}
19344 This command shows a list of current Ada tasks, as in the following example:
19346 @example
19347 (gdb) info tasks
19348   ID       TID P-ID   Thread Pri State                 Name
19349    1   8088000   0   807e000  15 Child Activation Wait main_task
19350    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19351    3   809a800   1   80a4800  15 Child Activation Wait a
19352 *  4   80ae800   3   80b8000  15 Running               c
19353 @end example
19355 In this listing, the asterisk before the first task indicates it to be the
19356 currently running task. The first column lists the task ID that is used
19357 to refer to tasks in the following commands.
19358 @end table
19359 @end itemize
19361 @geindex Breakpoints and tasks
19364 @itemize *
19366 @item 
19367 @emph{break `linespec` task `taskid`}, @emph{break `linespec` task `taskid` if ...}
19369 @quotation
19371 These commands are like the @cite{break ... thread ...}.
19372 @cite{linespec} specifies source lines.
19374 Use the qualifier @code{task @emph{taskid}} with a breakpoint command
19375 to specify that you only want @cite{GDB} to stop the program when a
19376 particular Ada task reaches this breakpoint. @cite{taskid} is one of the
19377 numeric task identifiers assigned by @cite{GDB}, shown in the first
19378 column of the @code{info tasks} display.
19380 If you do not specify @code{task @emph{taskid}} when you set a
19381 breakpoint, the breakpoint applies to @emph{all} tasks of your
19382 program.
19384 You can use the @cite{task} qualifier on conditional breakpoints as
19385 well; in this case, place @code{task @emph{taskid}} before the
19386 breakpoint condition (before the @cite{if}).
19387 @end quotation
19388 @end itemize
19390 @geindex Task switching (in gdb)
19393 @itemize *
19395 @item 
19396 @emph{task `taskno`}
19398 @quotation
19400 This command allows switching to the task referred by @cite{taskno}. In
19401 particular, this allows browsing of the backtrace of the specified
19402 task. It is advisable to switch back to the original task before
19403 continuing execution otherwise the scheduling of the program may be
19404 perturbed.
19405 @end quotation
19406 @end itemize
19408 For more detailed information on the tasking support,
19409 see @cite{Debugging with GDB}.
19411 @geindex Debugging Generic Units
19413 @geindex Generics
19415 @node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
19416 @anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{17c}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{17d}
19417 @subsection Debugging Generic Units
19420 GNAT always uses code expansion for generic instantiation. This means that
19421 each time an instantiation occurs, a complete copy of the original code is
19422 made, with appropriate substitutions of formals by actuals.
19424 It is not possible to refer to the original generic entities in
19425 @cite{GDB}, but it is always possible to debug a particular instance of
19426 a generic, by using the appropriate expanded names. For example, if we have
19428 @quotation
19430 @example
19431 procedure g is
19433    generic package k is
19434       procedure kp (v1 : in out integer);
19435    end k;
19437    package body k is
19438       procedure kp (v1 : in out integer) is
19439       begin
19440          v1 := v1 + 1;
19441       end kp;
19442    end k;
19444    package k1 is new k;
19445    package k2 is new k;
19447    var : integer := 1;
19449 begin
19450    k1.kp (var);
19451    k2.kp (var);
19452    k1.kp (var);
19453    k2.kp (var);
19454 end;
19455 @end example
19456 @end quotation
19458 Then to break on a call to procedure kp in the k2 instance, simply
19459 use the command:
19461 @quotation
19463 @example
19464 (gdb) break g.k2.kp
19465 @end example
19466 @end quotation
19468 When the breakpoint occurs, you can step through the code of the
19469 instance in the normal manner and examine the values of local variables, as for
19470 other units.
19472 @geindex Remote Debugging with gdbserver
19474 @node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
19475 @anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{17e}@anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{17f}
19476 @subsection Remote Debugging with gdbserver
19479 On platforms where gdbserver is supported, it is possible to use this tool
19480 to debug your application remotely.  This can be useful in situations
19481 where the program needs to be run on a target host that is different
19482 from the host used for development, particularly when the target has
19483 a limited amount of resources (either CPU and/or memory).
19485 To do so, start your program using gdbserver on the target machine.
19486 gdbserver then automatically suspends the execution of your program
19487 at its entry point, waiting for a debugger to connect to it.  The
19488 following commands starts an application and tells gdbserver to
19489 wait for a connection with the debugger on localhost port 4444.
19491 @quotation
19493 @example
19494 $ gdbserver localhost:4444 program
19495 Process program created; pid = 5685
19496 Listening on port 4444
19497 @end example
19498 @end quotation
19500 Once gdbserver has started listening, we can tell the debugger to establish
19501 a connection with this gdbserver, and then start the same debugging session
19502 as if the program was being debugged on the same host, directly under
19503 the control of GDB.
19505 @quotation
19507 @example
19508 $ gdb program
19509 (gdb) target remote targethost:4444
19510 Remote debugging using targethost:4444
19511 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19512 (gdb) b foo.adb:3
19513 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19514 (gdb) continue
19515 Continuing.
19517 Breakpoint 1, foo () at foo.adb:4
19518 4       end foo;
19519 @end example
19520 @end quotation
19522 It is also possible to use gdbserver to attach to an already running
19523 program, in which case the execution of that program is simply suspended
19524 until the connection between the debugger and gdbserver is established.
19526 For more information on how to use gdbserver, see the @emph{Using the gdbserver Program}
19527 section in @cite{Debugging with GDB}.
19528 GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
19530 @geindex Abnormal Termination or Failure to Terminate
19532 @node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
19533 @anchor{gnat_ugn/gnat_and_program_execution gnat-abnormal-termination-or-failure-to-terminate}@anchor{180}@anchor{gnat_ugn/gnat_and_program_execution id13}@anchor{181}
19534 @subsection GNAT Abnormal Termination or Failure to Terminate
19537 When presented with programs that contain serious errors in syntax
19538 or semantics,
19539 GNAT may on rare occasions  experience problems in operation, such
19540 as aborting with a
19541 segmentation fault or illegal memory access, raising an internal
19542 exception, terminating abnormally, or failing to terminate at all.
19543 In such cases, you can activate
19544 various features of GNAT that can help you pinpoint the construct in your
19545 program that is the likely source of the problem.
19547 The following strategies are presented in increasing order of
19548 difficulty, corresponding to your experience in using GNAT and your
19549 familiarity with compiler internals.
19552 @itemize *
19554 @item 
19555 Run @emph{gcc} with the @emph{-gnatf}. This first
19556 switch causes all errors on a given line to be reported. In its absence,
19557 only the first error on a line is displayed.
19559 The @emph{-gnatdO} switch causes errors to be displayed as soon as they
19560 are encountered, rather than after compilation is terminated. If GNAT
19561 terminates prematurely or goes into an infinite loop, the last error
19562 message displayed may help to pinpoint the culprit.
19564 @item 
19565 Run @emph{gcc} with the @emph{-v (verbose)} switch. In this
19566 mode, @emph{gcc} produces ongoing information about the progress of the
19567 compilation and provides the name of each procedure as code is
19568 generated. This switch allows you to find which Ada procedure was being
19569 compiled when it encountered a code generation problem.
19570 @end itemize
19572 @geindex -gnatdc switch
19575 @itemize *
19577 @item 
19578 Run @emph{gcc} with the @emph{-gnatdc} switch. This is a GNAT specific
19579 switch that does for the front-end what @emph{-v} does
19580 for the back end. The system prints the name of each unit,
19581 either a compilation unit or nested unit, as it is being analyzed.
19583 @item 
19584 Finally, you can start
19585 @cite{gdb} directly on the @cite{gnat1} executable. @cite{gnat1} is the
19586 front-end of GNAT, and can be run independently (normally it is just
19587 called from @emph{gcc}). You can use @cite{gdb} on @cite{gnat1} as you
19588 would on a C program (but @ref{16c,,The GNAT Debugger GDB} for caveats). The
19589 @cite{where} command is the first line of attack; the variable
19590 @cite{lineno} (seen by @cite{print lineno}), used by the second phase of
19591 @cite{gnat1} and by the @emph{gcc} backend, indicates the source line at
19592 which the execution stopped, and @cite{input_file name} indicates the name of
19593 the source file.
19594 @end itemize
19596 @node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
19597 @anchor{gnat_ugn/gnat_and_program_execution naming-conventions-for-gnat-source-files}@anchor{182}@anchor{gnat_ugn/gnat_and_program_execution id14}@anchor{183}
19598 @subsection Naming Conventions for GNAT Source Files
19601 In order to examine the workings of the GNAT system, the following
19602 brief description of its organization may be helpful:
19605 @itemize *
19607 @item 
19608 Files with prefix @code{sc} contain the lexical scanner.
19610 @item 
19611 All files prefixed with @code{par} are components of the parser. The
19612 numbers correspond to chapters of the Ada Reference Manual. For example,
19613 parsing of select statements can be found in @code{par-ch9.adb}.
19615 @item 
19616 All files prefixed with @code{sem} perform semantic analysis. The
19617 numbers correspond to chapters of the Ada standard. For example, all
19618 issues involving context clauses can be found in @code{sem_ch10.adb}. In
19619 addition, some features of the language require sufficient special processing
19620 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19621 dynamic dispatching, etc.
19623 @item 
19624 All files prefixed with @code{exp} perform normalization and
19625 expansion of the intermediate representation (abstract syntax tree, or AST).
19626 these files use the same numbering scheme as the parser and semantics files.
19627 For example, the construction of record initialization procedures is done in
19628 @code{exp_ch3.adb}.
19630 @item 
19631 The files prefixed with @code{bind} implement the binder, which
19632 verifies the consistency of the compilation, determines an order of
19633 elaboration, and generates the bind file.
19635 @item 
19636 The files @code{atree.ads} and @code{atree.adb} detail the low-level
19637 data structures used by the front-end.
19639 @item 
19640 The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
19641 the abstract syntax tree as produced by the parser.
19643 @item 
19644 The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
19645 all entities, computed during semantic analysis.
19647 @item 
19648 Library management issues are dealt with in files with prefix
19649 @code{lib}.
19651 @geindex Annex A (in Ada Reference Manual)
19653 @item 
19654 Ada files with the prefix @code{a-} are children of @cite{Ada}, as
19655 defined in Annex A.
19657 @geindex Annex B (in Ada reference Manual)
19659 @item 
19660 Files with prefix @code{i-} are children of @cite{Interfaces}, as
19661 defined in Annex B.
19663 @geindex System (package in Ada Reference Manual)
19665 @item 
19666 Files with prefix @code{s-} are children of @cite{System}. This includes
19667 both language-defined children and GNAT run-time routines.
19669 @geindex GNAT (package)
19671 @item 
19672 Files with prefix @code{g-} are children of @cite{GNAT}. These are useful
19673 general-purpose packages, fully documented in their specs. All
19674 the other @code{.c} files are modifications of common @emph{gcc} files.
19675 @end itemize
19677 @node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
19678 @anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{184}@anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{185}
19679 @subsection Getting Internal Debugging Information
19682 Most compilers have internal debugging switches and modes. GNAT
19683 does also, except GNAT internal debugging switches and modes are not
19684 secret. A summary and full description of all the compiler and binder
19685 debug flags are in the file @code{debug.adb}. You must obtain the
19686 sources of the compiler to see the full detailed effects of these flags.
19688 The switches that print the source of the program (reconstructed from
19689 the internal tree) are of general interest for user programs, as are the
19690 options to print
19691 the full internal tree, and the entity table (the symbol table
19692 information). The reconstructed source provides a readable version of the
19693 program after the front-end has completed analysis and  expansion,
19694 and is useful when studying the performance of specific constructs.
19695 For example, constraint checks are indicated, complex aggregates
19696 are replaced with loops and assignments, and tasking primitives
19697 are replaced with run-time calls.
19699 @geindex traceback
19701 @geindex stack traceback
19703 @geindex stack unwinding
19705 @node Stack Traceback,,Getting Internal Debugging Information,Running and Debugging Ada Programs
19706 @anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{186}@anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{187}
19707 @subsection Stack Traceback
19710 Traceback is a mechanism to display the sequence of subprogram calls that
19711 leads to a specified execution point in a program. Often (but not always)
19712 the execution point is an instruction at which an exception has been raised.
19713 This mechanism is also known as @emph{stack unwinding} because it obtains
19714 its information by scanning the run-time stack and recovering the activation
19715 records of all active subprograms. Stack unwinding is one of the most
19716 important tools for program debugging.
19718 The first entry stored in traceback corresponds to the deepest calling level,
19719 that is to say the subprogram currently executing the instruction
19720 from which we want to obtain the traceback.
19722 Note that there is no runtime performance penalty when stack traceback
19723 is enabled, and no exception is raised during program execution.
19725 @geindex traceback
19726 @geindex non-symbolic
19728 @menu
19729 * Non-Symbolic Traceback:: 
19730 * Symbolic Traceback:: 
19732 @end menu
19734 @node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
19735 @anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{188}@anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{189}
19736 @subsubsection Non-Symbolic Traceback
19739 Note: this feature is not supported on all platforms. See
19740 @code{GNAT.Traceback} spec in @code{g-traceb.ads}
19741 for a complete list of supported platforms.
19743 @subsubheading Tracebacks From an Unhandled Exception
19746 A runtime non-symbolic traceback is a list of addresses of call instructions.
19747 To enable this feature you must use the @emph{-E}
19748 @cite{gnatbind}'s option. With this option a stack traceback is stored as part
19749 of exception information. You can retrieve this information using the
19750 @cite{addr2line} tool.
19752 Here is a simple example:
19754 @quotation
19756 @example
19757 procedure STB is
19759    procedure P1 is
19760    begin
19761       raise Constraint_Error;
19762    end P1;
19764    procedure P2 is
19765    begin
19766       P1;
19767    end P2;
19769 begin
19770    P2;
19771 end STB;
19772 @end example
19774 @example
19775 $ gnatmake stb -bargs -E
19776 $ stb
19778 Execution terminated by unhandled exception
19779 Exception name: CONSTRAINT_ERROR
19780 Message: stb.adb:5
19781 Call stack traceback locations:
19782 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19783 @end example
19784 @end quotation
19786 As we see the traceback lists a sequence of addresses for the unhandled
19787 exception @cite{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19788 guess that this exception come from procedure P1. To translate these
19789 addresses into the source lines where the calls appear, the
19790 @cite{addr2line} tool, described below, is invaluable. The use of this tool
19791 requires the program to be compiled with debug information.
19793 @quotation
19795 @example
19796 $ gnatmake -g stb -bargs -E
19797 $ stb
19799 Execution terminated by unhandled exception
19800 Exception name: CONSTRAINT_ERROR
19801 Message: stb.adb:5
19802 Call stack traceback locations:
19803 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19805 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19806    0x4011f1 0x77e892a4
19808 00401373 at d:/stb/stb.adb:5
19809 0040138B at d:/stb/stb.adb:10
19810 0040139C at d:/stb/stb.adb:14
19811 00401335 at d:/stb/b~stb.adb:104
19812 004011C4 at /build/.../crt1.c:200
19813 004011F1 at /build/.../crt1.c:222
19814 77E892A4 in ?? at ??:0
19815 @end example
19816 @end quotation
19818 The @cite{addr2line} tool has several other useful options:
19820 @quotation
19823 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
19824 @item
19826 @code{--functions}
19828 @tab
19830 to get the function name corresponding to any location
19832 @item
19834 @code{--demangle=gnat}
19836 @tab
19838 to use the gnat decoding mode for the function names.
19839 Note that for binutils version 2.9.x the option is
19840 simply @code{--demangle}.
19842 @end multitable
19845 @example
19846 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19847    0x40139c 0x401335 0x4011c4 0x4011f1
19849 00401373 in stb.p1 at d:/stb/stb.adb:5
19850 0040138B in stb.p2 at d:/stb/stb.adb:10
19851 0040139C in stb at d:/stb/stb.adb:14
19852 00401335 in main at d:/stb/b~stb.adb:104
19853 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
19854 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
19855 @end example
19856 @end quotation
19858 From this traceback we can see that the exception was raised in
19859 @code{stb.adb} at line 5, which was reached from a procedure call in
19860 @code{stb.adb} at line 10, and so on. The @code{b~std.adb} is the binder file,
19861 which contains the call to the main program.
19862 @ref{11a,,Running gnatbind}. The remaining entries are assorted runtime routines,
19863 and the output will vary from platform to platform.
19865 It is also possible to use @cite{GDB} with these traceback addresses to debug
19866 the program. For example, we can break at a given code location, as reported
19867 in the stack traceback:
19869 @quotation
19871 @example
19872 $ gdb -nw stb
19873 @end example
19874 @end quotation
19876 Furthermore, this feature is not implemented inside Windows DLL. Only
19877 the non-symbolic traceback is reported in this case.
19879 @quotation
19881 @example
19882 (gdb) break *0x401373
19883 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19884 @end example
19885 @end quotation
19887 It is important to note that the stack traceback addresses
19888 do not change when debug information is included. This is particularly useful
19889 because it makes it possible to release software without debug information (to
19890 minimize object size), get a field report that includes a stack traceback
19891 whenever an internal bug occurs, and then be able to retrieve the sequence
19892 of calls with the same program compiled with debug information.
19894 @subsubheading Tracebacks From Exception Occurrences
19897 Non-symbolic tracebacks are obtained by using the @emph{-E} binder argument.
19898 The stack traceback is attached to the exception information string, and can
19899 be retrieved in an exception handler within the Ada program, by means of the
19900 Ada facilities defined in @cite{Ada.Exceptions}. Here is a simple example:
19902 @quotation
19904 @example
19905 with Ada.Text_IO;
19906 with Ada.Exceptions;
19908 procedure STB is
19910    use Ada;
19911    use Ada.Exceptions;
19913    procedure P1 is
19914       K : Positive := 1;
19915    begin
19916       K := K - 1;
19917    exception
19918       when E : others =>
19919          Text_IO.Put_Line (Exception_Information (E));
19920    end P1;
19922    procedure P2 is
19923    begin
19924       P1;
19925    end P2;
19927 begin
19928    P2;
19929 end STB;
19930 @end example
19931 @end quotation
19933 This program will output:
19935 @quotation
19937 @example
19938 $ stb
19940 Exception name: CONSTRAINT_ERROR
19941 Message: stb.adb:12
19942 Call stack traceback locations:
19943 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19944 @end example
19945 @end quotation
19947 @subsubheading Tracebacks From Anywhere in a Program
19950 It is also possible to retrieve a stack traceback from anywhere in a
19951 program. For this you need to
19952 use the @cite{GNAT.Traceback} API. This package includes a procedure called
19953 @cite{Call_Chain} that computes a complete stack traceback, as well as useful
19954 display procedures described below. It is not necessary to use the
19955 @emph{-E gnatbind} option in this case, because the stack traceback mechanism
19956 is invoked explicitly.
19958 In the following example we compute a traceback at a specific location in
19959 the program, and we display it using @cite{GNAT.Debug_Utilities.Image} to
19960 convert addresses to strings:
19962 @quotation
19964 @example
19965 with Ada.Text_IO;
19966 with GNAT.Traceback;
19967 with GNAT.Debug_Utilities;
19969 procedure STB is
19971    use Ada;
19972    use GNAT;
19973    use GNAT.Traceback;
19975    procedure P1 is
19976       TB  : Tracebacks_Array (1 .. 10);
19977       --  We are asking for a maximum of 10 stack frames.
19978       Len : Natural;
19979       --  Len will receive the actual number of stack frames returned.
19980    begin
19981       Call_Chain (TB, Len);
19983       Text_IO.Put ("In STB.P1 : ");
19985       for K in 1 .. Len loop
19986          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19987          Text_IO.Put (' ');
19988       end loop;
19990       Text_IO.New_Line;
19991    end P1;
19993    procedure P2 is
19994    begin
19995       P1;
19996    end P2;
19998 begin
19999    P2;
20000 end STB;
20001 @end example
20003 @example
20004 $ gnatmake -g stb
20005 $ stb
20007 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20008 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20009 @end example
20010 @end quotation
20012 You can then get further information by invoking the @cite{addr2line}
20013 tool as described earlier (note that the hexadecimal addresses
20014 need to be specified in C format, with a leading '0x').
20016 @geindex traceback
20017 @geindex symbolic
20019 @node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
20020 @anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{18a}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{18b}
20021 @subsubsection Symbolic Traceback
20024 A symbolic traceback is a stack traceback in which procedure names are
20025 associated with each code location.
20027 Note that this feature is not supported on all platforms. See
20028 @code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
20029 list of currently supported platforms.
20031 Note that the symbolic traceback requires that the program be compiled
20032 with debug information. If it is not compiled with debug information
20033 only the non-symbolic information will be valid.
20035 @subsubheading Tracebacks From Exception Occurrences
20038 Here is an example:
20040 @quotation
20042 @example
20043 with Ada.Text_IO;
20044 with GNAT.Traceback.Symbolic;
20046 procedure STB is
20048    procedure P1 is
20049    begin
20050       raise Constraint_Error;
20051    end P1;
20053    procedure P2 is
20054    begin
20055       P1;
20056    end P2;
20058    procedure P3 is
20059    begin
20060       P2;
20061    end P3;
20063 begin
20064    P3;
20065 exception
20066    when E : others =>
20067       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20068 end STB;
20069 @end example
20071 @example
20072 $ gnatmake -g .\stb -bargs -E
20073 $ stb
20075 0040149F in stb.p1 at stb.adb:8
20076 004014B7 in stb.p2 at stb.adb:13
20077 004014CF in stb.p3 at stb.adb:18
20078 004015DD in ada.stb at stb.adb:22
20079 00401461 in main at b~stb.adb:168
20080 004011C4 in __mingw_CRTStartup at crt1.c:200
20081 004011F1 in mainCRTStartup at crt1.c:222
20082 77E892A4 in ?? at ??:0
20083 @end example
20084 @end quotation
20086 In the above example the @code{.\} syntax in the @emph{gnatmake} command
20087 is currently required by @emph{addr2line} for files that are in
20088 the current working directory.
20089 Moreover, the exact sequence of linker options may vary from platform
20090 to platform.
20091 The above @emph{-largs} section is for Windows platforms. By contrast,
20092 under Unix there is no need for the @emph{-largs} section.
20093 Differences across platforms are due to details of linker implementation.
20095 @subsubheading Tracebacks From Anywhere in a Program
20098 It is possible to get a symbolic stack traceback
20099 from anywhere in a program, just as for non-symbolic tracebacks.
20100 The first step is to obtain a non-symbolic
20101 traceback, and then call @cite{Symbolic_Traceback} to compute the symbolic
20102 information. Here is an example:
20104 @quotation
20106 @example
20107 with Ada.Text_IO;
20108 with GNAT.Traceback;
20109 with GNAT.Traceback.Symbolic;
20111 procedure STB is
20113    use Ada;
20114    use GNAT.Traceback;
20115    use GNAT.Traceback.Symbolic;
20117    procedure P1 is
20118       TB  : Tracebacks_Array (1 .. 10);
20119       --  We are asking for a maximum of 10 stack frames.
20120       Len : Natural;
20121       --  Len will receive the actual number of stack frames returned.
20122    begin
20123       Call_Chain (TB, Len);
20124       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20125    end P1;
20127    procedure P2 is
20128    begin
20129       P1;
20130    end P2;
20132 begin
20133    P2;
20134 end STB;
20135 @end example
20136 @end quotation
20138 @subsubheading Automatic Symbolic Tracebacks
20141 Symbolic tracebacks may also be enabled by using the -Es switch to gnatbind (as
20142 in @cite{gprbuild -g ... -bargs -Es}).
20143 This will cause the Exception_Information to contain a symbolic traceback,
20144 which will also be printed if an unhandled exception terminates the
20145 program.
20147 @geindex Code Coverage
20149 @geindex Profiling
20151 @node Code Coverage and Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
20152 @anchor{gnat_ugn/gnat_and_program_execution id19}@anchor{166}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-and-profiling}@anchor{25}
20153 @section Code Coverage and Profiling
20156 This section describes how to use the @cite{gcov} coverage testing tool and
20157 the @cite{gprof} profiler tool on Ada programs.
20159 @geindex gcov
20161 @menu
20162 * Code Coverage of Ada Programs with gcov:: 
20163 * Profiling an Ada Program with gprof:: 
20165 @end menu
20167 @node Code Coverage of Ada Programs with gcov,Profiling an Ada Program with gprof,,Code Coverage and Profiling
20168 @anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{18c}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-of-ada-programs-with-gcov}@anchor{18d}
20169 @subsection Code Coverage of Ada Programs with gcov
20172 @cite{gcov} is a test coverage program: it analyzes the execution of a given
20173 program on selected tests, to help you determine the portions of the program
20174 that are still untested.
20176 @cite{gcov} is part of the GCC suite, and is described in detail in the GCC
20177 User's Guide. You can refer to this documentation for a more complete
20178 description.
20180 This chapter provides a quick startup guide, and
20181 details some GNAT-specific features.
20183 @menu
20184 * Quick startup guide:: 
20185 * GNAT specifics:: 
20187 @end menu
20189 @node Quick startup guide,GNAT specifics,,Code Coverage of Ada Programs with gcov
20190 @anchor{gnat_ugn/gnat_and_program_execution id21}@anchor{18e}@anchor{gnat_ugn/gnat_and_program_execution quick-startup-guide}@anchor{18f}
20191 @subsubsection Quick startup guide
20194 In order to perform coverage analysis of a program using @cite{gcov}, several
20195 steps are needed:
20198 @enumerate 
20200 @item 
20201 Instrument the code during the compilation process,
20203 @item 
20204 Execute the instrumented program, and
20206 @item 
20207 Invoke the @cite{gcov} tool to generate the coverage results.
20208 @end enumerate
20210 @geindex -fprofile-arcs (gcc)
20212 @geindex -ftest-coverage (gcc
20214 @geindex -fprofile-arcs (gnatbind)
20216 The code instrumentation needed by gcov is created at the object level.
20217 The source code is not modified in any way, because the instrumentation code is
20218 inserted by gcc during the compilation process. To compile your code with code
20219 coverage activated, you need to recompile your whole project using the
20220 switches
20221 @cite{-fprofile-arcs} and @cite{-ftest-coverage}, and link it using
20222 @cite{-fprofile-arcs}.
20224 @quotation
20226 @example
20227 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \\
20228    -largs -fprofile-arcs
20229 @end example
20230 @end quotation
20232 This compilation process will create @code{.gcno} files together with
20233 the usual object files.
20235 Once the program is compiled with coverage instrumentation, you can
20236 run it as many times as needed -- on portions of a test suite for
20237 example. The first execution will produce @code{.gcda} files at the
20238 same location as the @code{.gcno} files.  Subsequent executions
20239 will update those files, so that a cumulative result of the covered
20240 portions of the program is generated.
20242 Finally, you need to call the @cite{gcov} tool. The different options of
20243 @cite{gcov} are described in the GCC User's Guide, section 'Invoking gcov'.
20245 This will create annotated source files with a @code{.gcov} extension:
20246 @code{my_main.adb} file will be analyzed in @code{my_main.adb.gcov}.
20248 @node GNAT specifics,,Quick startup guide,Code Coverage of Ada Programs with gcov
20249 @anchor{gnat_ugn/gnat_and_program_execution gnat-specifics}@anchor{190}@anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{191}
20250 @subsubsection GNAT specifics
20253 Because of Ada semantics, portions of the source code may be shared among
20254 several object files. This is the case for example when generics are
20255 involved, when inlining is active  or when declarations generate  initialisation
20256 calls. In order to take
20257 into account this shared code, you need to call @cite{gcov} on all
20258 source files of the tested program at once.
20260 The list of source files might exceed the system's maximum command line
20261 length. In order to bypass this limitation, a new mechanism has been
20262 implemented in @cite{gcov}: you can now list all your project's files into a
20263 text file, and provide this file to gcov as a parameter,  preceded by a @code{@@}
20264 (e.g. @code{gcov @@mysrclist.txt}).
20266 Note that on AIX compiling a static library with @cite{-fprofile-arcs} is
20267 not supported as there can be unresolved symbols during the final link.
20269 @geindex gprof
20271 @geindex Profiling
20273 @node Profiling an Ada Program with gprof,,Code Coverage of Ada Programs with gcov,Code Coverage and Profiling
20274 @anchor{gnat_ugn/gnat_and_program_execution profiling-an-ada-program-with-gprof}@anchor{192}@anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{193}
20275 @subsection Profiling an Ada Program with gprof
20278 This section is not meant to be an exhaustive documentation of @cite{gprof}.
20279 Full documentation for it can be found in the @cite{GNU Profiler User's Guide}
20280 documentation that is part of this GNAT distribution.
20282 Profiling a program helps determine the parts of a program that are executed
20283 most often, and are therefore the most time-consuming.
20285 @cite{gprof} is the standard GNU profiling tool; it has been enhanced to
20286 better handle Ada programs and multitasking.
20287 It is currently supported on the following platforms
20290 @itemize *
20292 @item 
20293 linux x86/x86_64
20295 @item 
20296 solaris sparc/sparc64/x86
20298 @item 
20299 windows x86
20300 @end itemize
20302 In order to profile a program using @cite{gprof}, several steps are needed:
20305 @enumerate 
20307 @item 
20308 Instrument the code, which requires a full recompilation of the project with the
20309 proper switches.
20311 @item 
20312 Execute the program under the analysis conditions, i.e. with the desired
20313 input.
20315 @item 
20316 Analyze the results using the @cite{gprof} tool.
20317 @end enumerate
20319 The following sections detail the different steps, and indicate how
20320 to interpret the results.
20322 @menu
20323 * Compilation for profiling:: 
20324 * Program execution:: 
20325 * Running gprof:: 
20326 * Interpretation of profiling results:: 
20328 @end menu
20330 @node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
20331 @anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{194}@anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{195}
20332 @subsubsection Compilation for profiling
20335 @geindex -pg (gcc)
20336 @geindex for profiling
20338 @geindex -pg (gnatlink)
20339 @geindex for profiling
20341 In order to profile a program the first step is to tell the compiler
20342 to generate the necessary profiling information. The compiler switch to be used
20343 is @code{-pg}, which must be added to other compilation switches. This
20344 switch needs to be specified both during compilation and link stages, and can
20345 be specified once when using gnatmake:
20347 @quotation
20349 @example
20350 $ gnatmake -f -pg -P my_project
20351 @end example
20352 @end quotation
20354 Note that only the objects that were compiled with the @code{-pg} switch will
20355 be profiled; if you need to profile your whole project, use the @code{-f}
20356 gnatmake switch to force full recompilation.
20358 @node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
20359 @anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{196}@anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{197}
20360 @subsubsection Program execution
20363 Once the program has been compiled for profiling, you can run it as usual.
20365 The only constraint imposed by profiling is that the program must terminate
20366 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20367 properly analyzed.
20369 Once the program completes execution, a data file called @code{gmon.out} is
20370 generated in the directory where the program was launched from. If this file
20371 already exists, it will be overwritten.
20373 @node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
20374 @anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{198}@anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{199}
20375 @subsubsection Running gprof
20378 The @cite{gprof} tool is called as follow:
20380 @quotation
20382 @example
20383 $ gprof my_prog gmon.out
20384 @end example
20385 @end quotation
20387 or simply:
20389 @quotation
20391 @example
20392 $  gprof my_prog
20393 @end example
20394 @end quotation
20396 The complete form of the gprof command line is the following:
20398 @quotation
20400 @example
20401 $ gprof [switches] [executable [data-file]]
20402 @end example
20403 @end quotation
20405 @cite{gprof} supports numerous switches. The order of these
20406 switch does not matter. The full list of options can be found in
20407 the GNU Profiler User's Guide documentation that comes with this documentation.
20409 The following is the subset of those switches that is most relevant:
20411 @geindex --demangle (gprof)
20414 @table @asis
20416 @item @code{--demangle[=@emph{style}]}, @code{--no-demangle}
20418 These options control whether symbol names should be demangled when
20419 printing output.  The default is to demangle C++ symbols.  The
20420 @code{--no-demangle} option may be used to turn off demangling. Different
20421 compilers have different mangling styles.  The optional demangling style
20422 argument can be used to choose an appropriate demangling style for your
20423 compiler, in particular Ada symbols generated by GNAT can be demangled using
20424 @code{--demangle=gnat}.
20425 @end table
20427 @geindex -e (gprof)
20430 @table @asis
20432 @item @code{-e @emph{function_name}}
20434 The @code{-e @emph{function}} option tells @cite{gprof} not to print
20435 information about the function @cite{function_name} (and its
20436 children...) in the call graph.  The function will still be listed
20437 as a child of any functions that call it, but its index number will be
20438 shown as @code{[not printed]}.  More than one @code{-e} option may be
20439 given; only one @cite{function_name} may be indicated with each @code{-e}
20440 option.
20441 @end table
20443 @geindex -E (gprof)
20446 @table @asis
20448 @item @code{-E @emph{function_name}}
20450 The @code{-E @emph{function}} option works like the @code{-e} option, but
20451 execution time spent in the function (and children who were not called from
20452 anywhere else), will not be used to compute the percentages-of-time for
20453 the call graph.  More than one @code{-E} option may be given; only one
20454 @cite{function_name} may be indicated with each @code{-E} option.
20455 @end table
20457 @geindex -f (gprof)
20460 @table @asis
20462 @item @code{-f @emph{function_name}}
20464 The @code{-f @emph{function}} option causes @cite{gprof} to limit the
20465 call graph to the function @cite{function_name} and its children (and
20466 their children...).  More than one @code{-f} option may be given;
20467 only one @cite{function_name} may be indicated with each @code{-f}
20468 option.
20469 @end table
20471 @geindex -F (gprof)
20474 @table @asis
20476 @item @code{-F @emph{function_name}}
20478 The @code{-F @emph{function}} option works like the @code{-f} option, but
20479 only time spent in the function and its children (and their
20480 children...) will be used to determine total-time and
20481 percentages-of-time for the call graph.  More than one @code{-F} option
20482 may be given; only one @cite{function_name} may be indicated with each
20483 @code{-F} option.  The @code{-F} option overrides the @code{-E} option.
20484 @end table
20486 @node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
20487 @anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{19a}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{19b}
20488 @subsubsection Interpretation of profiling results
20491 The results of the profiling analysis are represented by two arrays: the
20492 'flat profile' and the 'call graph'. Full documentation of those outputs
20493 can be found in the GNU Profiler User's Guide.
20495 The flat profile shows the time spent in each function of the program, and how
20496 many time it has been called. This allows you to locate easily the most
20497 time-consuming functions.
20499 The call graph shows, for each subprogram, the subprograms that call it,
20500 and the subprograms that it calls. It also provides an estimate of the time
20501 spent in each of those callers/called subprograms.
20503 @node Improving Performance,Overflow Check Handling in GNAT,Code Coverage and Profiling,GNAT and Program Execution
20504 @anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{26}@anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{167}
20505 @section Improving Performance
20508 @geindex Improving performance
20510 This section presents several topics related to program performance.
20511 It first describes some of the tradeoffs that need to be considered
20512 and some of the techniques for making your program run faster.
20515 It then documents the unused subprogram/data elimination feature,
20516 which can reduce the size of program executables.
20518 @menu
20519 * Performance Considerations:: 
20520 * Text_IO Suggestions:: 
20521 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
20523 @end menu
20525 @node Performance Considerations,Text_IO Suggestions,,Improving Performance
20526 @anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{19c}@anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{19d}
20527 @subsection Performance Considerations
20530 The GNAT system provides a number of options that allow a trade-off
20531 between
20534 @itemize *
20536 @item 
20537 performance of the generated code
20539 @item 
20540 speed of compilation
20542 @item 
20543 minimization of dependences and recompilation
20545 @item 
20546 the degree of run-time checking.
20547 @end itemize
20549 The defaults (if no options are selected) aim at improving the speed
20550 of compilation and minimizing dependences, at the expense of performance
20551 of the generated code:
20554 @itemize *
20556 @item 
20557 no optimization
20559 @item 
20560 no inlining of subprogram calls
20562 @item 
20563 all run-time checks enabled except overflow and elaboration checks
20564 @end itemize
20566 These options are suitable for most program development purposes. This
20567 section describes how you can modify these choices, and also provides
20568 some guidelines on debugging optimized code.
20570 @menu
20571 * Controlling Run-Time Checks:: 
20572 * Use of Restrictions:: 
20573 * Optimization Levels:: 
20574 * Debugging Optimized Code:: 
20575 * Inlining of Subprograms:: 
20576 * Floating_Point_Operations:: 
20577 * Vectorization of loops:: 
20578 * Other Optimization Switches:: 
20579 * Optimization and Strict Aliasing:: 
20580 * Aliased Variables and Optimization:: 
20581 * Atomic Variables and Optimization:: 
20582 * Passive Task Optimization:: 
20584 @end menu
20586 @node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
20587 @anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{19e}@anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{19f}
20588 @subsubsection Controlling Run-Time Checks
20591 By default, GNAT generates all run-time checks, except stack overflow
20592 checks, and checks for access before elaboration on subprogram
20593 calls. The latter are not required in default mode, because all
20594 necessary checking is done at compile time.
20596 @geindex -gnatp (gcc)
20598 @geindex -gnato (gcc)
20600 The gnat switch, @emph{-gnatp} allows this default to be modified. See
20601 @ref{f9,,Run-Time Checks}.
20603 Our experience is that the default is suitable for most development
20604 purposes.
20606 Elaboration checks are off by default, and also not needed by default, since
20607 GNAT uses a static elaboration analysis approach that avoids the need for
20608 run-time checking. This manual contains a full chapter discussing the issue
20609 of elaboration checks, and if the default is not satisfactory for your use,
20610 you should read this chapter.
20612 For validity checks, the minimal checks required by the Ada Reference
20613 Manual (for case statements and assignments to array elements) are on
20614 by default. These can be suppressed by use of the @emph{-gnatVn} switch.
20615 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
20616 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
20617 it may be reasonable to routinely use @emph{-gnatVn}. Validity checks
20618 are also suppressed entirely if @emph{-gnatp} is used.
20620 @geindex Overflow checks
20622 @geindex Checks
20623 @geindex overflow
20625 @geindex Suppress
20627 @geindex Unsuppress
20629 @geindex pragma Suppress
20631 @geindex pragma Unsuppress
20633 Note that the setting of the switches controls the default setting of
20634 the checks. They may be modified using either @cite{pragma Suppress} (to
20635 remove checks) or @cite{pragma Unsuppress} (to add back suppressed
20636 checks) in the program source.
20638 @node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
20639 @anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{1a0}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{1a1}
20640 @subsubsection Use of Restrictions
20643 The use of pragma Restrictions allows you to control which features are
20644 permitted in your program. Apart from the obvious point that if you avoid
20645 relatively expensive features like finalization (enforceable by the use
20646 of pragma Restrictions (No_Finalization), the use of this pragma does not
20647 affect the generated code in most cases.
20649 One notable exception to this rule is that the possibility of task abort
20650 results in some distributed overhead, particularly if finalization or
20651 exception handlers are used. The reason is that certain sections of code
20652 have to be marked as non-abortable.
20654 If you use neither the @cite{abort} statement, nor asynchronous transfer
20655 of control (@cite{select ... then abort}), then this distributed overhead
20656 is removed, which may have a general positive effect in improving
20657 overall performance.  Especially code involving frequent use of tasking
20658 constructs and controlled types will show much improved performance.
20659 The relevant restrictions pragmas are
20661 @quotation
20663 @example
20664 pragma Restrictions (No_Abort_Statements);
20665 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
20666 @end example
20667 @end quotation
20669 It is recommended that these restriction pragmas be used if possible. Note
20670 that this also means that you can write code without worrying about the
20671 possibility of an immediate abort at any point.
20673 @node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
20674 @anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{1a2}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{fc}
20675 @subsubsection Optimization Levels
20678 @geindex -O (gcc)
20680 Without any optimization option,
20681 the compiler's goal is to reduce the cost of
20682 compilation and to make debugging produce the expected results.
20683 Statements are independent: if you stop the program with a breakpoint between
20684 statements, you can then assign a new value to any variable or change
20685 the program counter to any other statement in the subprogram and get exactly
20686 the results you would expect from the source code.
20688 Turning on optimization makes the compiler attempt to improve the
20689 performance and/or code size at the expense of compilation time and
20690 possibly the ability to debug the program.
20692 If you use multiple
20693 -O options, with or without level numbers,
20694 the last such option is the one that is effective.
20696 The default is optimization off. This results in the fastest compile
20697 times, but GNAT makes absolutely no attempt to optimize, and the
20698 generated programs are considerably larger and slower than when
20699 optimization is enabled. You can use the
20700 @emph{-O} switch (the permitted forms are @emph{-O0}, @emph{-O1}
20701 @emph{-O2}, @emph{-O3}, and @emph{-Os})
20702 to @emph{gcc} to control the optimization level:
20705 @itemize *
20707 @item 
20709 @table @asis
20711 @item @emph{-O0}
20713 No optimization (the default);
20714 generates unoptimized code but has
20715 the fastest compilation time.
20717 Note that many other compilers do fairly extensive optimization
20718 even if 'no optimization' is specified. With gcc, it is
20719 very unusual to use -O0 for production if
20720 execution time is of any concern, since -O0
20721 really does mean no optimization at all. This difference between
20722 gcc and other compilers should be kept in mind when doing
20723 performance comparisons.
20724 @end table
20726 @item 
20728 @table @asis
20730 @item @emph{-O1}
20732 Moderate optimization;
20733 optimizes reasonably well but does not
20734 degrade compilation time significantly.
20735 @end table
20737 @item 
20739 @table @asis
20741 @item @emph{-O2}
20743 Full optimization;
20744 generates highly optimized code and has
20745 the slowest compilation time.
20746 @end table
20748 @item 
20750 @table @asis
20752 @item @emph{-O3}
20754 Full optimization as in @emph{-O2};
20755 also uses more aggressive automatic inlining of subprograms within a unit
20756 (@ref{10f,,Inlining of Subprograms}) and attempts to vectorize loops.
20757 @end table
20759 @item 
20761 @table @asis
20763 @item @emph{-Os}
20765 Optimize space usage (code and data) of resulting program.
20766 @end table
20767 @end itemize
20769 Higher optimization levels perform more global transformations on the
20770 program and apply more expensive analysis algorithms in order to generate
20771 faster and more compact code. The price in compilation time, and the
20772 resulting improvement in execution time,
20773 both depend on the particular application and the hardware environment.
20774 You should experiment to find the best level for your application.
20776 Since the precise set of optimizations done at each level will vary from
20777 release to release (and sometime from target to target), it is best to think
20778 of the optimization settings in general terms.
20779 See the @emph{Options That Control Optimization} section in
20780 @cite{Using the GNU Compiler Collection (GCC)}
20781 for details about
20782 the @emph{-O} settings and a number of @emph{-f} options that
20783 individually enable or disable specific optimizations.
20785 Unlike some other compilation systems, @emph{gcc} has
20786 been tested extensively at all optimization levels. There are some bugs
20787 which appear only with optimization turned on, but there have also been
20788 bugs which show up only in @emph{unoptimized} code. Selecting a lower
20789 level of optimization does not improve the reliability of the code
20790 generator, which in practice is highly reliable at all optimization
20791 levels.
20793 Note regarding the use of @emph{-O3}: The use of this optimization level
20794 is generally discouraged with GNAT, since it often results in larger
20795 executables which may run more slowly. See further discussion of this point
20796 in @ref{10f,,Inlining of Subprograms}.
20798 @node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
20799 @anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{1a3}@anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{1a4}
20800 @subsubsection Debugging Optimized Code
20803 @geindex Debugging optimized code
20805 @geindex Optimization and debugging
20807 Although it is possible to do a reasonable amount of debugging at
20808 nonzero optimization levels,
20809 the higher the level the more likely that
20810 source-level constructs will have been eliminated by optimization.
20811 For example, if a loop is strength-reduced, the loop
20812 control variable may be completely eliminated and thus cannot be
20813 displayed in the debugger.
20814 This can only happen at @emph{-O2} or @emph{-O3}.
20815 Explicit temporary variables that you code might be eliminated at
20816 level @emph{-O1} or higher.
20818 @geindex -g (gcc)
20820 The use of the @emph{-g} switch,
20821 which is needed for source-level debugging,
20822 affects the size of the program executable on disk,
20823 and indeed the debugging information can be quite large.
20824 However, it has no effect on the generated code (and thus does not
20825 degrade performance)
20827 Since the compiler generates debugging tables for a compilation unit before
20828 it performs optimizations, the optimizing transformations may invalidate some
20829 of the debugging data.  You therefore need to anticipate certain
20830 anomalous situations that may arise while debugging optimized code.
20831 These are the most common cases:
20834 @itemize *
20836 @item 
20837 @emph{The 'hopping Program Counter':}  Repeated @cite{step} or @cite{next}
20838 commands show
20839 the PC bouncing back and forth in the code.  This may result from any of
20840 the following optimizations:
20843 @itemize -
20845 @item 
20846 @emph{Common subexpression elimination:} using a single instance of code for a
20847 quantity that the source computes several times.  As a result you
20848 may not be able to stop on what looks like a statement.
20850 @item 
20851 @emph{Invariant code motion:} moving an expression that does not change within a
20852 loop, to the beginning of the loop.
20854 @item 
20855 @emph{Instruction scheduling:} moving instructions so as to
20856 overlap loads and stores (typically) with other code, or in
20857 general to move computations of values closer to their uses. Often
20858 this causes you to pass an assignment statement without the assignment
20859 happening and then later bounce back to the statement when the
20860 value is actually needed.  Placing a breakpoint on a line of code
20861 and then stepping over it may, therefore, not always cause all the
20862 expected side-effects.
20863 @end itemize
20865 @item 
20866 @emph{The 'big leap':} More commonly known as @emph{cross-jumping}, in which
20867 two identical pieces of code are merged and the program counter suddenly
20868 jumps to a statement that is not supposed to be executed, simply because
20869 it (and the code following) translates to the same thing as the code
20870 that @emph{was} supposed to be executed.  This effect is typically seen in
20871 sequences that end in a jump, such as a @cite{goto}, a @cite{return}, or
20872 a @cite{break} in a C @cite{switch} statement.
20874 @item 
20875 @emph{The 'roving variable':} The symptom is an unexpected value in a variable.
20876 There are various reasons for this effect:
20879 @itemize -
20881 @item 
20882 In a subprogram prologue, a parameter may not yet have been moved to its
20883 'home'.
20885 @item 
20886 A variable may be dead, and its register re-used.  This is
20887 probably the most common cause.
20889 @item 
20890 As mentioned above, the assignment of a value to a variable may
20891 have been moved.
20893 @item 
20894 A variable may be eliminated entirely by value propagation or
20895 other means.  In this case, GCC may incorrectly generate debugging
20896 information for the variable
20897 @end itemize
20899 In general, when an unexpected value appears for a local variable or parameter
20900 you should first ascertain if that value was actually computed by
20901 your program, as opposed to being incorrectly reported by the debugger.
20902 Record fields or
20903 array elements in an object designated by an access value
20904 are generally less of a problem, once you have ascertained that the access
20905 value is sensible.
20906 Typically, this means checking variables in the preceding code and in the
20907 calling subprogram to verify that the value observed is explainable from other
20908 values (one must apply the procedure recursively to those
20909 other values); or re-running the code and stopping a little earlier
20910 (perhaps before the call) and stepping to better see how the variable obtained
20911 the value in question; or continuing to step @emph{from} the point of the
20912 strange value to see if code motion had simply moved the variable's
20913 assignments later.
20914 @end itemize
20916 In light of such anomalies, a recommended technique is to use @emph{-O0}
20917 early in the software development cycle, when extensive debugging capabilities
20918 are most needed, and then move to @emph{-O1} and later @emph{-O2} as
20919 the debugger becomes less critical.
20920 Whether to use the @emph{-g} switch in the release version is
20921 a release management issue.
20922 Note that if you use @emph{-g} you can then use the @emph{strip} program
20923 on the resulting executable,
20924 which removes both debugging information and global symbols.
20926 @node Inlining of Subprograms,Floating_Point_Operations,Debugging Optimized Code,Performance Considerations
20927 @anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{1a5}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{10f}
20928 @subsubsection Inlining of Subprograms
20931 A call to a subprogram in the current unit is inlined if all the
20932 following conditions are met:
20935 @itemize *
20937 @item 
20938 The optimization level is at least @emph{-O1}.
20940 @item 
20941 The called subprogram is suitable for inlining: It must be small enough
20942 and not contain something that @emph{gcc} cannot support in inlined
20943 subprograms.
20945 @geindex pragma Inline
20947 @geindex Inline
20949 @item 
20950 Any one of the following applies: @cite{pragma Inline} is applied to the
20951 subprogram and the @emph{-gnatn} switch is specified; the
20952 subprogram is local to the unit and called once from within it; the
20953 subprogram is small and optimization level @emph{-O2} is specified;
20954 optimization level @emph{-O3} is specified.
20955 @end itemize
20957 Calls to subprograms in @emph{with}ed units are normally not inlined.
20958 To achieve actual inlining (that is, replacement of the call by the code
20959 in the body of the subprogram), the following conditions must all be true:
20962 @itemize *
20964 @item 
20965 The optimization level is at least @emph{-O1}.
20967 @item 
20968 The called subprogram is suitable for inlining: It must be small enough
20969 and not contain something that @emph{gcc} cannot support in inlined
20970 subprograms.
20972 @item 
20973 The call appears in a body (not in a package spec).
20975 @item 
20976 There is a @cite{pragma Inline} for the subprogram.
20978 @item 
20979 The @emph{-gnatn} switch is used on the command line.
20980 @end itemize
20982 Even if all these conditions are met, it may not be possible for
20983 the compiler to inline the call, due to the length of the body,
20984 or features in the body that make it impossible for the compiler
20985 to do the inlining.
20987 Note that specifying the @emph{-gnatn} switch causes additional
20988 compilation dependencies. Consider the following:
20990 @quotation
20992 @example
20993 package R is
20994    procedure Q;
20995    pragma Inline (Q);
20996 end R;
20997 package body R is
20998    ...
20999 end R;
21001 with R;
21002 procedure Main is
21003 begin
21004    ...
21005    R.Q;
21006 end Main;
21007 @end example
21008 @end quotation
21010 With the default behavior (no @emph{-gnatn} switch specified), the
21011 compilation of the @cite{Main} procedure depends only on its own source,
21012 @code{main.adb}, and the spec of the package in file @code{r.ads}. This
21013 means that editing the body of @cite{R} does not require recompiling
21014 @cite{Main}.
21016 On the other hand, the call @cite{R.Q} is not inlined under these
21017 circumstances. If the @emph{-gnatn} switch is present when @cite{Main}
21018 is compiled, the call will be inlined if the body of @cite{Q} is small
21019 enough, but now @cite{Main} depends on the body of @cite{R} in
21020 @code{r.adb} as well as on the spec. This means that if this body is edited,
21021 the main program must be recompiled. Note that this extra dependency
21022 occurs whether or not the call is in fact inlined by @emph{gcc}.
21024 The use of front end inlining with @emph{-gnatN} generates similar
21025 additional dependencies.
21027 @geindex -fno-inline (gcc)
21029 Note: The @emph{-fno-inline} switch overrides all other conditions and ensures that
21030 no inlining occurs, unless requested with pragma Inline_Always for gcc
21031 back-ends. The extra dependences resulting from @emph{-gnatn} will still be active,
21032 even if this switch is used to suppress the resulting inlining actions.
21034 @geindex -fno-inline-functions (gcc)
21036 Note: The @emph{-fno-inline-functions} switch can be used to prevent
21037 automatic inlining of subprograms if @emph{-O3} is used.
21039 @geindex -fno-inline-small-functions (gcc)
21041 Note: The @emph{-fno-inline-small-functions} switch can be used to prevent
21042 automatic inlining of small subprograms if @emph{-O2} is used.
21044 @geindex -fno-inline-functions-called-once (gcc)
21046 Note: The @emph{-fno-inline-functions-called-once} switch
21047 can be used to prevent inlining of subprograms local to the unit
21048 and called once from within it if @emph{-O1} is used.
21050 Note regarding the use of @emph{-O3}: @emph{-gnatn} is made up of two
21051 sub-switches @emph{-gnatn1} and @emph{-gnatn2} that can be directly
21052 specified in lieu of it, @emph{-gnatn} being translated into one of them
21053 based on the optimization level. With @emph{-O2} or below, @emph{-gnatn}
21054 is equivalent to @emph{-gnatn1} which activates pragma @cite{Inline} with
21055 moderate inlining across modules. With @emph{-O3}, @emph{-gnatn} is
21056 equivalent to @emph{-gnatn2} which activates pragma @cite{Inline} with
21057 full inlining across modules. If you have used pragma @cite{Inline} in
21058 appropriate cases, then it is usually much better to use @emph{-O2}
21059 and @emph{-gnatn} and avoid the use of @emph{-O3} which has the additional
21060 effect of inlining subprograms you did not think should be inlined. We have
21061 found that the use of @emph{-O3} may slow down the compilation and increase
21062 the code size by performing excessive inlining, leading to increased
21063 instruction cache pressure from the increased code size and thus minor
21064 performance improvements. So the bottom line here is that you should not
21065 automatically assume that @emph{-O3} is better than @emph{-O2}, and
21066 indeed you should use @emph{-O3} only if tests show that it actually
21067 improves performance for your program.
21069 @node Floating_Point_Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
21070 @anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{1a6}@anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{1a7}
21071 @subsubsection Floating_Point_Operations
21074 @geindex Floating-Point Operations
21076 On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
21077 64-bit standard IEEE floating-point representations, and operations will
21078 use standard IEEE arithmetic as provided by the processor. On most, but
21079 not all, architectures, the attribute Machine_Overflows is False for these
21080 types, meaning that the semantics of overflow is implementation-defined.
21081 In the case of GNAT, these semantics correspond to the normal IEEE
21082 treatment of infinities and NaN (not a number) values. For example,
21083 1.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
21084 avoiding explicit overflow checks, the performance is greatly improved
21085 on many targets. However, if required, floating-point overflow can be
21086 enabled by the use of the pragma Check_Float_Overflow.
21088 Another consideration that applies specifically to x86 32-bit
21089 architectures is which form of floating-point arithmetic is used.
21090 By default the operations use the old style x86 floating-point,
21091 which implements an 80-bit extended precision form (on these
21092 architectures the type Long_Long_Float corresponds to that form).
21093 In addition, generation of efficient code in this mode means that
21094 the extended precision form will be used for intermediate results.
21095 This may be helpful in improving the final precision of a complex
21096 expression. However it means that the results obtained on the x86
21097 will be different from those on other architectures, and for some
21098 algorithms, the extra intermediate precision can be detrimental.
21100 In addition to this old-style floating-point, all modern x86 chips
21101 implement an alternative floating-point operation model referred
21102 to as SSE2. In this model there is no extended form, and furthermore
21103 execution performance is significantly enhanced. To force GNAT to use
21104 this more modern form, use both of the switches:
21106 @quotation
21108 -msse2 -mfpmath=sse
21109 @end quotation
21111 A unit compiled with these switches will automatically use the more
21112 efficient SSE2 instruction set for Float and Long_Float operations.
21113 Note that the ABI has the same form for both floating-point models,
21114 so it is permissible to mix units compiled with and without these
21115 switches.
21117 @node Vectorization of loops,Other Optimization Switches,Floating_Point_Operations,Performance Considerations
21118 @anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{1a8}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{1a9}
21119 @subsubsection Vectorization of loops
21122 @geindex Optimization Switches
21124 You can take advantage of the auto-vectorizer present in the @emph{gcc}
21125 back end to vectorize loops with GNAT.  The corresponding command line switch
21126 is @emph{-ftree-vectorize} but, as it is enabled by default at @emph{-O3}
21127 and other aggressive optimizations helpful for vectorization also are enabled
21128 by default at this level, using @emph{-O3} directly is recommended.
21130 You also need to make sure that the target architecture features a supported
21131 SIMD instruction set.  For example, for the x86 architecture, you should at
21132 least specify @emph{-msse2} to get significant vectorization (but you don't
21133 need to specify it for x86-64 as it is part of the base 64-bit architecture).
21134 Similarly, for the PowerPC architecture, you should specify @emph{-maltivec}.
21136 The preferred loop form for vectorization is the @cite{for} iteration scheme.
21137 Loops with a @cite{while} iteration scheme can also be vectorized if they are
21138 very simple, but the vectorizer will quickly give up otherwise.  With either
21139 iteration scheme, the flow of control must be straight, in particular no
21140 @cite{exit} statement may appear in the loop body.  The loop may however
21141 contain a single nested loop, if it can be vectorized when considered alone:
21143 @quotation
21145 @example
21146 A : array (1..4, 1..4) of Long_Float;
21147 S : array (1..4) of Long_Float;
21149 procedure Sum is
21150 begin
21151    for I in A'Range(1) loop
21152       for J in A'Range(2) loop
21153          S (I) := S (I) + A (I, J);
21154       end loop;
21155    end loop;
21156 end Sum;
21157 @end example
21158 @end quotation
21160 The vectorizable operations depend on the targeted SIMD instruction set, but
21161 the adding and some of the multiplying operators are generally supported, as
21162 well as the logical operators for modular types. Note that compiling
21163 with @emph{-gnatp} might well reveal cases where some checks do thwart
21164 vectorization.
21166 Type conversions may also prevent vectorization if they involve semantics that
21167 are not directly supported by the code generator or the SIMD instruction set.
21168 A typical example is direct conversion from floating-point to integer types.
21169 The solution in this case is to use the following idiom:
21171 @quotation
21173 @example
21174 Integer (S'Truncation (F))
21175 @end example
21176 @end quotation
21178 if @cite{S} is the subtype of floating-point object @cite{F}.
21180 In most cases, the vectorizable loops are loops that iterate over arrays.
21181 All kinds of array types are supported, i.e. constrained array types with
21182 static bounds:
21184 @quotation
21186 @example
21187 type Array_Type is array (1 .. 4) of Long_Float;
21188 @end example
21189 @end quotation
21191 constrained array types with dynamic bounds:
21193 @quotation
21195 @example
21196 type Array_Type is array (1 .. Q.N) of Long_Float;
21198 type Array_Type is array (Q.K .. 4) of Long_Float;
21200 type Array_Type is array (Q.K .. Q.N) of Long_Float;
21201 @end example
21202 @end quotation
21204 or unconstrained array types:
21206 @quotation
21208 @example
21209 type Array_Type is array (Positive range <>) of Long_Float;
21210 @end example
21211 @end quotation
21213 The quality of the generated code decreases when the dynamic aspect of the
21214 array type increases, the worst code being generated for unconstrained array
21215 types.  This is so because, the less information the compiler has about the
21216 bounds of the array, the more fallback code it needs to generate in order to
21217 fix things up at run time.
21219 It is possible to specify that a given loop should be subject to vectorization
21220 preferably to other optimizations by means of pragma @cite{Loop_Optimize}:
21222 @quotation
21224 @example
21225 pragma Loop_Optimize (Vector);
21226 @end example
21227 @end quotation
21229 placed immediately within the loop will convey the appropriate hint to the
21230 compiler for this loop.
21232 It is also possible to help the compiler generate better vectorized code
21233 for a given loop by asserting that there are no loop-carried dependencies
21234 in the loop.  Consider for example the procedure:
21236 @quotation
21238 @example
21239 type Arr is array (1 .. 4) of Long_Float;
21241 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
21242 begin
21243   for I in Arr'Range loop
21244     R(I) := X(I) + Y(I);
21245   end loop;
21246 end;
21247 @end example
21248 @end quotation
21250 By default, the compiler cannot unconditionally vectorize the loop because
21251 assigning to a component of the array designated by R in one iteration could
21252 change the value read from the components of the array designated by X or Y
21253 in a later iteration.  As a result, the compiler will generate two versions
21254 of the loop in the object code, one vectorized and the other not vectorized,
21255 as well as a test to select the appropriate version at run time.  This can
21256 be overcome by another hint:
21258 @quotation
21260 @example
21261 pragma Loop_Optimize (Ivdep);
21262 @end example
21263 @end quotation
21265 placed immediately within the loop will tell the compiler that it can safely
21266 omit the non-vectorized version of the loop as well as the run-time test.
21268 @node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
21269 @anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{1aa}@anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{1ab}
21270 @subsubsection Other Optimization Switches
21273 @geindex Optimization Switches
21275 Since @cite{GNAT} uses the @emph{gcc} back end, all the specialized
21276 @emph{gcc} optimization switches are potentially usable. These switches
21277 have not been extensively tested with GNAT but can generally be expected
21278 to work. Examples of switches in this category are @emph{-funroll-loops}
21279 and the various target-specific @emph{-m} options (in particular, it has
21280 been observed that @emph{-march=xxx} can significantly improve performance
21281 on appropriate machines). For full details of these switches, see
21282 the @cite{Submodel Options} section in the @cite{Hardware Models and Configurations}
21283 chapter of @cite{Using the GNU Compiler Collection (GCC)}.
21285 @node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
21286 @anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{f3}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{1ac}
21287 @subsubsection Optimization and Strict Aliasing
21290 @geindex Aliasing
21292 @geindex Strict Aliasing
21294 @geindex No_Strict_Aliasing
21296 The strong typing capabilities of Ada allow an optimizer to generate
21297 efficient code in situations where other languages would be forced to
21298 make worst case assumptions preventing such optimizations. Consider
21299 the following example:
21301 @quotation
21303 @example
21304 procedure R is
21305    type Int1 is new Integer;
21306    type Int2 is new Integer;
21307    type Int1A is access Int1;
21308    type Int2A is access Int2;
21309    Int1V : Int1A;
21310    Int2V : Int2A;
21311    ...
21313 begin
21314    ...
21315    for J in Data'Range loop
21316       if Data (J) = Int1V.all then
21317          Int2V.all := Int2V.all + 1;
21318       end if;
21319    end loop;
21320    ...
21321 end R;
21322 @end example
21323 @end quotation
21325 In this example, since the variable @cite{Int1V} can only access objects
21326 of type @cite{Int1}, and @cite{Int2V} can only access objects of type
21327 @cite{Int2}, there is no possibility that the assignment to
21328 @cite{Int2V.all} affects the value of @cite{Int1V.all}. This means that
21329 the compiler optimizer can "know" that the value @cite{Int1V.all} is constant
21330 for all iterations of the loop and avoid the extra memory reference
21331 required to dereference it each time through the loop.
21333 This kind of optimization, called strict aliasing analysis, is
21334 triggered by specifying an optimization level of @emph{-O2} or
21335 higher or @emph{-Os} and allows @cite{GNAT} to generate more efficient code
21336 when access values are involved.
21338 However, although this optimization is always correct in terms of
21339 the formal semantics of the Ada Reference Manual, difficulties can
21340 arise if features like @cite{Unchecked_Conversion} are used to break
21341 the typing system. Consider the following complete program example:
21343 @quotation
21345 @example
21346 package p1 is
21347    type int1 is new integer;
21348    type int2 is new integer;
21349    type a1 is access int1;
21350    type a2 is access int2;
21351 end p1;
21353 with p1; use p1;
21354 package p2 is
21355    function to_a2 (Input : a1) return a2;
21356 end p2;
21358 with Unchecked_Conversion;
21359 package body p2 is
21360    function to_a2 (Input : a1) return a2 is
21361       function to_a2u is
21362         new Unchecked_Conversion (a1, a2);
21363    begin
21364       return to_a2u (Input);
21365    end to_a2;
21366 end p2;
21368 with p2; use p2;
21369 with p1; use p1;
21370 with Text_IO; use Text_IO;
21371 procedure m is
21372    v1 : a1 := new int1;
21373    v2 : a2 := to_a2 (v1);
21374 begin
21375    v1.all := 1;
21376    v2.all := 0;
21377    put_line (int1'image (v1.all));
21378 end;
21379 @end example
21380 @end quotation
21382 This program prints out 0 in @emph{-O0} or @emph{-O1}
21383 mode, but it prints out 1 in @emph{-O2} mode. That's
21384 because in strict aliasing mode, the compiler can and
21385 does assume that the assignment to @cite{v2.all} could not
21386 affect the value of @cite{v1.all}, since different types
21387 are involved.
21389 This behavior is not a case of non-conformance with the standard, since
21390 the Ada RM specifies that an unchecked conversion where the resulting
21391 bit pattern is not a correct value of the target type can result in an
21392 abnormal value and attempting to reference an abnormal value makes the
21393 execution of a program erroneous.  That's the case here since the result
21394 does not point to an object of type @cite{int2}.  This means that the
21395 effect is entirely unpredictable.
21397 However, although that explanation may satisfy a language
21398 lawyer, in practice an applications programmer expects an
21399 unchecked conversion involving pointers to create true
21400 aliases and the behavior of printing 1 seems plain wrong.
21401 In this case, the strict aliasing optimization is unwelcome.
21403 Indeed the compiler recognizes this possibility, and the
21404 unchecked conversion generates a warning:
21406 @quotation
21408 @example
21409 p2.adb:5:07: warning: possible aliasing problem with type "a2"
21410 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
21411 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
21412 @end example
21413 @end quotation
21415 Unfortunately the problem is recognized when compiling the body of
21416 package @cite{p2}, but the actual "bad" code is generated while
21417 compiling the body of @cite{m} and this latter compilation does not see
21418 the suspicious @cite{Unchecked_Conversion}.
21420 As implied by the warning message, there are approaches you can use to
21421 avoid the unwanted strict aliasing optimization in a case like this.
21423 One possibility is to simply avoid the use of @emph{-O2}, but
21424 that is a bit drastic, since it throws away a number of useful
21425 optimizations that do not involve strict aliasing assumptions.
21427 A less drastic approach is to compile the program using the
21428 option @emph{-fno-strict-aliasing}. Actually it is only the
21429 unit containing the dereferencing of the suspicious pointer
21430 that needs to be compiled. So in this case, if we compile
21431 unit @cite{m} with this switch, then we get the expected
21432 value of zero printed. Analyzing which units might need
21433 the switch can be painful, so a more reasonable approach
21434 is to compile the entire program with options @emph{-O2}
21435 and @emph{-fno-strict-aliasing}. If the performance is
21436 satisfactory with this combination of options, then the
21437 advantage is that the entire issue of possible "wrong"
21438 optimization due to strict aliasing is avoided.
21440 To avoid the use of compiler switches, the configuration
21441 pragma @cite{No_Strict_Aliasing} with no parameters may be
21442 used to specify that for all access types, the strict
21443 aliasing optimization should be suppressed.
21445 However, these approaches are still overkill, in that they causes
21446 all manipulations of all access values to be deoptimized. A more
21447 refined approach is to concentrate attention on the specific
21448 access type identified as problematic.
21450 First, if a careful analysis of uses of the pointer shows
21451 that there are no possible problematic references, then
21452 the warning can be suppressed by bracketing the
21453 instantiation of @cite{Unchecked_Conversion} to turn
21454 the warning off:
21456 @quotation
21458 @example
21459 pragma Warnings (Off);
21460 function to_a2u is
21461   new Unchecked_Conversion (a1, a2);
21462 pragma Warnings (On);
21463 @end example
21464 @end quotation
21466 Of course that approach is not appropriate for this particular
21467 example, since indeed there is a problematic reference. In this
21468 case we can take one of two other approaches.
21470 The first possibility is to move the instantiation of unchecked
21471 conversion to the unit in which the type is declared. In
21472 this example, we would move the instantiation of
21473 @cite{Unchecked_Conversion} from the body of package
21474 @cite{p2} to the spec of package @cite{p1}. Now the
21475 warning disappears. That's because any use of the
21476 access type knows there is a suspicious unchecked
21477 conversion, and the strict aliasing optimization
21478 is automatically suppressed for the type.
21480 If it is not practical to move the unchecked conversion to the same unit
21481 in which the destination access type is declared (perhaps because the
21482 source type is not visible in that unit), you may use pragma
21483 @cite{No_Strict_Aliasing} for the type. This pragma must occur in the
21484 same declarative sequence as the declaration of the access type:
21486 @quotation
21488 @example
21489 type a2 is access int2;
21490 pragma No_Strict_Aliasing (a2);
21491 @end example
21492 @end quotation
21494 Here again, the compiler now knows that the strict aliasing optimization
21495 should be suppressed for any reference to type @cite{a2} and the
21496 expected behavior is obtained.
21498 Finally, note that although the compiler can generate warnings for
21499 simple cases of unchecked conversions, there are tricker and more
21500 indirect ways of creating type incorrect aliases which the compiler
21501 cannot detect. Examples are the use of address overlays and unchecked
21502 conversions involving composite types containing access types as
21503 components. In such cases, no warnings are generated, but there can
21504 still be aliasing problems. One safe coding practice is to forbid the
21505 use of address clauses for type overlaying, and to allow unchecked
21506 conversion only for primitive types. This is not really a significant
21507 restriction since any possible desired effect can be achieved by
21508 unchecked conversion of access values.
21510 The aliasing analysis done in strict aliasing mode can certainly
21511 have significant benefits. We have seen cases of large scale
21512 application code where the time is increased by up to 5% by turning
21513 this optimization off. If you have code that includes significant
21514 usage of unchecked conversion, you might want to just stick with
21515 @emph{-O1} and avoid the entire issue. If you get adequate
21516 performance at this level of optimization level, that's probably
21517 the safest approach. If tests show that you really need higher
21518 levels of optimization, then you can experiment with @emph{-O2}
21519 and @emph{-O2 -fno-strict-aliasing} to see how much effect this
21520 has on size and speed of the code. If you really need to use
21521 @emph{-O2} with strict aliasing in effect, then you should
21522 review any uses of unchecked conversion of access types,
21523 particularly if you are getting the warnings described above.
21525 @node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
21526 @anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{1ad}@anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{1ae}
21527 @subsubsection Aliased Variables and Optimization
21530 @geindex Aliasing
21532 There are scenarios in which programs may
21533 use low level techniques to modify variables
21534 that otherwise might be considered to be unassigned. For example,
21535 a variable can be passed to a procedure by reference, which takes
21536 the address of the parameter and uses the address to modify the
21537 variable's value, even though it is passed as an IN parameter.
21538 Consider the following example:
21540 @quotation
21542 @example
21543 procedure P is
21544    Max_Length : constant Natural := 16;
21545    type Char_Ptr is access all Character;
21547    procedure Get_String(Buffer: Char_Ptr; Size : Integer);
21548    pragma Import (C, Get_String, "get_string");
21550    Name : aliased String (1 .. Max_Length) := (others => ' ');
21551    Temp : Char_Ptr;
21553    function Addr (S : String) return Char_Ptr is
21554       function To_Char_Ptr is
21555         new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
21556    begin
21557       return To_Char_Ptr (S (S'First)'Address);
21558    end;
21560 begin
21561    Temp := Addr (Name);
21562    Get_String (Temp, Max_Length);
21563 end;
21564 @end example
21565 @end quotation
21567 where Get_String is a C function that uses the address in Temp to
21568 modify the variable @cite{Name}. This code is dubious, and arguably
21569 erroneous, and the compiler would be entitled to assume that
21570 @cite{Name} is never modified, and generate code accordingly.
21572 However, in practice, this would cause some existing code that
21573 seems to work with no optimization to start failing at high
21574 levels of optimzization.
21576 What the compiler does for such cases is to assume that marking
21577 a variable as aliased indicates that some "funny business" may
21578 be going on. The optimizer recognizes the aliased keyword and
21579 inhibits optimizations that assume the value cannot be assigned.
21580 This means that the above example will in fact "work" reliably,
21581 that is, it will produce the expected results.
21583 @node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
21584 @anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{1af}@anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{1b0}
21585 @subsubsection Atomic Variables and Optimization
21588 @geindex Atomic
21590 There are two considerations with regard to performance when
21591 atomic variables are used.
21593 First, the RM only guarantees that access to atomic variables
21594 be atomic, it has nothing to say about how this is achieved,
21595 though there is a strong implication that this should not be
21596 achieved by explicit locking code. Indeed GNAT will never
21597 generate any locking code for atomic variable access (it will
21598 simply reject any attempt to make a variable or type atomic
21599 if the atomic access cannot be achieved without such locking code).
21601 That being said, it is important to understand that you cannot
21602 assume that the entire variable will always be accessed. Consider
21603 this example:
21605 @quotation
21607 @example
21608 type R is record
21609    A,B,C,D : Character;
21610 end record;
21611 for R'Size use 32;
21612 for R'Alignment use 4;
21614 RV : R;
21615 pragma Atomic (RV);
21616 X : Character;
21618 X := RV.B;
21619 @end example
21620 @end quotation
21622 You cannot assume that the reference to @cite{RV.B}
21623 will read the entire 32-bit
21624 variable with a single load instruction. It is perfectly legitimate if
21625 the hardware allows it to do a byte read of just the B field. This read
21626 is still atomic, which is all the RM requires. GNAT can and does take
21627 advantage of this, depending on the architecture and optimization level.
21628 Any assumption to the contrary is non-portable and risky. Even if you
21629 examine the assembly language and see a full 32-bit load, this might
21630 change in a future version of the compiler.
21632 If your application requires that all accesses to @cite{RV} in this
21633 example be full 32-bit loads, you need to make a copy for the access
21634 as in:
21636 @quotation
21638 @example
21639 declare
21640    RV_Copy : constant R := RV;
21641 begin
21642    X := RV_Copy.B;
21643 end;
21644 @end example
21645 @end quotation
21647 Now the reference to RV must read the whole variable.
21648 Actually one can imagine some compiler which figures
21649 out that the whole copy is not required (because only
21650 the B field is actually accessed), but GNAT
21651 certainly won't do that, and we don't know of any
21652 compiler that would not handle this right, and the
21653 above code will in practice work portably across
21654 all architectures (that permit the Atomic declaration).
21656 The second issue with atomic variables has to do with
21657 the possible requirement of generating synchronization
21658 code. For more details on this, consult the sections on
21659 the pragmas Enable/Disable_Atomic_Synchronization in the
21660 GNAT Reference Manual. If performance is critical, and
21661 such synchronization code is not required, it may be
21662 useful to disable it.
21664 @node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
21665 @anchor{gnat_ugn/gnat_and_program_execution id41}@anchor{1b1}@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{1b2}
21666 @subsubsection Passive Task Optimization
21669 @geindex Passive Task
21671 A passive task is one which is sufficiently simple that
21672 in theory a compiler could recognize it an implement it
21673 efficiently without creating a new thread. The original design
21674 of Ada 83 had in mind this kind of passive task optimization, but
21675 only a few Ada 83 compilers attempted it. The problem was that
21676 it was difficult to determine the exact conditions under which
21677 the optimization was possible. The result is a very fragile
21678 optimization where a very minor change in the program can
21679 suddenly silently make a task non-optimizable.
21681 With the revisiting of this issue in Ada 95, there was general
21682 agreement that this approach was fundamentally flawed, and the
21683 notion of protected types was introduced. When using protected
21684 types, the restrictions are well defined, and you KNOW that the
21685 operations will be optimized, and furthermore this optimized
21686 performance is fully portable.
21688 Although it would theoretically be possible for GNAT to attempt to
21689 do this optimization, but it really doesn't make sense in the
21690 context of Ada 95, and none of the Ada 95 compilers implement
21691 this optimization as far as we know. In particular GNAT never
21692 attempts to perform this optimization.
21694 In any new Ada 95 code that is written, you should always
21695 use protected types in place of tasks that might be able to
21696 be optimized in this manner.
21697 Of course this does not help if you have legacy Ada 83 code
21698 that depends on this optimization, but it is unusual to encounter
21699 a case where the performance gains from this optimization
21700 are significant.
21702 Your program should work correctly without this optimization. If
21703 you have performance problems, then the most practical
21704 approach is to figure out exactly where these performance problems
21705 arise, and update those particular tasks to be protected types. Note
21706 that typically clients of the tasks who call entries, will not have
21707 to be modified, only the task definition itself.
21709 @node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
21710 @anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{1b3}@anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{1b4}
21711 @subsection @cite{Text_IO} Suggestions
21714 @geindex Text_IO and performance
21716 The @cite{Ada.Text_IO} package has fairly high overheads due in part to
21717 the requirement of maintaining page and line counts. If performance
21718 is critical, a recommendation is to use @cite{Stream_IO} instead of
21719 @cite{Text_IO} for volume output, since this package has less overhead.
21721 If @cite{Text_IO} must be used, note that by default output to the standard
21722 output and standard error files is unbuffered (this provides better
21723 behavior when output statements are used for debugging, or if the
21724 progress of a program is observed by tracking the output, e.g. by
21725 using the Unix @emph{tail -f} command to watch redirected output.
21727 If you are generating large volumes of output with @cite{Text_IO} and
21728 performance is an important factor, use a designated file instead
21729 of the standard output file, or change the standard output file to
21730 be buffered using @cite{Interfaces.C_Streams.setvbuf}.
21732 @node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
21733 @anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{1b5}@anchor{gnat_ugn/gnat_and_program_execution reducing-size-of-executables-with-unused-subprogram-data-elimination}@anchor{1b6}
21734 @subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
21737 @geindex Uunused subprogram/data elimination
21739 This section describes how you can eliminate unused subprograms and data from
21740 your executable just by setting options at compilation time.
21742 @menu
21743 * About unused subprogram/data elimination:: 
21744 * Compilation options:: 
21745 * Example of unused subprogram/data elimination:: 
21747 @end menu
21749 @node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
21750 @anchor{gnat_ugn/gnat_and_program_execution id44}@anchor{1b7}@anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{1b8}
21751 @subsubsection About unused subprogram/data elimination
21754 By default, an executable contains all code and data of its composing objects
21755 (directly linked or coming from statically linked libraries), even data or code
21756 never used by this executable.
21758 This feature will allow you to eliminate such unused code from your
21759 executable, making it smaller (in disk and in memory).
21761 This functionality is available on all Linux platforms except for the IA-64
21762 architecture and on all cross platforms using the ELF binary file format.
21763 In both cases GNU binutils version 2.16 or later are required to enable it.
21765 @node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
21766 @anchor{gnat_ugn/gnat_and_program_execution id45}@anchor{1b9}@anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{1ba}
21767 @subsubsection Compilation options
21770 The operation of eliminating the unused code and data from the final executable
21771 is directly performed by the linker.
21773 @geindex -ffunction-sections (gcc)
21775 @geindex -fdata-sections (gcc)
21777 In order to do this, it has to work with objects compiled with the
21778 following options:
21779 @emph{-ffunction-sections} @emph{-fdata-sections}.
21781 These options are usable with C and Ada files.
21782 They will place respectively each
21783 function or data in a separate section in the resulting object file.
21785 Once the objects and static libraries are created with these options, the
21786 linker can perform the dead code elimination. You can do this by setting
21787 the @emph{-Wl,--gc-sections} option to gcc command or in the
21788 @emph{-largs} section of @emph{gnatmake}. This will perform a
21789 garbage collection of code and data never referenced.
21791 If the linker performs a partial link (@emph{-r} linker option), then you
21792 will need to provide the entry point using the @emph{-e} / @emph{--entry}
21793 linker option.
21795 Note that objects compiled without the @emph{-ffunction-sections} and
21796 @emph{-fdata-sections} options can still be linked with the executable.
21797 However, no dead code elimination will be performed on those objects (they will
21798 be linked as is).
21800 The GNAT static library is now compiled with -ffunction-sections and
21801 -fdata-sections on some platforms. This allows you to eliminate the unused code
21802 and data of the GNAT library from your executable.
21804 @node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
21805 @anchor{gnat_ugn/gnat_and_program_execution id46}@anchor{1bb}@anchor{gnat_ugn/gnat_and_program_execution example-of-unused-subprogram-data-elimination}@anchor{1bc}
21806 @subsubsection Example of unused subprogram/data elimination
21809 Here is a simple example:
21811 @quotation
21813 @example
21814 with Aux;
21816 procedure Test is
21817 begin
21818    Aux.Used (10);
21819 end Test;
21821 package Aux is
21822    Used_Data   : Integer;
21823    Unused_Data : Integer;
21825    procedure Used   (Data : Integer);
21826    procedure Unused (Data : Integer);
21827 end Aux;
21829 package body Aux is
21830    procedure Used (Data : Integer) is
21831    begin
21832       Used_Data := Data;
21833    end Used;
21835    procedure Unused (Data : Integer) is
21836    begin
21837       Unused_Data := Data;
21838    end Unused;
21839 end Aux;
21840 @end example
21841 @end quotation
21843 @cite{Unused} and @cite{Unused_Data} are never referenced in this code
21844 excerpt, and hence they may be safely removed from the final executable.
21846 @quotation
21848 @example
21849 $ gnatmake test
21851 $ nm test | grep used
21852 020015f0 T aux__unused
21853 02005d88 B aux__unused_data
21854 020015cc T aux__used
21855 02005d84 B aux__used_data
21857 $ gnatmake test -cargs -fdata-sections -ffunction-sections \\
21858      -largs -Wl,--gc-sections
21860 $ nm test | grep used
21861 02005350 T aux__used
21862 0201ffe0 B aux__used_data
21863 @end example
21864 @end quotation
21866 It can be observed that the procedure @cite{Unused} and the object
21867 @cite{Unused_Data} are removed by the linker when using the
21868 appropriate options.
21870 @geindex Overflow checks
21872 @geindex Checks (overflow)
21875 @node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
21876 @anchor{gnat_ugn/gnat_and_program_execution id54}@anchor{168}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{27}
21877 @section Overflow Check Handling in GNAT
21880 This section explains how to control the handling of overflow checks.
21882 @menu
21883 * Background:: 
21884 * Management of Overflows in GNAT:: 
21885 * Specifying the Desired Mode:: 
21886 * Default Settings:: 
21887 * Implementation Notes:: 
21889 @end menu
21891 @node Background,Management of Overflows in GNAT,,Overflow Check Handling in GNAT
21892 @anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{1bd}@anchor{gnat_ugn/gnat_and_program_execution background}@anchor{1be}
21893 @subsection Background
21896 Overflow checks are checks that the compiler may make to ensure
21897 that intermediate results are not out of range. For example:
21899 @quotation
21901 @example
21902 A : Integer;
21904 A := A + 1;
21905 @end example
21906 @end quotation
21908 If @cite{A} has the value @cite{Integer'Last}, then the addition may cause
21909 overflow since the result is out of range of the type @cite{Integer}.
21910 In this case @cite{Constraint_Error} will be raised if checks are
21911 enabled.
21913 A trickier situation arises in examples like the following:
21915 @quotation
21917 @example
21918 A, C : Integer;
21920 A := (A + 1) + C;
21921 @end example
21922 @end quotation
21924 where @cite{A} is @cite{Integer'Last} and @cite{C} is @cite{-1}.
21925 Now the final result of the expression on the right hand side is
21926 @cite{Integer'Last} which is in range, but the question arises whether the
21927 intermediate addition of @cite{(A + 1)} raises an overflow error.
21929 The (perhaps surprising) answer is that the Ada language
21930 definition does not answer this question. Instead it leaves
21931 it up to the implementation to do one of two things if overflow
21932 checks are enabled.
21935 @itemize *
21937 @item 
21938 raise an exception (@cite{Constraint_Error}), or
21940 @item 
21941 yield the correct mathematical result which is then used in
21942 subsequent operations.
21943 @end itemize
21945 If the compiler chooses the first approach, then the assignment of this
21946 example will indeed raise @cite{Constraint_Error} if overflow checking is
21947 enabled, or result in erroneous execution if overflow checks are suppressed.
21949 But if the compiler
21950 chooses the second approach, then it can perform both additions yielding
21951 the correct mathematical result, which is in range, so no exception
21952 will be raised, and the right result is obtained, regardless of whether
21953 overflow checks are suppressed.
21955 Note that in the first example an
21956 exception will be raised in either case, since if the compiler
21957 gives the correct mathematical result for the addition, it will
21958 be out of range of the target type of the assignment, and thus
21959 fails the range check.
21961 This lack of specified behavior in the handling of overflow for
21962 intermediate results is a source of non-portability, and can thus
21963 be problematic when programs are ported. Most typically this arises
21964 in a situation where the original compiler did not raise an exception,
21965 and then the application is moved to a compiler where the check is
21966 performed on the intermediate result and an unexpected exception is
21967 raised.
21969 Furthermore, when using Ada 2012's preconditions and other
21970 assertion forms, another issue arises. Consider:
21972 @quotation
21974 @example
21975 procedure P (A, B : Integer) with
21976   Pre => A + B <= Integer'Last;
21977 @end example
21978 @end quotation
21980 One often wants to regard arithmetic in a context like this from
21981 a mathematical point of view. So for example, if the two actual parameters
21982 for a call to @cite{P} are both @cite{Integer'Last}, then
21983 the precondition should be regarded as False. If we are executing
21984 in a mode with run-time checks enabled for preconditions, then we would
21985 like this precondition to fail, rather than raising an exception
21986 because of the intermediate overflow.
21988 However, the language definition leaves the specification of
21989 whether the above condition fails (raising @cite{Assert_Error}) or
21990 causes an intermediate overflow (raising @cite{Constraint_Error})
21991 up to the implementation.
21993 The situation is worse in a case such as the following:
21995 @quotation
21997 @example
21998 procedure Q (A, B, C : Integer) with
21999   Pre => A + B + C <= Integer'Last;
22000 @end example
22001 @end quotation
22003 Consider the call
22005 @quotation
22007 @example
22008 Q (A => Integer'Last, B => 1, C => -1);
22009 @end example
22010 @end quotation
22012 From a mathematical point of view the precondition
22013 is True, but at run time we may (but are not guaranteed to) get an
22014 exception raised because of the intermediate overflow (and we really
22015 would prefer this precondition to be considered True at run time).
22017 @node Management of Overflows in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
22018 @anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{1bf}@anchor{gnat_ugn/gnat_and_program_execution management-of-overflows-in-gnat}@anchor{1c0}
22019 @subsection Management of Overflows in GNAT
22022 To deal with the portability issue, and with the problem of
22023 mathematical versus run-time interpretation of the expressions in
22024 assertions, GNAT provides comprehensive control over the handling
22025 of intermediate overflow. GNAT can operate in three modes, and
22026 furthemore, permits separate selection of operating modes for
22027 the expressions within assertions (here the term 'assertions'
22028 is used in the technical sense, which includes preconditions and so forth)
22029 and for expressions appearing outside assertions.
22031 The three modes are:
22034 @itemize *
22036 @item 
22037 @emph{Use base type for intermediate operations} (@cite{STRICT})
22039 In this mode, all intermediate results for predefined arithmetic
22040 operators are computed using the base type, and the result must
22041 be in range of the base type. If this is not the
22042 case then either an exception is raised (if overflow checks are
22043 enabled) or the execution is erroneous (if overflow checks are suppressed).
22044 This is the normal default mode.
22046 @item 
22047 @emph{Most intermediate overflows avoided} (@cite{MINIMIZED})
22049 In this mode, the compiler attempts to avoid intermediate overflows by
22050 using a larger integer type, typically @cite{Long_Long_Integer},
22051 as the type in which arithmetic is
22052 performed for predefined arithmetic operators. This may be slightly more
22053 expensive at
22054 run time (compared to suppressing intermediate overflow checks), though
22055 the cost is negligible on modern 64-bit machines. For the examples given
22056 earlier, no intermediate overflows would have resulted in exceptions,
22057 since the intermediate results are all in the range of
22058 @cite{Long_Long_Integer} (typically 64-bits on nearly all implementations
22059 of GNAT). In addition, if checks are enabled, this reduces the number of
22060 checks that must be made, so this choice may actually result in an
22061 improvement in space and time behavior.
22063 However, there are cases where @cite{Long_Long_Integer} is not large
22064 enough, consider the following example:
22066 @quotation
22068 @example
22069 procedure R (A, B, C, D : Integer) with
22070   Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
22071 @end example
22072 @end quotation
22074 where @cite{A} = @cite{B} = @cite{C} = @cite{D} = @cite{Integer'Last}.
22075 Now the intermediate results are
22076 out of the range of @cite{Long_Long_Integer} even though the final result
22077 is in range and the precondition is True (from a mathematical point
22078 of view). In such a case, operating in this mode, an overflow occurs
22079 for the intermediate computation (which is why this mode
22080 says @emph{most} intermediate overflows are avoided). In this case,
22081 an exception is raised if overflow checks are enabled, and the
22082 execution is erroneous if overflow checks are suppressed.
22084 @item 
22085 @emph{All intermediate overflows avoided} (@cite{ELIMINATED})
22087 In this mode, the compiler  avoids all intermediate overflows
22088 by using arbitrary precision arithmetic as required. In this
22089 mode, the above example with @cite{A**2 * B**2} would
22090 not cause intermediate overflow, because the intermediate result
22091 would be evaluated using sufficient precision, and the result
22092 of evaluating the precondition would be True.
22094 This mode has the advantage of avoiding any intermediate
22095 overflows, but at the expense of significant run-time overhead,
22096 including the use of a library (included automatically in this
22097 mode) for multiple-precision arithmetic.
22099 This mode provides cleaner semantics for assertions, since now
22100 the run-time behavior emulates true arithmetic behavior for the
22101 predefined arithmetic operators, meaning that there is never a
22102 conflict between the mathematical view of the assertion, and its
22103 run-time behavior.
22105 Note that in this mode, the behavior is unaffected by whether or
22106 not overflow checks are suppressed, since overflow does not occur.
22107 It is possible for gigantic intermediate expressions to raise
22108 @cite{Storage_Error} as a result of attempting to compute the
22109 results of such expressions (e.g. @cite{Integer'Last ** Integer'Last})
22110 but overflow is impossible.
22111 @end itemize
22113 Note that these modes apply only to the evaluation of predefined
22114 arithmetic, membership, and comparison operators for signed integer
22115 aritmetic.
22117 For fixed-point arithmetic, checks can be suppressed. But if checks
22118 are enabled
22119 then fixed-point values are always checked for overflow against the
22120 base type for intermediate expressions (that is such checks always
22121 operate in the equivalent of @cite{STRICT} mode).
22123 For floating-point, on nearly all architectures, @cite{Machine_Overflows}
22124 is False, and IEEE infinities are generated, so overflow exceptions
22125 are never raised. If you want to avoid infinities, and check that
22126 final results of expressions are in range, then you can declare a
22127 constrained floating-point type, and range checks will be carried
22128 out in the normal manner (with infinite values always failing all
22129 range checks).
22131 @node Specifying the Desired Mode,Default Settings,Management of Overflows in GNAT,Overflow Check Handling in GNAT
22132 @anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{f8}@anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{1c1}
22133 @subsection Specifying the Desired Mode
22136 @geindex pragma Overflow_Mode
22138 The desired mode of for handling intermediate overflow can be specified using
22139 either the @cite{Overflow_Mode} pragma or an equivalent compiler switch.
22140 The pragma has the form
22142 @quotation
22144 @example
22145 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
22146 @end example
22147 @end quotation
22149 where @cite{MODE} is one of
22152 @itemize *
22154 @item 
22155 @cite{STRICT}:  intermediate overflows checked (using base type)
22157 @item 
22158 @cite{MINIMIZED}: minimize intermediate overflows
22160 @item 
22161 @cite{ELIMINATED}: eliminate intermediate overflows
22162 @end itemize
22164 The case is ignored, so @cite{MINIMIZED}, @cite{Minimized} and
22165 @cite{minimized} all have the same effect.
22167 If only the @cite{General} parameter is present, then the given @cite{MODE}
22168 applies
22169 to expressions both within and outside assertions. If both arguments
22170 are present, then @cite{General} applies to expressions outside assertions,
22171 and @cite{Assertions} applies to expressions within assertions. For example:
22173 @quotation
22175 @example
22176 pragma Overflow_Mode
22177   (General => Minimized, Assertions => Eliminated);
22178 @end example
22179 @end quotation
22181 specifies that general expressions outside assertions be evaluated
22182 in 'minimize intermediate overflows' mode, and expressions within
22183 assertions be evaluated in 'eliminate intermediate overflows' mode.
22184 This is often a reasonable choice, avoiding excessive overhead
22185 outside assertions, but assuring a high degree of portability
22186 when importing code from another compiler, while incurring
22187 the extra overhead for assertion expressions to ensure that
22188 the behavior at run time matches the expected mathematical
22189 behavior.
22191 The @cite{Overflow_Mode} pragma has the same scoping and placement
22192 rules as pragma @cite{Suppress}, so it can occur either as a
22193 configuration pragma, specifying a default for the whole
22194 program, or in a declarative scope, where it applies to the
22195 remaining declarations and statements in that scope.
22197 Note that pragma @cite{Overflow_Mode} does not affect whether
22198 overflow checks are enabled or suppressed. It only controls the
22199 method used to compute intermediate values. To control whether
22200 overflow checking is enabled or suppressed, use pragma @cite{Suppress}
22201 or @cite{Unsuppress} in the usual manner
22203 @geindex -gnato? (gcc)
22205 @geindex -gnato?? (gcc)
22207 Additionally, a compiler switch @emph{-gnato?} or @emph{-gnato??}
22208 can be used to control the checking mode default (which can be subsequently
22209 overridden using pragmas).
22211 Here @code{?} is one of the digits @code{1} through @code{3}:
22213 @quotation
22216 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
22217 @item
22219 @code{1}
22221 @tab
22223 use base type for intermediate operations (@cite{STRICT})
22225 @item
22227 @code{2}
22229 @tab
22231 minimize intermediate overflows (@cite{MINIMIZED})
22233 @item
22235 @code{3}
22237 @tab
22239 eliminate intermediate overflows (@cite{ELIMINATED})
22241 @end multitable
22243 @end quotation
22245 As with the pragma, if only one digit appears then it applies to all
22246 cases; if two digits are given, then the first applies outside
22247 assertions, and the second within assertions. Thus the equivalent
22248 of the example pragma above would be
22249 @emph{-gnato23}.
22251 If no digits follow the @emph{-gnato}, then it is equivalent to
22252 @emph{-gnato11},
22253 causing all intermediate operations to be computed using the base
22254 type (@cite{STRICT} mode).
22256 @node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
22257 @anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{1c2}@anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{1c3}
22258 @subsection Default Settings
22261 The default mode for overflow checks is
22263 @quotation
22265 @example
22266 General => Strict
22267 @end example
22268 @end quotation
22270 which causes all computations both inside and outside assertions to use
22271 the base type.
22273 This retains compatibility with previous versions of
22274 GNAT which suppressed overflow checks by default and always
22275 used the base type for computation of intermediate results.
22277 @c Sphinx allows no emphasis within :index: role. As a workaround we
22278 @c point the index to "switch" and use emphasis for "-gnato".
22280 The 
22281 @geindex -gnato (gcc)
22282 switch @emph{-gnato} (with no digits following)
22283 is equivalent to
22285 @quotation
22287 @example
22288 General => Strict
22289 @end example
22290 @end quotation
22292 which causes overflow checking of all intermediate overflows
22293 both inside and outside assertions against the base type.
22295 The pragma @cite{Suppress (Overflow_Check)} disables overflow
22296 checking, but it has no effect on the method used for computing
22297 intermediate results.
22299 The pragma @cite{Unsuppress (Overflow_Check)} enables overflow
22300 checking, but it has no effect on the method used for computing
22301 intermediate results.
22303 @node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
22304 @anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{1c4}@anchor{gnat_ugn/gnat_and_program_execution id59}@anchor{1c5}
22305 @subsection Implementation Notes
22308 In practice on typical 64-bit machines, the @cite{MINIMIZED} mode is
22309 reasonably efficient, and can be generally used. It also helps
22310 to ensure compatibility with code imported from some other
22311 compiler to GNAT.
22313 Setting all intermediate overflows checking (@cite{CHECKED} mode)
22314 makes sense if you want to
22315 make sure that your code is compatible with any other possible
22316 Ada implementation. This may be useful in ensuring portability
22317 for code that is to be exported to some other compiler than GNAT.
22319 The Ada standard allows the reassociation of expressions at
22320 the same precedence level if no parentheses are present. For
22321 example, @cite{A+B+C} parses as though it were @cite{(A+B)+C}, but
22322 the compiler can reintepret this as @cite{A+(B+C)}, possibly
22323 introducing or eliminating an overflow exception. The GNAT
22324 compiler never takes advantage of this freedom, and the
22325 expression @cite{A+B+C} will be evaluated as @cite{(A+B)+C}.
22326 If you need the other order, you can write the parentheses
22327 explicitly @cite{A+(B+C)} and GNAT will respect this order.
22329 The use of @cite{ELIMINATED} mode will cause the compiler to
22330 automatically include an appropriate arbitrary precision
22331 integer arithmetic package. The compiler will make calls
22332 to this package, though only in cases where it cannot be
22333 sure that @cite{Long_Long_Integer} is sufficient to guard against
22334 intermediate overflows. This package does not use dynamic
22335 alllocation, but it does use the secondary stack, so an
22336 appropriate secondary stack package must be present (this
22337 is always true for standard full Ada, but may require
22338 specific steps for restricted run times such as ZFP).
22340 Although @cite{ELIMINATED} mode causes expressions to use arbitrary
22341 precision arithmetic, avoiding overflow, the final result
22342 must be in an appropriate range. This is true even if the
22343 final result is of type @cite{[Long_[Long_]]Integer'Base}, which
22344 still has the same bounds as its associated constrained
22345 type at run-time.
22347 Currently, the @cite{ELIMINATED} mode is only available on target
22348 platforms for which @cite{Long_Long_Integer} is 64-bits (nearly all GNAT
22349 platforms).
22351 @node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
22352 @anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{28}@anchor{gnat_ugn/gnat_and_program_execution id60}@anchor{169}
22353 @section Performing Dimensionality Analysis in GNAT
22356 @geindex Dimensionality analysis
22358 The GNAT compiler supports dimensionality checking. The user can
22359 specify physical units for objects, and the compiler will verify that uses
22360 of these objects are compatible with their dimensions, in a fashion that is
22361 familiar to engineering practice. The dimensions of algebraic expressions
22362 (including powers with static exponents) are computed from their constituents.
22364 @geindex Dimension_System aspect
22366 @geindex Dimension aspect
22368 This feature depends on Ada 2012 aspect specifications, and is available from
22369 version 7.0.1 of GNAT onwards.
22370 The GNAT-specific aspect @cite{Dimension_System}
22371 allows you to define a system of units; the aspect @cite{Dimension}
22372 then allows the user to declare dimensioned quantities within a given system.
22373 (These aspects are described in the @emph{Implementation Defined Aspects}
22374 chapter of the @emph{GNAT Reference Manual}).
22376 The major advantage of this model is that it does not require the declaration of
22377 multiple operators for all possible combinations of types: it is only necessary
22378 to use the proper subtypes in object declarations.
22380 @geindex System.Dim.Mks package (GNAT library)
22382 @geindex MKS_Type type
22384 The simplest way to impose dimensionality checking on a computation is to make
22385 use of the package @cite{System.Dim.Mks},
22386 which is part of the GNAT library. This
22387 package defines a floating-point type @cite{MKS_Type},
22388 for which a sequence of
22389 dimension names are specified, together with their conventional abbreviations.
22390 The following should be read together with the full specification of the
22391 package, in file @code{s-dimmks.ads}.
22393 @quotation
22395 @geindex s-dimmks.ads file
22397 @example
22398 type Mks_Type is new Long_Long_Float
22399   with
22400    Dimension_System => (
22401      (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
22402      (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
22403      (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
22404      (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
22405      (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
22406      (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
22407      (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
22408 @end example
22409 @end quotation
22411 The package then defines a series of subtypes that correspond to these
22412 conventional units. For example:
22414 @quotation
22416 @example
22417 subtype Length is Mks_Type
22418   with
22419    Dimension => (Symbol => 'm', Meter  => 1, others => 0);
22420 @end example
22421 @end quotation
22423 and similarly for @cite{Mass}, @cite{Time}, @cite{Electric_Current},
22424 @cite{Thermodynamic_Temperature}, @cite{Amount_Of_Substance}, and
22425 @cite{Luminous_Intensity} (the standard set of units of the SI system).
22427 The package also defines conventional names for values of each unit, for
22428 example:
22430 @quotation
22432 @c code-block":: ada
22433 @c 
22434 @c m   : constant Length           := 1.0;
22435 @c kg  : constant Mass             := 1.0;
22436 @c s   : constant Time             := 1.0;
22437 @c A   : constant Electric_Current := 1.0;
22438 @end quotation
22440 as well as useful multiples of these units:
22442 @quotation
22444 @example
22445  cm  : constant Length := 1.0E-02;
22446  g   : constant Mass   := 1.0E-03;
22447  min : constant Time   := 60.0;
22448  day : constant Time   := 60.0 * 24.0 * min;
22450 @end example
22451 @end quotation
22453 Using this package, you can then define a derived unit by
22454 providing the aspect that
22455 specifies its dimensions within the MKS system, as well as the string to
22456 be used for output of a value of that unit:
22458 @quotation
22460 @example
22461 subtype Acceleration is Mks_Type
22462   with Dimension => ("m/sec^2",
22463                      Meter => 1,
22464                      Second => -2,
22465                      others => 0);
22466 @end example
22467 @end quotation
22469 Here is a complete example of use:
22471 @quotation
22473 @example
22474 with System.Dim.MKS; use System.Dim.Mks;
22475 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
22476 with Text_IO; use Text_IO;
22477 procedure Free_Fall is
22478   subtype Acceleration is Mks_Type
22479     with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
22480   G : constant acceleration := 9.81 * m / (s ** 2);
22481   T : Time := 10.0*s;
22482   Distance : Length;
22484 begin
22485   Put ("Gravitational constant: ");
22486   Put (G, Aft => 2, Exp => 0); Put_Line ("");
22487   Distance := 0.5 * G * T ** 2;
22488   Put ("distance travelled in 10 seconds of free fall ");
22489   Put (Distance, Aft => 2, Exp => 0);
22490   Put_Line ("");
22491 end Free_Fall;
22492 @end example
22493 @end quotation
22495 Execution of this program yields:
22497 @quotation
22499 @example
22500 Gravitational constant:  9.81 m/sec^2
22501 distance travelled in 10 seconds of free fall 490.50 m
22502 @end example
22503 @end quotation
22505 However, incorrect assignments such as:
22507 @quotation
22509 @example
22510 Distance := 5.0;
22511 Distance := 5.0 * kg:
22512 @end example
22513 @end quotation
22515 are rejected with the following diagnoses:
22517 @quotation
22519 @example
22520 Distance := 5.0;
22521    >>> dimensions mismatch in assignment
22522    >>> left-hand side has dimension [L]
22523    >>> right-hand side is dimensionless
22525 Distance := 5.0 * kg:
22526    >>> dimensions mismatch in assignment
22527    >>> left-hand side has dimension [L]
22528    >>> right-hand side has dimension [M]
22529 @end example
22530 @end quotation
22532 The dimensions of an expression are properly displayed, even if there is
22533 no explicit subtype for it. If we add to the program:
22535 @quotation
22537 @example
22538 Put ("Final velocity: ");
22539 Put (G * T, Aft =>2, Exp =>0);
22540 Put_Line ("");
22541 @end example
22542 @end quotation
22544 then the output includes:
22546 @quotation
22548 @example
22549 Final velocity: 98.10 m.s**(-1)
22550 @end example
22551 @end quotation
22553 @node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
22554 @anchor{gnat_ugn/gnat_and_program_execution id61}@anchor{16a}@anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{29}
22555 @section Stack Related Facilities
22558 This section describes some useful tools associated with stack
22559 checking and analysis. In
22560 particular, it deals with dynamic and static stack usage measurements.
22562 @menu
22563 * Stack Overflow Checking:: 
22564 * Static Stack Usage Analysis:: 
22565 * Dynamic Stack Usage Analysis:: 
22567 @end menu
22569 @node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
22570 @anchor{gnat_ugn/gnat_and_program_execution id62}@anchor{1c6}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{f4}
22571 @subsection Stack Overflow Checking
22574 @geindex Stack Overflow Checking
22576 @geindex -fstack-check (gcc)
22578 For most operating systems, @emph{gcc} does not perform stack overflow
22579 checking by default. This means that if the main environment task or
22580 some other task exceeds the available stack space, then unpredictable
22581 behavior will occur. Most native systems offer some level of protection by
22582 adding a guard page at the end of each task stack. This mechanism is usually
22583 not enough for dealing properly with stack overflow situations because
22584 a large local variable could "jump" above the guard page.
22585 Furthermore, when the
22586 guard page is hit, there may not be any space left on the stack for executing
22587 the exception propagation code. Enabling stack checking avoids
22588 such situations.
22590 To activate stack checking, compile all units with the gcc option
22591 @cite{-fstack-check}. For example:
22593 @quotation
22595 @example
22596 $ gcc -c -fstack-check package1.adb
22597 @end example
22598 @end quotation
22600 Units compiled with this option will generate extra instructions to check
22601 that any use of the stack (for procedure calls or for declaring local
22602 variables in declare blocks) does not exceed the available stack space.
22603 If the space is exceeded, then a @cite{Storage_Error} exception is raised.
22605 For declared tasks, the stack size is controlled by the size
22606 given in an applicable @cite{Storage_Size} pragma or by the value specified
22607 at bind time with @code{-d} (@ref{11d,,Switches for gnatbind}) or is set to
22608 the default size as defined in the GNAT runtime otherwise.
22610 @geindex GNAT_STACK_LIMIT
22612 For the environment task, the stack size depends on
22613 system defaults and is unknown to the compiler. Stack checking
22614 may still work correctly if a fixed
22615 size stack is allocated, but this cannot be guaranteed.
22616 To ensure that a clean exception is signalled for stack
22617 overflow, set the environment variable
22618 @geindex GNAT_STACK_LIMIT
22619 @geindex environment variable; GNAT_STACK_LIMIT
22620 @code{GNAT_STACK_LIMIT} to indicate the maximum
22621 stack area that can be used, as in:
22623 @quotation
22625 @example
22626 $ SET GNAT_STACK_LIMIT 1600
22627 @end example
22628 @end quotation
22630 The limit is given in kilobytes, so the above declaration would
22631 set the stack limit of the environment task to 1.6 megabytes.
22632 Note that the only purpose of this usage is to limit the amount
22633 of stack used by the environment task. If it is necessary to
22634 increase the amount of stack for the environment task, then this
22635 is an operating systems issue, and must be addressed with the
22636 appropriate operating systems commands.
22638 @node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
22639 @anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{f5}@anchor{gnat_ugn/gnat_and_program_execution id63}@anchor{1c7}
22640 @subsection Static Stack Usage Analysis
22643 @geindex Static Stack Usage Analysis
22645 @geindex -fstack-usage
22647 A unit compiled with @code{-fstack-usage} will generate an extra file
22648 that specifies
22649 the maximum amount of stack used, on a per-function basis.
22650 The file has the same
22651 basename as the target object file with a @code{.su} extension.
22652 Each line of this file is made up of three fields:
22655 @itemize *
22657 @item 
22658 The name of the function.
22660 @item 
22661 A number of bytes.
22663 @item 
22664 One or more qualifiers: @cite{static}, @cite{dynamic}, @cite{bounded}.
22665 @end itemize
22667 The second field corresponds to the size of the known part of the function
22668 frame.
22670 The qualifier @cite{static} means that the function frame size
22671 is purely static.
22672 It usually means that all local variables have a static size.
22673 In this case, the second field is a reliable measure of the function stack
22674 utilization.
22676 The qualifier @cite{dynamic} means that the function frame size is not static.
22677 It happens mainly when some local variables have a dynamic size. When this
22678 qualifier appears alone, the second field is not a reliable measure
22679 of the function stack analysis. When it is qualified with  @cite{bounded}, it
22680 means that the second field is a reliable maximum of the function stack
22681 utilization.
22683 A unit compiled with @code{-Wstack-usage} will issue a warning for each
22684 subprogram whose stack usage might be larger than the specified amount of
22685 bytes.  The wording is in keeping with the qualifier documented above.
22687 @node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
22688 @anchor{gnat_ugn/gnat_and_program_execution id64}@anchor{1c8}@anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{11f}
22689 @subsection Dynamic Stack Usage Analysis
22692 It is possible to measure the maximum amount of stack used by a task, by
22693 adding a switch to @emph{gnatbind}, as:
22695 @quotation
22697 @example
22698 $ gnatbind -u0 file
22699 @end example
22700 @end quotation
22702 With this option, at each task termination, its stack usage is  output on
22703 @code{stderr}.
22704 It is not always convenient to output the stack usage when the program
22705 is still running. Hence, it is possible to delay this output until program
22706 termination. for a given number of tasks specified as the argument of the
22707 @code{-u} option. For instance:
22709 @quotation
22711 @example
22712 $ gnatbind -u100 file
22713 @end example
22714 @end quotation
22716 will buffer the stack usage information of the first 100 tasks to terminate and
22717 output this info at program termination. Results are displayed in four
22718 columns:
22720 @quotation
22722 @example
22723 Index | Task Name | Stack Size | Stack Usage
22724 @end example
22725 @end quotation
22727 where:
22730 @itemize *
22732 @item 
22733 @emph{Index} is a number associated with each task.
22735 @item 
22736 @emph{Task Name} is the name of the task analyzed.
22738 @item 
22739 @emph{Stack Size} is the maximum size for the stack.
22741 @item 
22742 @emph{Stack Usage} is the measure done by the stack analyzer.
22743 In order to prevent overflow, the stack
22744 is not entirely analyzed, and it's not possible to know exactly how
22745 much has actually been used.
22746 @end itemize
22748 The environment task stack, e.g., the stack that contains the main unit, is
22749 only processed when the environment variable GNAT_STACK_LIMIT is set.
22751 The package @cite{GNAT.Task_Stack_Usage} provides facilities to get
22752 stack usage reports at run-time. See its body for the details.
22754 @node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
22755 @anchor{gnat_ugn/gnat_and_program_execution id65}@anchor{16b}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{2a}
22756 @section Memory Management Issues
22759 This section describes some useful memory pools provided in the GNAT library
22760 and in particular the GNAT Debug Pool facility, which can be used to detect
22761 incorrect uses of access values (including 'dangling references').
22764 @menu
22765 * Some Useful Memory Pools:: 
22766 * The GNAT Debug Pool Facility:: 
22768 @end menu
22770 @node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
22771 @anchor{gnat_ugn/gnat_and_program_execution id66}@anchor{1c9}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{1ca}
22772 @subsection Some Useful Memory Pools
22775 @geindex Memory Pool
22777 @geindex storage
22778 @geindex pool
22780 The @cite{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
22781 storage pool. Allocations use the standard system call @cite{malloc} while
22782 deallocations use the standard system call @cite{free}. No reclamation is
22783 performed when the pool goes out of scope. For performance reasons, the
22784 standard default Ada allocators/deallocators do not use any explicit storage
22785 pools but if they did, they could use this storage pool without any change in
22786 behavior. That is why this storage pool is used  when the user
22787 manages to make the default implicit allocator explicit as in this example:
22789 @quotation
22791 @example
22792 type T1 is access Something;
22793  -- no Storage pool is defined for T2
22795 type T2 is access Something_Else;
22796 for T2'Storage_Pool use T1'Storage_Pool;
22797 -- the above is equivalent to
22798 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
22799 @end example
22800 @end quotation
22802 The @cite{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
22803 pool. The allocation strategy is similar to @cite{Pool_Local}'s
22804 except that the all
22805 storage allocated with this pool is reclaimed when the pool object goes out of
22806 scope. This pool provides a explicit mechanism similar to the implicit one
22807 provided by several Ada 83 compilers for allocations performed through a local
22808 access type and whose purpose was to reclaim memory when exiting the
22809 scope of a given local access. As an example, the following program does not
22810 leak memory even though it does not perform explicit deallocation:
22812 @quotation
22814 @example
22815 with System.Pool_Local;
22816 procedure Pooloc1 is
22817    procedure Internal is
22818       type A is access Integer;
22819       X : System.Pool_Local.Unbounded_Reclaim_Pool;
22820       for A'Storage_Pool use X;
22821       v : A;
22822    begin
22823       for I in  1 .. 50 loop
22824          v := new Integer;
22825       end loop;
22826    end Internal;
22827 begin
22828    for I in  1 .. 100 loop
22829       Internal;
22830    end loop;
22831 end Pooloc1;
22832 @end example
22833 @end quotation
22835 The @cite{System.Pool_Size} package implements the Stack_Bounded_Pool used when
22836 @cite{Storage_Size} is specified for an access type.
22837 The whole storage for the pool is
22838 allocated at once, usually on the stack at the point where the access type is
22839 elaborated. It is automatically reclaimed when exiting the scope where the
22840 access type is defined. This package is not intended to be used directly by the
22841 user and it is implicitly used for each such declaration:
22843 @quotation
22845 @example
22846 type T1 is access Something;
22847 for T1'Storage_Size use 10_000;
22848 @end example
22849 @end quotation
22851 @node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
22852 @anchor{gnat_ugn/gnat_and_program_execution id67}@anchor{1cb}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{1cc}
22853 @subsection The GNAT Debug Pool Facility
22856 @geindex Debug Pool
22858 @geindex storage
22859 @geindex pool
22860 @geindex memory corruption
22862 The use of unchecked deallocation and unchecked conversion can easily
22863 lead to incorrect memory references. The problems generated by such
22864 references are usually difficult to tackle because the symptoms can be
22865 very remote from the origin of the problem. In such cases, it is
22866 very helpful to detect the problem as early as possible. This is the
22867 purpose of the Storage Pool provided by @cite{GNAT.Debug_Pools}.
22869 In order to use the GNAT specific debugging pool, the user must
22870 associate a debug pool object with each of the access types that may be
22871 related to suspected memory problems. See Ada Reference Manual 13.11.
22873 @quotation
22875 @example
22876 type Ptr is access Some_Type;
22877 Pool : GNAT.Debug_Pools.Debug_Pool;
22878 for Ptr'Storage_Pool use Pool;
22879 @end example
22880 @end quotation
22882 @cite{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
22883 pool: the @cite{Checked_Pool}. Such pools, like standard Ada storage pools,
22884 allow the user to redefine allocation and deallocation strategies. They
22885 also provide a checkpoint for each dereference, through the use of
22886 the primitive operation @cite{Dereference} which is implicitly called at
22887 each dereference of an access value.
22889 Once an access type has been associated with a debug pool, operations on
22890 values of the type may raise four distinct exceptions,
22891 which correspond to four potential kinds of memory corruption:
22894 @itemize *
22896 @item 
22897 @cite{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
22899 @item 
22900 @cite{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
22902 @item 
22903 @cite{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
22905 @item 
22906 @cite{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
22907 @end itemize
22909 For types associated with a Debug_Pool, dynamic allocation is performed using
22910 the standard GNAT allocation routine. References to all allocated chunks of
22911 memory are kept in an internal dictionary. Several deallocation strategies are
22912 provided, whereupon the user can choose to release the memory to the system,
22913 keep it allocated for further invalid access checks, or fill it with an easily
22914 recognizable pattern for debug sessions. The memory pattern is the old IBM
22915 hexadecimal convention: @cite{16#DEADBEEF#}.
22917 See the documentation in the file g-debpoo.ads for more information on the
22918 various strategies.
22920 Upon each dereference, a check is made that the access value denotes a
22921 properly allocated memory location. Here is a complete example of use of
22922 @cite{Debug_Pools}, that includes typical instances of  memory corruption:
22924 @quotation
22926 @example
22927 with Gnat.Io; use Gnat.Io;
22928 with Unchecked_Deallocation;
22929 with Unchecked_Conversion;
22930 with GNAT.Debug_Pools;
22931 with System.Storage_Elements;
22932 with Ada.Exceptions; use Ada.Exceptions;
22933 procedure Debug_Pool_Test is
22935    type T is access Integer;
22936    type U is access all T;
22938    P : GNAT.Debug_Pools.Debug_Pool;
22939    for T'Storage_Pool use P;
22941    procedure Free is new Unchecked_Deallocation (Integer, T);
22942    function UC is new Unchecked_Conversion (U, T);
22943    A, B : aliased T;
22945    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
22947 begin
22948    Info (P);
22949    A := new Integer;
22950    B := new Integer;
22951    B := A;
22952    Info (P);
22953    Free (A);
22954    begin
22955       Put_Line (Integer'Image(B.all));
22956    exception
22957       when E : others => Put_Line ("raised: " & Exception_Name (E));
22958    end;
22959    begin
22960       Free (B);
22961    exception
22962       when E : others => Put_Line ("raised: " & Exception_Name (E));
22963    end;
22964    B := UC(A'Access);
22965    begin
22966       Put_Line (Integer'Image(B.all));
22967    exception
22968       when E : others => Put_Line ("raised: " & Exception_Name (E));
22969    end;
22970    begin
22971       Free (B);
22972    exception
22973       when E : others => Put_Line ("raised: " & Exception_Name (E));
22974    end;
22975    Info (P);
22976 end Debug_Pool_Test;
22977 @end example
22978 @end quotation
22980 The debug pool mechanism provides the following precise diagnostics on the
22981 execution of this erroneous program:
22983 @quotation
22985 @example
22986 Debug Pool info:
22987   Total allocated bytes :  0
22988   Total deallocated bytes :  0
22989   Current Water Mark:  0
22990   High Water Mark:  0
22992 Debug Pool info:
22993   Total allocated bytes :  8
22994   Total deallocated bytes :  0
22995   Current Water Mark:  8
22996   High Water Mark:  8
22998 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
22999 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
23000 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
23001 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
23002 Debug Pool info:
23003   Total allocated bytes :  8
23004   Total deallocated bytes :  4
23005   Current Water Mark:  4
23006   High Water Mark:  8
23007 @end example
23008 @end quotation
23011 @c -- Non-breaking space in running text
23012 @c -- E.g. Ada |nbsp| 95
23014 @node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
23015 @anchor{gnat_ugn/platform_specific_information platform-specific-information}@anchor{d}@anchor{gnat_ugn/platform_specific_information doc}@anchor{1cd}@anchor{gnat_ugn/platform_specific_information id1}@anchor{1ce}
23016 @chapter Platform-Specific Information
23019 This appendix contains information relating to the implementation
23020 of run-time libraries on various platforms and also covers
23021 topics related to the GNAT implementation on Windows and Mac OS.
23023 @menu
23024 * Run-Time Libraries:: 
23025 * Specifying a Run-Time Library:: 
23026 * Microsoft Windows Topics:: 
23027 * Mac OS Topics:: 
23029 @end menu
23031 @node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
23032 @anchor{gnat_ugn/platform_specific_information id2}@anchor{1cf}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{2b}
23033 @section Run-Time Libraries
23036 @geindex Tasking and threads libraries
23038 @geindex Threads libraries and tasking
23040 @geindex Run-time libraries (platform-specific information)
23042 The GNAT run-time implementation may vary with respect to both the
23043 underlying threads library and the exception handling scheme.
23044 For threads support, one or more of the following are supplied:
23047 @itemize *
23049 @item 
23050 @strong{native threads library}, a binding to the thread package from
23051 the underlying operating system
23053 @item 
23054 @strong{pthreads library} (Sparc Solaris only), a binding to the Solaris
23055 POSIX thread package
23056 @end itemize
23058 For exception handling, either or both of two models are supplied:
23060 @quotation
23062 @geindex Zero-Cost Exceptions
23064 @geindex ZCX (Zero-Cost Exceptions)
23065 @end quotation
23068 @itemize *
23070 @item 
23071 @strong{Zero-Cost Exceptions} ("ZCX"),
23072 which uses binder-generated tables that
23073 are interrogated at run time to locate a handler.
23075 @geindex setjmp/longjmp Exception Model
23077 @geindex SJLJ (setjmp/longjmp Exception Model)
23079 @item 
23080 @strong{setjmp / longjmp} ('SJLJ'),
23081 which uses dynamically-set data to establish
23082 the set of handlers
23083 @end itemize
23085 Most programs should experience a substantial speed improvement by
23086 being compiled with a ZCX run-time.
23087 This is especially true for
23088 tasking applications or applications with many exception handlers.@}
23090 This section summarizes which combinations of threads and exception support
23091 are supplied on various GNAT platforms.
23092 It then shows how to select a particular library either
23093 permanently or temporarily,
23094 explains the properties of (and tradeoffs among) the various threads
23095 libraries, and provides some additional
23096 information about several specific platforms.
23098 @menu
23099 * Summary of Run-Time Configurations:: 
23101 @end menu
23103 @node Summary of Run-Time Configurations,,,Run-Time Libraries
23104 @anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{1d0}@anchor{gnat_ugn/platform_specific_information id3}@anchor{1d1}
23105 @subsection Summary of Run-Time Configurations
23109 @multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
23110 @headitem
23112 Platform
23114 @tab
23116 Run-Time
23118 @tab
23120 Tasking
23122 @tab
23124 Exceptions
23126 @item
23128 ppc-aix
23130 @tab
23132 rts-native
23133 (default)
23135 @tab
23137 native AIX threads
23139 @tab
23143 @item
23145 rts-sjlj
23147 @tab
23149 native AIX threads
23151 @tab
23153 SJLJ
23155 @item
23157 sparc-solaris
23159 @tab
23161 rts-native
23162 (default)
23164 @tab
23166 native Solaris
23167 threads library
23169 @tab
23173 @item
23175 rts-pthread
23177 @tab
23179 pthread library
23181 @tab
23185 @item
23187 rts-sjlj
23189 @tab
23191 native Solaris
23192 threads library
23194 @tab
23196 SJLJ
23198 @item
23200 sparc64-solaris
23202 @tab
23204 rts-native
23205 (default)
23207 @tab
23209 native Solaris
23210 threads library
23212 @tab
23216 @item
23218 x86-linux
23220 @tab
23222 rts-native
23223 (default)
23225 @tab
23227 pthread library
23229 @tab
23233 @item
23235 rts-sjlj
23237 @tab
23239 pthread library
23241 @tab
23243 SJLJ
23245 @item
23247 x86-lynx
23249 @tab
23251 rts-native
23252 (default)
23254 @tab
23256 native LynxOS threads
23258 @tab
23260 SJLJ
23262 @item
23264 x86-solaris
23266 @tab
23268 rts-native
23269 (default)
23271 @tab
23273 native Solaris
23274 threads library
23276 @tab
23280 @item
23282 rts-sjlj
23284 @tab
23286 native Solaris
23287 threads library
23289 @tab
23291 SJLJ
23293 @item
23295 x86-windows
23297 @tab
23299 rts-native
23300 (default)
23302 @tab
23304 native Win32 threads
23306 @tab
23310 @item
23312 rts-sjlj
23314 @tab
23316 native Win32 threads
23318 @tab
23320 SJLJ
23322 @item
23324 x86_64-linux
23326 @tab
23328 rts-native
23329 (default)
23331 @tab
23333 pthread library
23335 @tab
23339 @item
23341 rts-sjlj
23343 @tab
23345 pthread library
23347 @tab
23349 SJLJ
23351 @end multitable
23354 @node Specifying a Run-Time Library,Microsoft Windows Topics,Run-Time Libraries,Platform-Specific Information
23355 @anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{1d2}@anchor{gnat_ugn/platform_specific_information id4}@anchor{1d3}
23356 @section Specifying a Run-Time Library
23359 The @code{adainclude} subdirectory containing the sources of the GNAT
23360 run-time library, and the @code{adalib} subdirectory containing the
23361 @code{ALI} files and the static and/or shared GNAT library, are located
23362 in the gcc target-dependent area:
23364 @quotation
23366 @example
23367 target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
23368 @end example
23369 @end quotation
23371 As indicated above, on some platforms several run-time libraries are supplied.
23372 These libraries are installed in the target dependent area and
23373 contain a complete source and binary subdirectory. The detailed description
23374 below explains the differences between the different libraries in terms of
23375 their thread support.
23377 The default run-time library (when GNAT is installed) is @emph{rts-native}.
23378 This default run time is selected by the means of soft links.
23379 For example on x86-linux:
23381 @example
23383 --  $(target-dir)
23384 --      |
23385 --      +--- adainclude----------+
23386 --      |                        |
23387 --      +--- adalib-----------+  |
23388 --      |                     |  |
23389 --      +--- rts-native       |  |
23390 --      |    |                |  |
23391 --      |    +--- adainclude <---+
23392 --      |    |                |
23393 --      |    +--- adalib <----+
23394 --      |
23395 --      +--- rts-sjlj
23396 --           |
23397 --           +--- adainclude
23398 --           |
23399 --           +--- adalib
23400 @end example
23403 @example
23404                $(target-dir)
23405               __/ /      \ \___
23406       _______/   /        \    \_________________
23407      /          /          \                     \
23408     /          /            \                     \
23409 ADAINCLUDE  ADALIB      rts-native             rts-sjlj
23410    :          :            /    \                 /   \
23411    :          :           /      \               /     \
23412    :          :          /        \             /       \
23413    :          :         /          \           /         \
23414    +-------------> adainclude     adalib   adainclude   adalib
23415               :                     ^
23416               :                     :
23417               +---------------------+
23419               Run-Time Library Directory Structure
23420    (Upper-case names and dotted/dashed arrows represent soft links)
23421 @end example
23423 If the @emph{rts-sjlj} library is to be selected on a permanent basis,
23424 these soft links can be modified with the following commands:
23426 @quotation
23428 @example
23429 $ cd $target
23430 $ rm -f adainclude adalib
23431 $ ln -s rts-sjlj/adainclude adainclude
23432 $ ln -s rts-sjlj/adalib adalib
23433 @end example
23434 @end quotation
23436 Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
23437 @code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
23438 @code{$target/ada_object_path}.
23440 @geindex --RTS option
23442 Selecting another run-time library temporarily can be
23443 achieved by using the @emph{--RTS} switch, e.g., @emph{--RTS=sjlj}
23444 @anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy}@anchor{1d4}
23445 @geindex SCHED_FIFO scheduling policy
23447 @geindex SCHED_RR scheduling policy
23449 @geindex SCHED_OTHER scheduling policy
23451 @menu
23452 * Choosing the Scheduling Policy:: 
23453 * Solaris-Specific Considerations:: 
23454 * Solaris Threads Issues:: 
23455 * AIX-Specific Considerations:: 
23457 @end menu
23459 @node Choosing the Scheduling Policy,Solaris-Specific Considerations,,Specifying a Run-Time Library
23460 @anchor{gnat_ugn/platform_specific_information id5}@anchor{1d5}
23461 @subsection Choosing the Scheduling Policy
23464 When using a POSIX threads implementation, you have a choice of several
23465 scheduling policies: @cite{SCHED_FIFO}, @cite{SCHED_RR} and @cite{SCHED_OTHER}.
23467 Typically, the default is @cite{SCHED_OTHER}, while using @cite{SCHED_FIFO}
23468 or @cite{SCHED_RR} requires special (e.g., root) privileges.
23470 @geindex pragma Time_Slice
23472 @geindex -T0 option
23474 @geindex pragma Task_Dispatching_Policy
23476 By default, GNAT uses the @cite{SCHED_OTHER} policy. To specify
23477 @cite{SCHED_FIFO},
23478 you can use one of the following:
23481 @itemize *
23483 @item 
23484 @cite{pragma Time_Slice (0.0)}
23486 @item 
23487 the corresponding binder option @emph{-T0}
23489 @item 
23490 @cite{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23491 @end itemize
23493 To specify @cite{SCHED_RR},
23494 you should use @cite{pragma Time_Slice} with a
23495 value greater than 0.0, or else use the corresponding @emph{-T}
23496 binder option.
23498 @geindex Solaris Sparc threads libraries
23500 @node Solaris-Specific Considerations,Solaris Threads Issues,Choosing the Scheduling Policy,Specifying a Run-Time Library
23501 @anchor{gnat_ugn/platform_specific_information id6}@anchor{1d6}@anchor{gnat_ugn/platform_specific_information solaris-specific-considerations}@anchor{1d7}
23502 @subsection Solaris-Specific Considerations
23505 This section addresses some topics related to the various threads libraries
23506 on Sparc Solaris.
23508 @geindex rts-pthread threads library
23510 @node Solaris Threads Issues,AIX-Specific Considerations,Solaris-Specific Considerations,Specifying a Run-Time Library
23511 @anchor{gnat_ugn/platform_specific_information id7}@anchor{1d8}@anchor{gnat_ugn/platform_specific_information solaris-threads-issues}@anchor{1d9}
23512 @subsection Solaris Threads Issues
23515 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
23516 library based on POSIX threads --- @emph{rts-pthread}.
23518 @geindex PTHREAD_PRIO_INHERIT policy (under rts-pthread)
23520 @geindex PTHREAD_PRIO_PROTECT policy (under rts-pthread)
23522 @geindex pragma Locking_Policy (under rts-pthread)
23524 @geindex Inheritance_Locking (under rts-pthread)
23526 @geindex Ceiling_Locking (under rts-pthread)
23528 This run-time library has the advantage of being mostly shared across all
23529 POSIX-compliant thread implementations, and it also provides under
23530 Solaris 8 the @cite{PTHREAD_PRIO_INHERIT}
23531 and @cite{PTHREAD_PRIO_PROTECT}
23532 semantics that can be selected using the predefined pragma
23533 @cite{Locking_Policy}
23534 with respectively
23535 @cite{Inheritance_Locking} and @cite{Ceiling_Locking} as the policy.
23537 As explained above, the native run-time library is based on the Solaris thread
23538 library (@cite{libthread}) and is the default library.
23540 @geindex GNAT_PROCESSOR environment variable (on Sparc Solaris)
23542 When the Solaris threads library is used (this is the default), programs
23543 compiled with GNAT can automatically take advantage of
23544 and can thus execute on multiple processors.
23545 The user can alternatively specify a processor on which the program should run
23546 to emulate a single-processor system. The multiprocessor / uniprocessor choice
23547 is made by
23548 setting the environment variable 
23549 @geindex GNAT_PROCESSOR
23550 @geindex environment variable; GNAT_PROCESSOR
23551 @code{GNAT_PROCESSOR}
23552 to one of the following:
23554 @quotation
23557 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
23558 @headitem
23560 @code{GNAT_PROCESSOR} Value
23562 @tab
23564 Effect
23566 @item
23568 @emph{-2}
23570 @tab
23572 Use the default configuration (run the program on all
23573 available processors) - this is the same as having @cite{GNAT_PROCESSOR}
23574 unset
23576 @item
23578 @emph{-1}
23580 @tab
23582 Let the run-time implementation choose one processor and run the
23583 program on that processor
23585 @item
23587 @emph{0 .. Last_Proc}
23589 @tab
23591 Run the program on the specified processor.
23592 @cite{Last_Proc} is equal to @cite{_SC_NPROCESSORS_CONF - 1}
23593 (where @cite{_SC_NPROCESSORS_CONF} is a system variable).
23595 @end multitable
23597 @end quotation
23599 @node AIX-Specific Considerations,,Solaris Threads Issues,Specifying a Run-Time Library
23600 @anchor{gnat_ugn/platform_specific_information aix-specific-considerations}@anchor{1da}@anchor{gnat_ugn/platform_specific_information id8}@anchor{1db}
23601 @subsection AIX-Specific Considerations
23604 @geindex AIX resolver library
23606 On AIX, the resolver library initializes some internal structure on
23607 the first call to @cite{get*by*} functions, which are used to implement
23608 @cite{GNAT.Sockets.Get_Host_By_Name} and
23609 @cite{GNAT.Sockets.Get_Host_By_Address}.
23610 If such initialization occurs within an Ada task, and the stack size for
23611 the task is the default size, a stack overflow may occur.
23613 To avoid this overflow, the user should either ensure that the first call
23614 to @cite{GNAT.Sockets.Get_Host_By_Name} or
23615 @cite{GNAT.Sockets.Get_Host_By_Addrss}
23616 occurs in the environment task, or use @cite{pragma Storage_Size} to
23617 specify a sufficiently large size for the stack of the task that contains
23618 this call.
23620 @geindex Windows NT
23622 @geindex Windows 95
23624 @geindex Windows 98
23626 @node Microsoft Windows Topics,Mac OS Topics,Specifying a Run-Time Library,Platform-Specific Information
23627 @anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{2c}@anchor{gnat_ugn/platform_specific_information id9}@anchor{1dc}
23628 @section Microsoft Windows Topics
23631 This section describes topics that are specific to the Microsoft Windows
23632 platforms.
23638 @menu
23639 * Using GNAT on Windows:: 
23640 * Using a network installation of GNAT:: 
23641 * CONSOLE and WINDOWS subsystems:: 
23642 * Temporary Files:: 
23643 * Disabling Command Line Argument Expansion:: 
23644 * Mixed-Language Programming on Windows:: 
23645 * Windows Specific Add-Ons:: 
23647 @end menu
23649 @node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
23650 @anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{1dd}@anchor{gnat_ugn/platform_specific_information id10}@anchor{1de}
23651 @subsection Using GNAT on Windows
23654 One of the strengths of the GNAT technology is that its tool set
23655 (@emph{gcc}, @emph{gnatbind}, @emph{gnatlink}, @emph{gnatmake}, the
23656 @cite{gdb} debugger, etc.) is used in the same way regardless of the
23657 platform.
23659 On Windows this tool set is complemented by a number of Microsoft-specific
23660 tools that have been provided to facilitate interoperability with Windows
23661 when this is required. With these tools:
23664 @itemize *
23666 @item 
23667 You can build applications using the @cite{CONSOLE} or @cite{WINDOWS}
23668 subsystems.
23670 @item 
23671 You can use any Dynamically Linked Library (DLL) in your Ada code (both
23672 relocatable and non-relocatable DLLs are supported).
23674 @item 
23675 You can build Ada DLLs for use in other applications. These applications
23676 can be written in a language other than Ada (e.g., C, C++, etc). Again both
23677 relocatable and non-relocatable Ada DLLs are supported.
23679 @item 
23680 You can include Windows resources in your Ada application.
23682 @item 
23683 You can use or create COM/DCOM objects.
23684 @end itemize
23686 Immediately below are listed all known general GNAT-for-Windows restrictions.
23687 Other restrictions about specific features like Windows Resources and DLLs
23688 are listed in separate sections below.
23691 @itemize *
23693 @item 
23694 It is not possible to use @cite{GetLastError} and @cite{SetLastError}
23695 when tasking, protected records, or exceptions are used. In these
23696 cases, in order to implement Ada semantics, the GNAT run-time system
23697 calls certain Win32 routines that set the last error variable to 0 upon
23698 success. It should be possible to use @cite{GetLastError} and
23699 @cite{SetLastError} when tasking, protected record, and exception
23700 features are not used, but it is not guaranteed to work.
23702 @item 
23703 It is not possible to link against Microsoft C++ libraries except for
23704 import libraries. Interfacing must be done by the mean of DLLs.
23706 @item 
23707 It is possible to link against Microsoft C libraries. Yet the preferred
23708 solution is to use C/C++ compiler that comes with GNAT, since it
23709 doesn't require having two different development environments and makes the
23710 inter-language debugging experience smoother.
23712 @item 
23713 When the compilation environment is located on FAT32 drives, users may
23714 experience recompilations of the source files that have not changed if
23715 Daylight Saving Time (DST) state has changed since the last time files
23716 were compiled. NTFS drives do not have this problem.
23718 @item 
23719 No components of the GNAT toolset use any entries in the Windows
23720 registry. The only entries that can be created are file associations and
23721 PATH settings, provided the user has chosen to create them at installation
23722 time, as well as some minimal book-keeping information needed to correctly
23723 uninstall or integrate different GNAT products.
23724 @end itemize
23726 @node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
23727 @anchor{gnat_ugn/platform_specific_information id11}@anchor{1df}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{1e0}
23728 @subsection Using a network installation of GNAT
23731 Make sure the system on which GNAT is installed is accessible from the
23732 current machine, i.e., the install location is shared over the network.
23733 Shared resources are accessed on Windows by means of UNC paths, which
23734 have the format @cite{\\server\sharename\path}
23736 In order to use such a network installation, simply add the UNC path of the
23737 @code{bin} directory of your GNAT installation in front of your PATH. For
23738 example, if GNAT is installed in @code{\GNAT} directory of a share location
23739 called @code{c-drive} on a machine @code{LOKI}, the following command will
23740 make it available:
23742 @quotation
23744 @example
23745 $ path \\loki\c-drive\gnat\bin;%path%`
23746 @end example
23747 @end quotation
23749 Be aware that every compilation using the network installation results in the
23750 transfer of large amounts of data across the network and will likely cause
23751 serious performance penalty.
23753 @node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
23754 @anchor{gnat_ugn/platform_specific_information id12}@anchor{1e1}@anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{1e2}
23755 @subsection CONSOLE and WINDOWS subsystems
23758 @geindex CONSOLE Subsystem
23760 @geindex WINDOWS Subsystem
23762 @geindex -mwindows
23764 There are two main subsystems under Windows. The @cite{CONSOLE} subsystem
23765 (which is the default subsystem) will always create a console when
23766 launching the application. This is not something desirable when the
23767 application has a Windows GUI. To get rid of this console the
23768 application must be using the @cite{WINDOWS} subsystem. To do so
23769 the @emph{-mwindows} linker option must be specified.
23771 @quotation
23773 @example
23774 $ gnatmake winprog -largs -mwindows
23775 @end example
23776 @end quotation
23778 @node Temporary Files,Disabling Command Line Argument Expansion,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
23779 @anchor{gnat_ugn/platform_specific_information id13}@anchor{1e3}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{1e4}
23780 @subsection Temporary Files
23783 @geindex Temporary files
23785 It is possible to control where temporary files gets created by setting
23786 the 
23787 @geindex TMP
23788 @geindex environment variable; TMP
23789 @code{TMP} environment variable. The file will be created:
23792 @itemize *
23794 @item 
23795 Under the directory pointed to by the 
23796 @geindex TMP
23797 @geindex environment variable; TMP
23798 @code{TMP} environment variable if
23799 this directory exists.
23801 @item 
23802 Under @code{c:\temp}, if the 
23803 @geindex TMP
23804 @geindex environment variable; TMP
23805 @code{TMP} environment variable is not
23806 set (or not pointing to a directory) and if this directory exists.
23808 @item 
23809 Under the current working directory otherwise.
23810 @end itemize
23812 This allows you to determine exactly where the temporary
23813 file will be created. This is particularly useful in networked
23814 environments where you may not have write access to some
23815 directories.
23817 @node Disabling Command Line Argument Expansion,Mixed-Language Programming on Windows,Temporary Files,Microsoft Windows Topics
23818 @anchor{gnat_ugn/platform_specific_information disabling-command-line-argument-expansion}@anchor{1e5}
23819 @subsection Disabling Command Line Argument Expansion
23822 @geindex Command Line Argument Expansion
23824 By default, an executable compiled for the @strong{Windows} platform will do
23825 the following postprocessing on the arguments passed on the command
23826 line:
23829 @itemize *
23831 @item 
23832 If the argument contains the characters @code{*} and/or @code{?}, then
23833 file expansion will be attempted. For example, if the current directory
23834 contains @code{a.txt} and @code{b.txt}, then when calling:
23836 @example
23837 $ my_ada_program *.txt
23838 @end example
23840 The following arguments will effectively be passed to the main program
23841 (for example when using @code{Ada.Command_Line.Argument}):
23843 @example
23844 Ada.Command_Line.Argument (1) -> "a.txt"
23845 Ada.Command_Line.Argument (2) -> "b.txt"
23846 @end example
23848 @item 
23849 Filename expansion can be disabled for a given argument by using single
23850 quotes. Thus, calling:
23852 @example
23853 $ my_ada_program '*.txt'
23854 @end example
23856 will result in:
23858 @example
23859 Ada.Command_Line.Argument (1) -> "*.txt"
23860 @end example
23861 @end itemize
23863 Note that if the program is launched from a shell such as @strong{Cygwin} @strong{Bash}
23864 then quote removal might be performed by the shell.
23866 In some contexts it might be useful to disable this feature (for example if
23867 the program performs its own argument expansion). In order to do this, a C
23868 symbol needs to be defined and set to @code{0}. You can do this by
23869 adding the following code fragment in one of your @strong{Ada} units:
23871 @example
23872 Do_Argv_Expansion : Integer := 0;
23873 pragma Export (C, Do_Argv_Expansion, "__gnat_do_argv_expansion");
23874 @end example
23876 The results of previous examples will be respectively:
23878 @example
23879 Ada.Command_Line.Argument (1) -> "*.txt"
23880 @end example
23882 and:
23884 @example
23885 Ada.Command_Line.Argument (1) -> "'*.txt'"
23886 @end example
23888 @node Mixed-Language Programming on Windows,Windows Specific Add-Ons,Disabling Command Line Argument Expansion,Microsoft Windows Topics
23889 @anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{1e6}@anchor{gnat_ugn/platform_specific_information id14}@anchor{1e7}
23890 @subsection Mixed-Language Programming on Windows
23893 Developing pure Ada applications on Windows is no different than on
23894 other GNAT-supported platforms. However, when developing or porting an
23895 application that contains a mix of Ada and C/C++, the choice of your
23896 Windows C/C++ development environment conditions your overall
23897 interoperability strategy.
23899 If you use @emph{gcc} or Microsoft C to compile the non-Ada part of
23900 your application, there are no Windows-specific restrictions that
23901 affect the overall interoperability with your Ada code. If you do want
23902 to use the Microsoft tools for your C++ code, you have two choices:
23905 @itemize *
23907 @item 
23908 Encapsulate your C++ code in a DLL to be linked with your Ada
23909 application. In this case, use the Microsoft or whatever environment to
23910 build the DLL and use GNAT to build your executable
23911 (@ref{1e8,,Using DLLs with GNAT}).
23913 @item 
23914 Or you can encapsulate your Ada code in a DLL to be linked with the
23915 other part of your application. In this case, use GNAT to build the DLL
23916 (@ref{1e9,,Building DLLs with GNAT Project files}) and use the Microsoft
23917 or whatever environment to build your executable.
23918 @end itemize
23920 In addition to the description about C main in
23921 @ref{44,,Mixed Language Programming} section, if the C main uses a
23922 stand-alone library it is required on x86-windows to
23923 setup the SEH context. For this the C main must looks like this:
23925 @quotation
23927 @example
23928 /* main.c */
23929 extern void adainit (void);
23930 extern void adafinal (void);
23931 extern void __gnat_initialize(void*);
23932 extern void call_to_ada (void);
23934 int main (int argc, char *argv[])
23936   int SEH [2];
23938   /* Initialize the SEH context */
23939   __gnat_initialize (&SEH);
23941   adainit();
23943   /* Then call Ada services in the stand-alone library */
23945   call_to_ada();
23947   adafinal();
23949 @end example
23950 @end quotation
23952 Note that this is not needed on x86_64-windows where the Windows
23953 native SEH support is used.
23955 @menu
23956 * Windows Calling Conventions:: 
23957 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
23958 * Using DLLs with GNAT:: 
23959 * Building DLLs with GNAT Project files:: 
23960 * Building DLLs with GNAT:: 
23961 * Building DLLs with gnatdll:: 
23962 * Ada DLLs and Finalization:: 
23963 * Creating a Spec for Ada DLLs:: 
23964 * GNAT and Windows Resources:: 
23965 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
23966 * Debugging a DLL:: 
23967 * Setting Stack Size from gnatlink:: 
23968 * Setting Heap Size from gnatlink:: 
23970 @end menu
23972 @node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
23973 @anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{1ea}@anchor{gnat_ugn/platform_specific_information id15}@anchor{1eb}
23974 @subsubsection Windows Calling Conventions
23977 @geindex Stdcall
23979 @geindex APIENTRY
23981 This section pertain only to Win32. On Win64 there is a single native
23982 calling convention. All convention specifiers are ignored on this
23983 platform.
23985 When a subprogram @cite{F} (caller) calls a subprogram @cite{G}
23986 (callee), there are several ways to push @cite{G}'s parameters on the
23987 stack and there are several possible scenarios to clean up the stack
23988 upon @cite{G}'s return. A calling convention is an agreed upon software
23989 protocol whereby the responsibilities between the caller (@cite{F}) and
23990 the callee (@cite{G}) are clearly defined. Several calling conventions
23991 are available for Windows:
23994 @itemize *
23996 @item 
23997 @cite{C} (Microsoft defined)
23999 @item 
24000 @cite{Stdcall} (Microsoft defined)
24002 @item 
24003 @cite{Win32} (GNAT specific)
24005 @item 
24006 @cite{DLL} (GNAT specific)
24007 @end itemize
24009 @menu
24010 * C Calling Convention:: 
24011 * Stdcall Calling Convention:: 
24012 * Win32 Calling Convention:: 
24013 * DLL Calling Convention:: 
24015 @end menu
24017 @node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
24018 @anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{1ec}@anchor{gnat_ugn/platform_specific_information id16}@anchor{1ed}
24019 @subsubsection @cite{C} Calling Convention
24022 This is the default calling convention used when interfacing to C/C++
24023 routines compiled with either @emph{gcc} or Microsoft Visual C++.
24025 In the @cite{C} calling convention subprogram parameters are pushed on the
24026 stack by the caller from right to left. The caller itself is in charge of
24027 cleaning up the stack after the call. In addition, the name of a routine
24028 with @cite{C} calling convention is mangled by adding a leading underscore.
24030 The name to use on the Ada side when importing (or exporting) a routine
24031 with @cite{C} calling convention is the name of the routine. For
24032 instance the C function:
24034 @quotation
24036 @example
24037 int get_val (long);
24038 @end example
24039 @end quotation
24041 should be imported from Ada as follows:
24043 @quotation
24045 @example
24046 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24047 pragma Import (C, Get_Val, External_Name => "get_val");
24048 @end example
24049 @end quotation
24051 Note that in this particular case the @cite{External_Name} parameter could
24052 have been omitted since, when missing, this parameter is taken to be the
24053 name of the Ada entity in lower case. When the @cite{Link_Name} parameter
24054 is missing, as in the above example, this parameter is set to be the
24055 @cite{External_Name} with a leading underscore.
24057 When importing a variable defined in C, you should always use the @cite{C}
24058 calling convention unless the object containing the variable is part of a
24059 DLL (in which case you should use the @cite{Stdcall} calling
24060 convention, @ref{1ee,,Stdcall Calling Convention}).
24062 @node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
24063 @anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{1ee}@anchor{gnat_ugn/platform_specific_information id17}@anchor{1ef}
24064 @subsubsection @cite{Stdcall} Calling Convention
24067 This convention, which was the calling convention used for Pascal
24068 programs, is used by Microsoft for all the routines in the Win32 API for
24069 efficiency reasons. It must be used to import any routine for which this
24070 convention was specified.
24072 In the @cite{Stdcall} calling convention subprogram parameters are pushed
24073 on the stack by the caller from right to left. The callee (and not the
24074 caller) is in charge of cleaning the stack on routine exit. In addition,
24075 the name of a routine with @cite{Stdcall} calling convention is mangled by
24076 adding a leading underscore (as for the @cite{C} calling convention) and a
24077 trailing @code{@@@emph{nn}}, where @cite{nn} is the overall size (in
24078 bytes) of the parameters passed to the routine.
24080 The name to use on the Ada side when importing a C routine with a
24081 @cite{Stdcall} calling convention is the name of the C routine. The leading
24082 underscore and trailing @code{@@@emph{nn}} are added automatically by
24083 the compiler. For instance the Win32 function:
24085 @quotation
24087 @example
24088 APIENTRY int get_val (long);
24089 @end example
24090 @end quotation
24092 should be imported from Ada as follows:
24094 @quotation
24096 @example
24097 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24098 pragma Import (Stdcall, Get_Val);
24099 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
24100 @end example
24101 @end quotation
24103 As for the @cite{C} calling convention, when the @cite{External_Name}
24104 parameter is missing, it is taken to be the name of the Ada entity in lower
24105 case. If instead of writing the above import pragma you write:
24107 @quotation
24109 @example
24110 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24111 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
24112 @end example
24113 @end quotation
24115 then the imported routine is @cite{_retrieve_val@@4}. However, if instead
24116 of specifying the @cite{External_Name} parameter you specify the
24117 @cite{Link_Name} as in the following example:
24119 @quotation
24121 @example
24122 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24123 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
24124 @end example
24125 @end quotation
24127 then the imported routine is @cite{retrieve_val}, that is, there is no
24128 decoration at all. No leading underscore and no Stdcall suffix
24129 @code{@@@emph{nn}}.
24131 This is especially important as in some special cases a DLL's entry
24132 point name lacks a trailing @code{@@@emph{nn}} while the exported
24133 name generated for a call has it.
24135 It is also possible to import variables defined in a DLL by using an
24136 import pragma for a variable. As an example, if a DLL contains a
24137 variable defined as:
24139 @quotation
24141 @example
24142 int my_var;
24143 @end example
24144 @end quotation
24146 then, to access this variable from Ada you should write:
24148 @quotation
24150 @example
24151 My_Var : Interfaces.C.int;
24152 pragma Import (Stdcall, My_Var);
24153 @end example
24154 @end quotation
24156 Note that to ease building cross-platform bindings this convention
24157 will be handled as a @cite{C} calling convention on non-Windows platforms.
24159 @node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
24160 @anchor{gnat_ugn/platform_specific_information id18}@anchor{1f0}@anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{1f1}
24161 @subsubsection @cite{Win32} Calling Convention
24164 This convention, which is GNAT-specific is fully equivalent to the
24165 @cite{Stdcall} calling convention described above.
24167 @node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
24168 @anchor{gnat_ugn/platform_specific_information id19}@anchor{1f2}@anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{1f3}
24169 @subsubsection @cite{DLL} Calling Convention
24172 This convention, which is GNAT-specific is fully equivalent to the
24173 @cite{Stdcall} calling convention described above.
24175 @node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
24176 @anchor{gnat_ugn/platform_specific_information id20}@anchor{1f4}@anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{1f5}
24177 @subsubsection Introduction to Dynamic Link Libraries (DLLs)
24180 @geindex DLL
24182 A Dynamically Linked Library (DLL) is a library that can be shared by
24183 several applications running under Windows. A DLL can contain any number of
24184 routines and variables.
24186 One advantage of DLLs is that you can change and enhance them without
24187 forcing all the applications that depend on them to be relinked or
24188 recompiled. However, you should be aware than all calls to DLL routines are
24189 slower since, as you will understand below, such calls are indirect.
24191 To illustrate the remainder of this section, suppose that an application
24192 wants to use the services of a DLL @code{API.dll}. To use the services
24193 provided by @code{API.dll} you must statically link against the DLL or
24194 an import library which contains a jump table with an entry for each
24195 routine and variable exported by the DLL. In the Microsoft world this
24196 import library is called @code{API.lib}. When using GNAT this import
24197 library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
24198 @code{libAPI.a} or @code{libapi.a} (names are case insensitive).
24200 After you have linked your application with the DLL or the import library
24201 and you run your application, here is what happens:
24204 @itemize *
24206 @item 
24207 Your application is loaded into memory.
24209 @item 
24210 The DLL @code{API.dll} is mapped into the address space of your
24211 application. This means that:
24214 @itemize -
24216 @item 
24217 The DLL will use the stack of the calling thread.
24219 @item 
24220 The DLL will use the virtual address space of the calling process.
24222 @item 
24223 The DLL will allocate memory from the virtual address space of the calling
24224 process.
24226 @item 
24227 Handles (pointers) can be safely exchanged between routines in the DLL
24228 routines and routines in the application using the DLL.
24229 @end itemize
24231 @item 
24232 The entries in the jump table (from the import library @code{libAPI.dll.a}
24233 or @code{API.lib} or automatically created when linking against a DLL)
24234 which is part of your application are initialized with the addresses
24235 of the routines and variables in @code{API.dll}.
24237 @item 
24238 If present in @code{API.dll}, routines @cite{DllMain} or
24239 @cite{DllMainCRTStartup} are invoked. These routines typically contain
24240 the initialization code needed for the well-being of the routines and
24241 variables exported by the DLL.
24242 @end itemize
24244 There is an additional point which is worth mentioning. In the Windows
24245 world there are two kind of DLLs: relocatable and non-relocatable
24246 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
24247 in the target application address space. If the addresses of two
24248 non-relocatable DLLs overlap and these happen to be used by the same
24249 application, a conflict will occur and the application will run
24250 incorrectly. Hence, when possible, it is always preferable to use and
24251 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
24252 supported by GNAT. Note that the @emph{-s} linker option (see GNU Linker
24253 User's Guide) removes the debugging symbols from the DLL but the DLL can
24254 still be relocated.
24256 As a side note, an interesting difference between Microsoft DLLs and
24257 Unix shared libraries, is the fact that on most Unix systems all public
24258 routines are exported by default in a Unix shared library, while under
24259 Windows it is possible (but not required) to list exported routines in
24260 a definition file (see @ref{1f6,,The Definition File}).
24262 @node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
24263 @anchor{gnat_ugn/platform_specific_information id21}@anchor{1f7}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{1e8}
24264 @subsubsection Using DLLs with GNAT
24267 To use the services of a DLL, say @code{API.dll}, in your Ada application
24268 you must have:
24271 @itemize *
24273 @item 
24274 The Ada spec for the routines and/or variables you want to access in
24275 @code{API.dll}. If not available this Ada spec must be built from the C/C++
24276 header files provided with the DLL.
24278 @item 
24279 The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
24280 mentioned an import library is a statically linked library containing the
24281 import table which will be filled at load time to point to the actual
24282 @code{API.dll} routines. Sometimes you don't have an import library for the
24283 DLL you want to use. The following sections will explain how to build
24284 one. Note that this is optional.
24286 @item 
24287 The actual DLL, @code{API.dll}.
24288 @end itemize
24290 Once you have all the above, to compile an Ada application that uses the
24291 services of @code{API.dll} and whose main subprogram is @cite{My_Ada_App},
24292 you simply issue the command
24294 @quotation
24296 @example
24297 $ gnatmake my_ada_app -largs -lAPI
24298 @end example
24299 @end quotation
24301 The argument @emph{-largs -lAPI} at the end of the @emph{gnatmake} command
24302 tells the GNAT linker to look for an import library. The linker will
24303 look for a library name in this specific order:
24306 @itemize *
24308 @item 
24309 @code{libAPI.dll.a}
24311 @item 
24312 @code{API.dll.a}
24314 @item 
24315 @code{libAPI.a}
24317 @item 
24318 @code{API.lib}
24320 @item 
24321 @code{libAPI.dll}
24323 @item 
24324 @code{API.dll}
24325 @end itemize
24327 The first three are the GNU style import libraries. The third is the
24328 Microsoft style import libraries. The last two are the actual DLL names.
24330 Note that if the Ada package spec for @code{API.dll} contains the
24331 following pragma
24333 @quotation
24335 @example
24336 pragma Linker_Options ("-lAPI");
24337 @end example
24338 @end quotation
24340 you do not have to add @emph{-largs -lAPI} at the end of the
24341 @emph{gnatmake} command.
24343 If any one of the items above is missing you will have to create it
24344 yourself. The following sections explain how to do so using as an
24345 example a fictitious DLL called @code{API.dll}.
24347 @menu
24348 * Creating an Ada Spec for the DLL Services:: 
24349 * Creating an Import Library:: 
24351 @end menu
24353 @node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
24354 @anchor{gnat_ugn/platform_specific_information creating-an-ada-spec-for-the-dll-services}@anchor{1f8}@anchor{gnat_ugn/platform_specific_information id22}@anchor{1f9}
24355 @subsubsection Creating an Ada Spec for the DLL Services
24358 A DLL typically comes with a C/C++ header file which provides the
24359 definitions of the routines and variables exported by the DLL. The Ada
24360 equivalent of this header file is a package spec that contains definitions
24361 for the imported entities. If the DLL you intend to use does not come with
24362 an Ada spec you have to generate one such spec yourself. For example if
24363 the header file of @code{API.dll} is a file @code{api.h} containing the
24364 following two definitions:
24366 @quotation
24368 @example
24369 int some_var;
24370 int get (char *);
24371 @end example
24372 @end quotation
24374 then the equivalent Ada spec could be:
24376 @quotation
24378 @example
24379 with Interfaces.C.Strings;
24380 package API is
24381    use Interfaces;
24383    Some_Var : C.int;
24384    function Get (Str : C.Strings.Chars_Ptr) return C.int;
24386 private
24387    pragma Import (C, Get);
24388    pragma Import (DLL, Some_Var);
24389 end API;
24390 @end example
24391 @end quotation
24393 @node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
24394 @anchor{gnat_ugn/platform_specific_information id23}@anchor{1fa}@anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{1fb}
24395 @subsubsection Creating an Import Library
24398 @geindex Import library
24400 If a Microsoft-style import library @code{API.lib} or a GNAT-style
24401 import library @code{libAPI.dll.a} or @code{libAPI.a} is available
24402 with @code{API.dll} you can skip this section. You can also skip this
24403 section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
24404 as in this case it is possible to link directly against the
24405 DLL. Otherwise read on.
24407 @geindex Definition file
24408 @anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{1f6}
24409 @subsubheading The Definition File
24412 As previously mentioned, and unlike Unix systems, the list of symbols
24413 that are exported from a DLL must be provided explicitly in Windows.
24414 The main goal of a definition file is precisely that: list the symbols
24415 exported by a DLL. A definition file (usually a file with a @cite{.def}
24416 suffix) has the following structure:
24418 @quotation
24420 @example
24421 [LIBRARY `name`]
24422 [DESCRIPTION `string`]
24423 EXPORTS
24424    `symbol1`
24425    `symbol2`
24426    ...
24427 @end example
24428 @end quotation
24431 @table @asis
24433 @item @emph{LIBRARY `name`}
24435 This section, which is optional, gives the name of the DLL.
24437 @item @emph{DESCRIPTION `string`}
24439 This section, which is optional, gives a description string that will be
24440 embedded in the import library.
24442 @item @emph{EXPORTS}
24444 This section gives the list of exported symbols (procedures, functions or
24445 variables). For instance in the case of @code{API.dll} the @cite{EXPORTS}
24446 section of @code{API.def} looks like:
24448 @example
24449 EXPORTS
24450    some_var
24451    get
24452 @end example
24453 @end table
24455 Note that you must specify the correct suffix (@code{@@@emph{nn}})
24456 (see @ref{1ea,,Windows Calling Conventions}) for a Stdcall
24457 calling convention function in the exported symbols list.
24459 There can actually be other sections in a definition file, but these
24460 sections are not relevant to the discussion at hand.
24461 @anchor{gnat_ugn/platform_specific_information create-def-file-automatically}@anchor{1fc}
24462 @subsubheading Creating a Definition File Automatically
24465 You can automatically create the definition file @code{API.def}
24466 (see @ref{1f6,,The Definition File}) from a DLL.
24467 For that use the @cite{dlltool} program as follows:
24469 @quotation
24471 @example
24472 $ dlltool API.dll -z API.def --export-all-symbols
24473 @end example
24475 Note that if some routines in the DLL have the @cite{Stdcall} convention
24476 (@ref{1ea,,Windows Calling Conventions}) with stripped @code{@@@emph{nn}}
24477 suffix then you'll have to edit @code{api.def} to add it, and specify
24478 @emph{-k} to @emph{gnatdll} when creating the import library.
24480 Here are some hints to find the right @code{@@@emph{nn}} suffix.
24483 @itemize -
24485 @item 
24486 If you have the Microsoft import library (.lib), it is possible to get
24487 the right symbols by using Microsoft @cite{dumpbin} tool (see the
24488 corresponding Microsoft documentation for further details).
24490 @example
24491 $ dumpbin /exports api.lib
24492 @end example
24494 @item 
24495 If you have a message about a missing symbol at link time the compiler
24496 tells you what symbol is expected. You just have to go back to the
24497 definition file and add the right suffix.
24498 @end itemize
24499 @end quotation
24500 @anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{1fd}
24501 @subsubheading GNAT-Style Import Library
24504 To create a static import library from @code{API.dll} with the GNAT tools
24505 you should create the .def file, then use @cite{gnatdll} tool
24506 (see @ref{1fe,,Using gnatdll}) as follows:
24508 @quotation
24510 @example
24511 $ gnatdll -e API.def -d API.dll
24512 @end example
24514 @cite{gnatdll} takes as input a definition file @code{API.def} and the
24515 name of the DLL containing the services listed in the definition file
24516 @code{API.dll}. The name of the static import library generated is
24517 computed from the name of the definition file as follows: if the
24518 definition file name is @cite{xyz`}.def`, the import library name will
24519 be @cite{lib`@w{`}xyz`}.a`. Note that in the previous example option
24520 @emph{-e} could have been removed because the name of the definition
24521 file (before the '@cite{.def}' suffix) is the same as the name of the
24522 DLL (@ref{1fe,,Using gnatdll} for more information about @cite{gnatdll}).
24523 @end quotation
24524 @anchor{gnat_ugn/platform_specific_information msvs-style-import-library}@anchor{1ff}
24525 @subsubheading Microsoft-Style Import Library
24528 A Microsoft import library is needed only if you plan to make an
24529 Ada DLL available to applications developed with Microsoft
24530 tools (@ref{1e6,,Mixed-Language Programming on Windows}).
24532 To create a Microsoft-style import library for @code{API.dll} you
24533 should create the .def file, then build the actual import library using
24534 Microsoft's @cite{lib} utility:
24536 @quotation
24538 @example
24539 $ lib -machine:IX86 -def:API.def -out:API.lib
24540 @end example
24542 If you use the above command the definition file @code{API.def} must
24543 contain a line giving the name of the DLL:
24545 @example
24546 LIBRARY      "API"
24547 @end example
24549 See the Microsoft documentation for further details about the usage of
24550 @cite{lib}.
24551 @end quotation
24553 @node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
24554 @anchor{gnat_ugn/platform_specific_information id24}@anchor{200}@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{1e9}
24555 @subsubsection Building DLLs with GNAT Project files
24558 @geindex DLLs
24559 @geindex building
24561 There is nothing specific to Windows in the build process.
24562 See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24563 chapter of the @emph{GPRbuild User's Guide}.
24565 Due to a system limitation, it is not possible under Windows to create threads
24566 when inside the @cite{DllMain} routine which is used for auto-initialization
24567 of shared libraries, so it is not possible to have library level tasks in SALs.
24569 @node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
24570 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{201}@anchor{gnat_ugn/platform_specific_information id25}@anchor{202}
24571 @subsubsection Building DLLs with GNAT
24574 @geindex DLLs
24575 @geindex building
24577 This section explain how to build DLLs using the GNAT built-in DLL
24578 support. With the following procedure it is straight forward to build
24579 and use DLLs with GNAT.
24582 @itemize *
24584 @item 
24585 Building object files.
24586 The first step is to build all objects files that are to be included
24587 into the DLL. This is done by using the standard @emph{gnatmake} tool.
24589 @item 
24590 Building the DLL.
24591 To build the DLL you must use @emph{gcc}'s @emph{-shared} and
24592 @emph{-shared-libgcc} options. It is quite simple to use this method:
24594 @example
24595 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
24596 @end example
24598 It is important to note that in this case all symbols found in the
24599 object files are automatically exported. It is possible to restrict
24600 the set of symbols to export by passing to @emph{gcc} a definition
24601 file (see @ref{1f6,,The Definition File}).
24602 For example:
24604 @example
24605 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
24606 @end example
24608 If you use a definition file you must export the elaboration procedures
24609 for every package that required one. Elaboration procedures are named
24610 using the package name followed by "_E".
24612 @item 
24613 Preparing DLL to be used.
24614 For the DLL to be used by client programs the bodies must be hidden
24615 from it and the .ali set with read-only attribute. This is very important
24616 otherwise GNAT will recompile all packages and will not actually use
24617 the code in the DLL. For example:
24619 @example
24620 $ mkdir apilib
24621 $ copy *.ads *.ali api.dll apilib
24622 $ attrib +R apilib\\*.ali
24623 @end example
24624 @end itemize
24626 At this point it is possible to use the DLL by directly linking
24627 against it. Note that you must use the GNAT shared runtime when using
24628 GNAT shared libraries. This is achieved by using @emph{-shared} binder's
24629 option.
24631 @quotation
24633 @example
24634 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
24635 @end example
24636 @end quotation
24638 @node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
24639 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{203}@anchor{gnat_ugn/platform_specific_information id26}@anchor{204}
24640 @subsubsection Building DLLs with gnatdll
24643 @geindex DLLs
24644 @geindex building
24646 Note that it is preferred to use GNAT Project files
24647 (@ref{1e9,,Building DLLs with GNAT Project files}) or the built-in GNAT
24648 DLL support (@ref{201,,Building DLLs with GNAT}) or to build DLLs.
24650 This section explains how to build DLLs containing Ada code using
24651 @cite{gnatdll}. These DLLs will be referred to as Ada DLLs in the
24652 remainder of this section.
24654 The steps required to build an Ada DLL that is to be used by Ada as well as
24655 non-Ada applications are as follows:
24658 @itemize *
24660 @item 
24661 You need to mark each Ada @emph{entity} exported by the DLL with a @cite{C} or
24662 @cite{Stdcall} calling convention to avoid any Ada name mangling for the
24663 entities exported by the DLL
24664 (see @ref{205,,Exporting Ada Entities}). You can
24665 skip this step if you plan to use the Ada DLL only from Ada applications.
24667 @item 
24668 Your Ada code must export an initialization routine which calls the routine
24669 @cite{adainit} generated by @emph{gnatbind} to perform the elaboration of
24670 the Ada code in the DLL (@ref{206,,Ada DLLs and Elaboration}). The initialization
24671 routine exported by the Ada DLL must be invoked by the clients of the DLL
24672 to initialize the DLL.
24674 @item 
24675 When useful, the DLL should also export a finalization routine which calls
24676 routine @cite{adafinal} generated by @emph{gnatbind} to perform the
24677 finalization of the Ada code in the DLL (@ref{207,,Ada DLLs and Finalization}).
24678 The finalization routine exported by the Ada DLL must be invoked by the
24679 clients of the DLL when the DLL services are no further needed.
24681 @item 
24682 You must provide a spec for the services exported by the Ada DLL in each
24683 of the programming languages to which you plan to make the DLL available.
24685 @item 
24686 You must provide a definition file listing the exported entities
24687 (@ref{1f6,,The Definition File}).
24689 @item 
24690 Finally you must use @cite{gnatdll} to produce the DLL and the import
24691 library (@ref{1fe,,Using gnatdll}).
24692 @end itemize
24694 Note that a relocatable DLL stripped using the @cite{strip}
24695 binutils tool will not be relocatable anymore. To build a DLL without
24696 debug information pass @cite{-largs -s} to @cite{gnatdll}. This
24697 restriction does not apply to a DLL built using a Library Project.
24698 See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24699 chapter of the @emph{GPRbuild User's Guide}.
24701 @c Limitations_When_Using_Ada_DLLs_from Ada:
24703 @menu
24704 * Limitations When Using Ada DLLs from Ada:: 
24705 * Exporting Ada Entities:: 
24706 * Ada DLLs and Elaboration:: 
24708 @end menu
24710 @node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
24711 @anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{208}
24712 @subsubsection Limitations When Using Ada DLLs from Ada
24715 When using Ada DLLs from Ada applications there is a limitation users
24716 should be aware of. Because on Windows the GNAT run time is not in a DLL of
24717 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
24718 each Ada DLL includes the services of the GNAT run time that are necessary
24719 to the Ada code inside the DLL. As a result, when an Ada program uses an
24720 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
24721 one in the main program.
24723 It is therefore not possible to exchange GNAT run-time objects between the
24724 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
24725 handles (e.g., @cite{Text_IO.File_Type}), tasks types, protected objects
24726 types, etc.
24728 It is completely safe to exchange plain elementary, array or record types,
24729 Windows object handles, etc.
24731 @node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
24732 @anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{205}@anchor{gnat_ugn/platform_specific_information id27}@anchor{209}
24733 @subsubsection Exporting Ada Entities
24736 @geindex Export table
24738 Building a DLL is a way to encapsulate a set of services usable from any
24739 application. As a result, the Ada entities exported by a DLL should be
24740 exported with the @cite{C} or @cite{Stdcall} calling conventions to avoid
24741 any Ada name mangling. As an example here is an Ada package
24742 @cite{API}, spec and body, exporting two procedures, a function, and a
24743 variable:
24745 @quotation
24747 @example
24748 with Interfaces.C; use Interfaces;
24749 package API is
24750    Count : C.int := 0;
24751    function Factorial (Val : C.int) return C.int;
24753    procedure Initialize_API;
24754    procedure Finalize_API;
24755    --  Initialization & Finalization routines. More in the next section.
24756 private
24757    pragma Export (C, Initialize_API);
24758    pragma Export (C, Finalize_API);
24759    pragma Export (C, Count);
24760    pragma Export (C, Factorial);
24761 end API;
24762 @end example
24764 @example
24765 package body API is
24766    function Factorial (Val : C.int) return C.int is
24767       Fact : C.int := 1;
24768    begin
24769       Count := Count + 1;
24770       for K in 1 .. Val loop
24771          Fact := Fact * K;
24772       end loop;
24773       return Fact;
24774    end Factorial;
24776    procedure Initialize_API is
24777       procedure Adainit;
24778       pragma Import (C, Adainit);
24779    begin
24780       Adainit;
24781    end Initialize_API;
24783    procedure Finalize_API is
24784       procedure Adafinal;
24785       pragma Import (C, Adafinal);
24786    begin
24787       Adafinal;
24788    end Finalize_API;
24789 end API;
24790 @end example
24791 @end quotation
24793 If the Ada DLL you are building will only be used by Ada applications
24794 you do not have to export Ada entities with a @cite{C} or @cite{Stdcall}
24795 convention. As an example, the previous package could be written as
24796 follows:
24798 @quotation
24800 @example
24801 package API is
24802    Count : Integer := 0;
24803    function Factorial (Val : Integer) return Integer;
24805    procedure Initialize_API;
24806    procedure Finalize_API;
24807    --  Initialization and Finalization routines.
24808 end API;
24809 @end example
24811 @example
24812 package body API is
24813    function Factorial (Val : Integer) return Integer is
24814       Fact : Integer := 1;
24815    begin
24816       Count := Count + 1;
24817       for K in 1 .. Val loop
24818          Fact := Fact * K;
24819       end loop;
24820       return Fact;
24821    end Factorial;
24823    ...
24824    --  The remainder of this package body is unchanged.
24825 end API;
24826 @end example
24827 @end quotation
24829 Note that if you do not export the Ada entities with a @cite{C} or
24830 @cite{Stdcall} convention you will have to provide the mangled Ada names
24831 in the definition file of the Ada DLL
24832 (@ref{20a,,Creating the Definition File}).
24834 @node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
24835 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{206}@anchor{gnat_ugn/platform_specific_information id28}@anchor{20b}
24836 @subsubsection Ada DLLs and Elaboration
24839 @geindex DLLs and elaboration
24841 The DLL that you are building contains your Ada code as well as all the
24842 routines in the Ada library that are needed by it. The first thing a
24843 user of your DLL must do is elaborate the Ada code
24844 (@ref{f,,Elaboration Order Handling in GNAT}).
24846 To achieve this you must export an initialization routine
24847 (@cite{Initialize_API} in the previous example), which must be invoked
24848 before using any of the DLL services. This elaboration routine must call
24849 the Ada elaboration routine @cite{adainit} generated by the GNAT binder
24850 (@ref{b4,,Binding with Non-Ada Main Programs}). See the body of
24851 @cite{Initialize_Api} for an example. Note that the GNAT binder is
24852 automatically invoked during the DLL build process by the @cite{gnatdll}
24853 tool (@ref{1fe,,Using gnatdll}).
24855 When a DLL is loaded, Windows systematically invokes a routine called
24856 @cite{DllMain}. It would therefore be possible to call @cite{adainit}
24857 directly from @cite{DllMain} without having to provide an explicit
24858 initialization routine. Unfortunately, it is not possible to call
24859 @cite{adainit} from the @cite{DllMain} if your program has library level
24860 tasks because access to the @cite{DllMain} entry point is serialized by
24861 the system (that is, only a single thread can execute 'through' it at a
24862 time), which means that the GNAT run time will deadlock waiting for the
24863 newly created task to complete its initialization.
24865 @node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
24866 @anchor{gnat_ugn/platform_specific_information id29}@anchor{20c}@anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{207}
24867 @subsubsection Ada DLLs and Finalization
24870 @geindex DLLs and finalization
24872 When the services of an Ada DLL are no longer needed, the client code should
24873 invoke the DLL finalization routine, if available. The DLL finalization
24874 routine is in charge of releasing all resources acquired by the DLL. In the
24875 case of the Ada code contained in the DLL, this is achieved by calling
24876 routine @cite{adafinal} generated by the GNAT binder
24877 (@ref{b4,,Binding with Non-Ada Main Programs}).
24878 See the body of @cite{Finalize_Api} for an
24879 example. As already pointed out the GNAT binder is automatically invoked
24880 during the DLL build process by the @cite{gnatdll} tool
24881 (@ref{1fe,,Using gnatdll}).
24883 @node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
24884 @anchor{gnat_ugn/platform_specific_information id30}@anchor{20d}@anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{20e}
24885 @subsubsection Creating a Spec for Ada DLLs
24888 To use the services exported by the Ada DLL from another programming
24889 language (e.g., C), you have to translate the specs of the exported Ada
24890 entities in that language. For instance in the case of @cite{API.dll},
24891 the corresponding C header file could look like:
24893 @quotation
24895 @example
24896 extern int *_imp__count;
24897 #define count (*_imp__count)
24898 int factorial (int);
24899 @end example
24900 @end quotation
24902 It is important to understand that when building an Ada DLL to be used by
24903 other Ada applications, you need two different specs for the packages
24904 contained in the DLL: one for building the DLL and the other for using
24905 the DLL. This is because the @cite{DLL} calling convention is needed to
24906 use a variable defined in a DLL, but when building the DLL, the variable
24907 must have either the @cite{Ada} or @cite{C} calling convention. As an
24908 example consider a DLL comprising the following package @cite{API}:
24910 @quotation
24912 @example
24913 package API is
24914    Count : Integer := 0;
24915    ...
24916    --  Remainder of the package omitted.
24917 end API;
24918 @end example
24919 @end quotation
24921 After producing a DLL containing package @cite{API}, the spec that
24922 must be used to import @cite{API.Count} from Ada code outside of the
24923 DLL is:
24925 @quotation
24927 @example
24928 package API is
24929    Count : Integer;
24930    pragma Import (DLL, Count);
24931 end API;
24932 @end example
24933 @end quotation
24935 @menu
24936 * Creating the Definition File:: 
24937 * Using gnatdll:: 
24939 @end menu
24941 @node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
24942 @anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{20a}@anchor{gnat_ugn/platform_specific_information id31}@anchor{20f}
24943 @subsubsection Creating the Definition File
24946 The definition file is the last file needed to build the DLL. It lists
24947 the exported symbols. As an example, the definition file for a DLL
24948 containing only package @cite{API} (where all the entities are exported
24949 with a @cite{C} calling convention) is:
24951 @quotation
24953 @example
24954 EXPORTS
24955     count
24956     factorial
24957     finalize_api
24958     initialize_api
24959 @end example
24960 @end quotation
24962 If the @cite{C} calling convention is missing from package @cite{API},
24963 then the definition file contains the mangled Ada names of the above
24964 entities, which in this case are:
24966 @quotation
24968 @example
24969 EXPORTS
24970     api__count
24971     api__factorial
24972     api__finalize_api
24973     api__initialize_api
24974 @end example
24975 @end quotation
24977 @node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
24978 @anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{1fe}@anchor{gnat_ugn/platform_specific_information id32}@anchor{210}
24979 @subsubsection Using @cite{gnatdll}
24982 @geindex gnatdll
24984 @cite{gnatdll} is a tool to automate the DLL build process once all the Ada
24985 and non-Ada sources that make up your DLL have been compiled.
24986 @cite{gnatdll} is actually in charge of two distinct tasks: build the
24987 static import library for the DLL and the actual DLL. The form of the
24988 @cite{gnatdll} command is
24990 @quotation
24992 @example
24993 $ gnatdll [`switches`] `list-of-files` [-largs `opts`]
24994 @end example
24995 @end quotation
24997 where @cite{list-of-files} is a list of ALI and object files. The object
24998 file list must be the exact list of objects corresponding to the non-Ada
24999 sources whose services are to be included in the DLL. The ALI file list
25000 must be the exact list of ALI files for the corresponding Ada sources
25001 whose services are to be included in the DLL. If @cite{list-of-files} is
25002 missing, only the static import library is generated.
25004 You may specify any of the following switches to @cite{gnatdll}:
25006 @quotation
25008 @geindex -a (gnatdll)
25009 @end quotation
25012 @table @asis
25014 @item @code{-a[@emph{address}]}
25016 Build a non-relocatable DLL at @cite{address}. If @cite{address} is not
25017 specified the default address @cite{0x11000000} will be used. By default,
25018 when this switch is missing, @cite{gnatdll} builds relocatable DLL. We
25019 advise the reader to build relocatable DLL.
25021 @geindex -b (gnatdll)
25023 @item @code{-b @emph{address}}
25025 Set the relocatable DLL base address. By default the address is
25026 @cite{0x11000000}.
25028 @geindex -bargs (gnatdll)
25030 @item @code{-bargs @emph{opts}}
25032 Binder options. Pass @cite{opts} to the binder.
25034 @geindex -d (gnatdll)
25036 @item @code{-d @emph{dllfile}}
25038 @cite{dllfile} is the name of the DLL. This switch must be present for
25039 @cite{gnatdll} to do anything. The name of the generated import library is
25040 obtained algorithmically from @cite{dllfile} as shown in the following
25041 example: if @cite{dllfile} is @cite{xyz.dll}, the import library name is
25042 @cite{libxyz.dll.a}. The name of the definition file to use (if not specified
25043 by option @emph{-e}) is obtained algorithmically from @cite{dllfile}
25044 as shown in the following example:
25045 if @cite{dllfile} is @cite{xyz.dll}, the definition
25046 file used is @cite{xyz.def}.
25048 @geindex -e (gnatdll)
25050 @item @code{-e @emph{deffile}}
25052 @cite{deffile} is the name of the definition file.
25054 @geindex -g (gnatdll)
25056 @item @code{-g}
25058 Generate debugging information. This information is stored in the object
25059 file and copied from there to the final DLL file by the linker,
25060 where it can be read by the debugger. You must use the
25061 @emph{-g} switch if you plan on using the debugger or the symbolic
25062 stack traceback.
25064 @geindex -h (gnatdll)
25066 @item @code{-h}
25068 Help mode. Displays @cite{gnatdll} switch usage information.
25070 @geindex -I (gnatdll)
25072 @item @code{-I@emph{dir}}
25074 Direct @cite{gnatdll} to search the @cite{dir} directory for source and
25075 object files needed to build the DLL.
25076 (@ref{89,,Search Paths and the Run-Time Library (RTL)}).
25078 @geindex -k (gnatdll)
25080 @item @code{-k}
25082 Removes the @code{@@@emph{nn}} suffix from the import library's exported
25083 names, but keeps them for the link names. You must specify this
25084 option if you want to use a @cite{Stdcall} function in a DLL for which
25085 the @code{@@@emph{nn}} suffix has been removed. This is the case for most
25086 of the Windows NT DLL for example. This option has no effect when
25087 @emph{-n} option is specified.
25089 @geindex -l (gnatdll)
25091 @item @code{-l @emph{file}}
25093 The list of ALI and object files used to build the DLL are listed in
25094 @cite{file}, instead of being given in the command line. Each line in
25095 @cite{file} contains the name of an ALI or object file.
25097 @geindex -n (gnatdll)
25099 @item @code{-n}
25101 No Import. Do not create the import library.
25103 @geindex -q (gnatdll)
25105 @item @code{-q}
25107 Quiet mode. Do not display unnecessary messages.
25109 @geindex -v (gnatdll)
25111 @item @code{-v}
25113 Verbose mode. Display extra information.
25115 @geindex -largs (gnatdll)
25117 @item @code{-largs @emph{opts}}
25119 Linker options. Pass @cite{opts} to the linker.
25120 @end table
25122 @subsubheading @cite{gnatdll} Example
25125 As an example the command to build a relocatable DLL from @code{api.adb}
25126 once @code{api.adb} has been compiled and @code{api.def} created is
25128 @quotation
25130 @example
25131 $ gnatdll -d api.dll api.ali
25132 @end example
25133 @end quotation
25135 The above command creates two files: @code{libapi.dll.a} (the import
25136 library) and @code{api.dll} (the actual DLL). If you want to create
25137 only the DLL, just type:
25139 @quotation
25141 @example
25142 $ gnatdll -d api.dll -n api.ali
25143 @end example
25144 @end quotation
25146 Alternatively if you want to create just the import library, type:
25148 @quotation
25150 @example
25151 $ gnatdll -d api.dll
25152 @end example
25153 @end quotation
25155 @subsubheading @cite{gnatdll} behind the Scenes
25158 This section details the steps involved in creating a DLL. @cite{gnatdll}
25159 does these steps for you. Unless you are interested in understanding what
25160 goes on behind the scenes, you should skip this section.
25162 We use the previous example of a DLL containing the Ada package @cite{API},
25163 to illustrate the steps necessary to build a DLL. The starting point is a
25164 set of objects that will make up the DLL and the corresponding ALI
25165 files. In the case of this example this means that @code{api.o} and
25166 @code{api.ali} are available. To build a relocatable DLL, @cite{gnatdll} does
25167 the following:
25170 @itemize *
25172 @item 
25173 @cite{gnatdll} builds the base file (@code{api.base}). A base file gives
25174 the information necessary to generate relocation information for the
25175 DLL.
25177 @example
25178 $ gnatbind -n api
25179 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
25180 @end example
25182 In addition to the base file, the @emph{gnatlink} command generates an
25183 output file @code{api.jnk} which can be discarded. The @emph{-mdll} switch
25184 asks @emph{gnatlink} to generate the routines @cite{DllMain} and
25185 @cite{DllMainCRTStartup} that are called by the Windows loader when the DLL
25186 is loaded into memory.
25188 @item 
25189 @cite{gnatdll} uses @cite{dlltool} (see @ref{211,,Using dlltool}) to build the
25190 export table (@code{api.exp}). The export table contains the relocation
25191 information in a form which can be used during the final link to ensure
25192 that the Windows loader is able to place the DLL anywhere in memory.
25194 @example
25195 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
25196           --output-exp api.exp
25197 @end example
25199 @item 
25200 @cite{gnatdll} builds the base file using the new export table. Note that
25201 @emph{gnatbind} must be called once again since the binder generated file
25202 has been deleted during the previous call to @emph{gnatlink}.
25204 @example
25205 $ gnatbind -n api
25206 $ gnatlink api -o api.jnk api.exp -mdll
25207       -Wl,--base-file,api.base
25208 @end example
25210 @item 
25211 @cite{gnatdll} builds the new export table using the new base file and
25212 generates the DLL import library @code{libAPI.dll.a}.
25214 @example
25215 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
25216           --output-exp api.exp --output-lib libAPI.a
25217 @end example
25219 @item 
25220 Finally @cite{gnatdll} builds the relocatable DLL using the final export
25221 table.
25223 @example
25224 $ gnatbind -n api
25225 $ gnatlink api api.exp -o api.dll -mdll
25226 @end example
25227 @end itemize
25228 @anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{211}
25229 @subsubheading Using @cite{dlltool}
25232 @cite{dlltool} is the low-level tool used by @cite{gnatdll} to build
25233 DLLs and static import libraries. This section summarizes the most
25234 common @cite{dlltool} switches. The form of the @cite{dlltool} command
25237 @quotation
25239 @example
25240 $ dlltool [`switches`]
25241 @end example
25242 @end quotation
25244 @cite{dlltool} switches include:
25246 @geindex --base-file (dlltool)
25249 @table @asis
25251 @item @code{--base-file @emph{basefile}}
25253 Read the base file @cite{basefile} generated by the linker. This switch
25254 is used to create a relocatable DLL.
25255 @end table
25257 @geindex --def (dlltool)
25260 @table @asis
25262 @item @code{--def @emph{deffile}}
25264 Read the definition file.
25265 @end table
25267 @geindex --dllname (dlltool)
25270 @table @asis
25272 @item @code{--dllname @emph{name}}
25274 Gives the name of the DLL. This switch is used to embed the name of the
25275 DLL in the static import library generated by @cite{dlltool} with switch
25276 @emph{--output-lib}.
25277 @end table
25279 @geindex -k (dlltool)
25282 @table @asis
25284 @item @code{-k}
25286 Kill @code{@@@emph{nn}} from exported names
25287 (@ref{1ea,,Windows Calling Conventions}
25288 for a discussion about @cite{Stdcall}-style symbols.
25289 @end table
25291 @geindex --help (dlltool)
25294 @table @asis
25296 @item @code{--help}
25298 Prints the @cite{dlltool} switches with a concise description.
25299 @end table
25301 @geindex --output-exp (dlltool)
25304 @table @asis
25306 @item @code{--output-exp @emph{exportfile}}
25308 Generate an export file @cite{exportfile}. The export file contains the
25309 export table (list of symbols in the DLL) and is used to create the DLL.
25310 @end table
25312 @geindex --output-lib (dlltool)
25315 @table @asis
25317 @item @code{--output-lib @emph{libfile}}
25319 Generate a static import library @cite{libfile}.
25320 @end table
25322 @geindex -v (dlltool)
25325 @table @asis
25327 @item @code{-v}
25329 Verbose mode.
25330 @end table
25332 @geindex --as (dlltool)
25335 @table @asis
25337 @item @code{--as @emph{assembler-name}}
25339 Use @cite{assembler-name} as the assembler. The default is @cite{as}.
25340 @end table
25342 @node GNAT and Windows Resources,Using GNAT DLLs from Microsoft Visual Studio Applications,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
25343 @anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{212}@anchor{gnat_ugn/platform_specific_information id33}@anchor{213}
25344 @subsubsection GNAT and Windows Resources
25347 @geindex Resources
25348 @geindex windows
25350 Resources are an easy way to add Windows specific objects to your
25351 application. The objects that can be added as resources include:
25354 @itemize *
25356 @item 
25357 menus
25359 @item 
25360 accelerators
25362 @item 
25363 dialog boxes
25365 @item 
25366 string tables
25368 @item 
25369 bitmaps
25371 @item 
25372 cursors
25374 @item 
25375 icons
25377 @item 
25378 fonts
25380 @item 
25381 version information
25382 @end itemize
25384 For example, a version information resource can be defined as follow and
25385 embedded into an executable or DLL:
25387 A version information resource can be used to embed information into an
25388 executable or a DLL. These information can be viewed using the file properties
25389 from the Windows Explorer. Here is an example of a version information
25390 resource:
25392 @quotation
25394 @example
25395 1 VERSIONINFO
25396 FILEVERSION     1,0,0,0
25397 PRODUCTVERSION  1,0,0,0
25398 BEGIN
25399   BLOCK "StringFileInfo"
25400   BEGIN
25401     BLOCK "080904E4"
25402     BEGIN
25403       VALUE "CompanyName", "My Company Name"
25404       VALUE "FileDescription", "My application"
25405       VALUE "FileVersion", "1.0"
25406       VALUE "InternalName", "my_app"
25407       VALUE "LegalCopyright", "My Name"
25408       VALUE "OriginalFilename", "my_app.exe"
25409       VALUE "ProductName", "My App"
25410       VALUE "ProductVersion", "1.0"
25411     END
25412   END
25414   BLOCK "VarFileInfo"
25415   BEGIN
25416     VALUE "Translation", 0x809, 1252
25417   END
25419 @end example
25420 @end quotation
25422 The value @cite{0809} (langID) is for the U.K English language and
25423 @cite{04E4} (charsetID), which is equal to @cite{1252} decimal, for
25424 multilingual.
25426 This section explains how to build, compile and use resources. Note that this
25427 section does not cover all resource objects, for a complete description see
25428 the corresponding Microsoft documentation.
25430 @menu
25431 * Building Resources:: 
25432 * Compiling Resources:: 
25433 * Using Resources:: 
25435 @end menu
25437 @node Building Resources,Compiling Resources,,GNAT and Windows Resources
25438 @anchor{gnat_ugn/platform_specific_information building-resources}@anchor{214}@anchor{gnat_ugn/platform_specific_information id34}@anchor{215}
25439 @subsubsection Building Resources
25442 @geindex Resources
25443 @geindex building
25445 A resource file is an ASCII file. By convention resource files have an
25446 @code{.rc} extension.
25447 The easiest way to build a resource file is to use Microsoft tools
25448 such as @cite{imagedit.exe} to build bitmaps, icons and cursors and
25449 @cite{dlgedit.exe} to build dialogs.
25450 It is always possible to build an @code{.rc} file yourself by writing a
25451 resource script.
25453 It is not our objective to explain how to write a resource file. A
25454 complete description of the resource script language can be found in the
25455 Microsoft documentation.
25457 @node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
25458 @anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{216}@anchor{gnat_ugn/platform_specific_information id35}@anchor{217}
25459 @subsubsection Compiling Resources
25462 @geindex rc
25464 @geindex windres
25466 @geindex Resources
25467 @geindex compiling
25469 This section describes how to build a GNAT-compatible (COFF) object file
25470 containing the resources. This is done using the Resource Compiler
25471 @cite{windres} as follows:
25473 @quotation
25475 @example
25476 $ windres -i myres.rc -o myres.o
25477 @end example
25478 @end quotation
25480 By default @cite{windres} will run @emph{gcc} to preprocess the @code{.rc}
25481 file. You can specify an alternate preprocessor (usually named
25482 @code{cpp.exe}) using the @cite{windres} @emph{--preprocessor}
25483 parameter. A list of all possible options may be obtained by entering
25484 the command @cite{windres} @emph{--help}.
25486 It is also possible to use the Microsoft resource compiler @cite{rc.exe}
25487 to produce a @code{.res} file (binary resource file). See the
25488 corresponding Microsoft documentation for further details. In this case
25489 you need to use @cite{windres} to translate the @code{.res} file to a
25490 GNAT-compatible object file as follows:
25492 @quotation
25494 @example
25495 $ windres -i myres.res -o myres.o
25496 @end example
25497 @end quotation
25499 @node Using Resources,,Compiling Resources,GNAT and Windows Resources
25500 @anchor{gnat_ugn/platform_specific_information id36}@anchor{218}@anchor{gnat_ugn/platform_specific_information using-resources}@anchor{219}
25501 @subsubsection Using Resources
25504 @geindex Resources
25505 @geindex using
25507 To include the resource file in your program just add the
25508 GNAT-compatible object file for the resource(s) to the linker
25509 arguments. With @emph{gnatmake} this is done by using the @emph{-largs}
25510 option:
25512 @quotation
25514 @example
25515 $ gnatmake myprog -largs myres.o
25516 @end example
25517 @end quotation
25519 @node Using GNAT DLLs from Microsoft Visual Studio Applications,Debugging a DLL,GNAT and Windows Resources,Mixed-Language Programming on Windows
25520 @anchor{gnat_ugn/platform_specific_information using-gnat-dll-from-msvs}@anchor{21a}@anchor{gnat_ugn/platform_specific_information using-gnat-dlls-from-microsoft-visual-studio-applications}@anchor{21b}
25521 @subsubsection Using GNAT DLLs from Microsoft Visual Studio Applications
25524 @geindex Microsoft Visual Studio
25525 @geindex use with GNAT DLLs
25527 This section describes a common case of mixed GNAT/Microsoft Visual Studio
25528 application development, where the main program is developed using MSVS, and
25529 is linked with a DLL developed using GNAT. Such a mixed application should
25530 be developed following the general guidelines outlined above; below is the
25531 cookbook-style sequence of steps to follow:
25534 @enumerate 
25536 @item 
25537 First develop and build the GNAT shared library using a library project
25538 (let's assume the project is @cite{mylib.gpr}, producing the library @cite{libmylib.dll}):
25539 @end enumerate
25541 @quotation
25543 @example
25544 $ gprbuild -p mylib.gpr
25545 @end example
25546 @end quotation
25549 @enumerate 2
25551 @item 
25552 Produce a .def file for the symbols you need to interface with, either by
25553 hand or automatically with possibly some manual adjustments
25554 (see @ref{1fc,,Creating Definition File Automatically}):
25555 @end enumerate
25557 @quotation
25559 @example
25560 $ dlltool libmylib.dll -z libmylib.def --export-all-symbols
25561 @end example
25562 @end quotation
25565 @enumerate 3
25567 @item 
25568 Make sure that MSVS command-line tools are accessible on the path.
25570 @item 
25571 Create the Microsoft-style import library (see @ref{1ff,,MSVS-Style Import Library}):
25572 @end enumerate
25574 @quotation
25576 @example
25577 $ lib -machine:IX86 -def:libmylib.def -out:libmylib.lib
25578 @end example
25579 @end quotation
25581 If you are using a 64-bit toolchain, the above becomes...
25583 @quotation
25585 @example
25586 $ lib -machine:X64 -def:libmylib.def -out:libmylib.lib
25587 @end example
25588 @end quotation
25591 @enumerate 5
25593 @item 
25594 Build the C main
25595 @end enumerate
25597 @quotation
25599 @example
25600 $ cl /O2 /MD main.c libmylib.lib
25601 @end example
25602 @end quotation
25605 @enumerate 6
25607 @item 
25608 Before running the executable, make sure you have set the PATH to the DLL,
25609 or copy the DLL into into the directory containing the .exe.
25610 @end enumerate
25612 @node Debugging a DLL,Setting Stack Size from gnatlink,Using GNAT DLLs from Microsoft Visual Studio Applications,Mixed-Language Programming on Windows
25613 @anchor{gnat_ugn/platform_specific_information id37}@anchor{21c}@anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{21d}
25614 @subsubsection Debugging a DLL
25617 @geindex DLL debugging
25619 Debugging a DLL is similar to debugging a standard program. But
25620 we have to deal with two different executable parts: the DLL and the
25621 program that uses it. We have the following four possibilities:
25624 @itemize *
25626 @item 
25627 The program and the DLL are built with @cite{GCC/GNAT}.
25629 @item 
25630 The program is built with foreign tools and the DLL is built with
25631 @cite{GCC/GNAT}.
25633 @item 
25634 The program is built with @cite{GCC/GNAT} and the DLL is built with
25635 foreign tools.
25636 @end itemize
25638 In this section we address only cases one and two above.
25639 There is no point in trying to debug
25640 a DLL with @cite{GNU/GDB}, if there is no GDB-compatible debugging
25641 information in it. To do so you must use a debugger compatible with the
25642 tools suite used to build the DLL.
25644 @menu
25645 * Program and DLL Both Built with GCC/GNAT:: 
25646 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
25648 @end menu
25650 @node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
25651 @anchor{gnat_ugn/platform_specific_information program-and-dll-both-built-with-gcc-gnat}@anchor{21e}@anchor{gnat_ugn/platform_specific_information id38}@anchor{21f}
25652 @subsubsection Program and DLL Both Built with GCC/GNAT
25655 This is the simplest case. Both the DLL and the program have @cite{GDB}
25656 compatible debugging information. It is then possible to break anywhere in
25657 the process. Let's suppose here that the main procedure is named
25658 @cite{ada_main} and that in the DLL there is an entry point named
25659 @cite{ada_dll}.
25661 The DLL (@ref{1f5,,Introduction to Dynamic Link Libraries (DLLs)}) and
25662 program must have been built with the debugging information (see GNAT -g
25663 switch). Here are the step-by-step instructions for debugging it:
25666 @itemize *
25668 @item 
25669 Launch @cite{GDB} on the main program.
25671 @example
25672 $ gdb -nw ada_main
25673 @end example
25675 @item 
25676 Start the program and stop at the beginning of the main procedure
25678 @example
25679 (gdb) start
25680 @end example
25682 This step is required to be able to set a breakpoint inside the DLL. As long
25683 as the program is not run, the DLL is not loaded. This has the
25684 consequence that the DLL debugging information is also not loaded, so it is not
25685 possible to set a breakpoint in the DLL.
25687 @item 
25688 Set a breakpoint inside the DLL
25690 @example
25691 (gdb) break ada_dll
25692 (gdb) cont
25693 @end example
25694 @end itemize
25696 At this stage a breakpoint is set inside the DLL. From there on
25697 you can use the standard approach to debug the whole program
25698 (@ref{24,,Running and Debugging Ada Programs}).
25700 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
25701 @anchor{gnat_ugn/platform_specific_information program-built-with-foreign-tools-and-dll-built-with-gcc-gnat}@anchor{220}@anchor{gnat_ugn/platform_specific_information id39}@anchor{221}
25702 @subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
25705 In this case things are slightly more complex because it is not possible to
25706 start the main program and then break at the beginning to load the DLL and the
25707 associated DLL debugging information. It is not possible to break at the
25708 beginning of the program because there is no @cite{GDB} debugging information,
25709 and therefore there is no direct way of getting initial control. This
25710 section addresses this issue by describing some methods that can be used
25711 to break somewhere in the DLL to debug it.
25713 First suppose that the main procedure is named @cite{main} (this is for
25714 example some C code built with Microsoft Visual C) and that there is a
25715 DLL named @cite{test.dll} containing an Ada entry point named
25716 @cite{ada_dll}.
25718 The DLL (see @ref{1f5,,Introduction to Dynamic Link Libraries (DLLs)}) must have
25719 been built with debugging information (see GNAT @cite{-g} option).
25721 @subsubheading Debugging the DLL Directly
25725 @itemize *
25727 @item 
25728 Find out the executable starting address
25730 @example
25731 $ objdump --file-header main.exe
25732 @end example
25734 The starting address is reported on the last line. For example:
25736 @example
25737 main.exe:     file format pei-i386
25738 architecture: i386, flags 0x0000010a:
25739 EXEC_P, HAS_DEBUG, D_PAGED
25740 start address 0x00401010
25741 @end example
25743 @item 
25744 Launch the debugger on the executable.
25746 @example
25747 $ gdb main.exe
25748 @end example
25750 @item 
25751 Set a breakpoint at the starting address, and launch the program.
25753 @example
25754 $ (gdb) break *0x00401010
25755 $ (gdb) run
25756 @end example
25758 The program will stop at the given address.
25760 @item 
25761 Set a breakpoint on a DLL subroutine.
25763 @example
25764 (gdb) break ada_dll.adb:45
25765 @end example
25767 Or if you want to break using a symbol on the DLL, you need first to
25768 select the Ada language (language used by the DLL).
25770 @example
25771 (gdb) set language ada
25772 (gdb) break ada_dll
25773 @end example
25775 @item 
25776 Continue the program.
25778 @example
25779 (gdb) cont
25780 @end example
25782 This will run the program until it reaches the breakpoint that has been
25783 set. From that point you can use the standard way to debug a program
25784 as described in (@ref{24,,Running and Debugging Ada Programs}).
25785 @end itemize
25787 It is also possible to debug the DLL by attaching to a running process.
25789 @subsubheading Attaching to a Running Process
25792 @geindex DLL debugging
25793 @geindex attach to process
25795 With @cite{GDB} it is always possible to debug a running process by
25796 attaching to it. It is possible to debug a DLL this way. The limitation
25797 of this approach is that the DLL must run long enough to perform the
25798 attach operation. It may be useful for instance to insert a time wasting
25799 loop in the code of the DLL to meet this criterion.
25802 @itemize *
25804 @item 
25805 Launch the main program @code{main.exe}.
25807 @example
25808 $ main
25809 @end example
25811 @item 
25812 Use the Windows @emph{Task Manager} to find the process ID. Let's say
25813 that the process PID for @code{main.exe} is 208.
25815 @item 
25816 Launch gdb.
25818 @example
25819 $ gdb
25820 @end example
25822 @item 
25823 Attach to the running process to be debugged.
25825 @example
25826 (gdb) attach 208
25827 @end example
25829 @item 
25830 Load the process debugging information.
25832 @example
25833 (gdb) symbol-file main.exe
25834 @end example
25836 @item 
25837 Break somewhere in the DLL.
25839 @example
25840 (gdb) break ada_dll
25841 @end example
25843 @item 
25844 Continue process execution.
25846 @example
25847 (gdb) cont
25848 @end example
25849 @end itemize
25851 This last step will resume the process execution, and stop at
25852 the breakpoint we have set. From there you can use the standard
25853 approach to debug a program as described in
25854 @ref{24,,Running and Debugging Ada Programs}.
25856 @node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
25857 @anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{134}@anchor{gnat_ugn/platform_specific_information id40}@anchor{222}
25858 @subsubsection Setting Stack Size from @emph{gnatlink}
25861 It is possible to specify the program stack size at link time. On modern
25862 versions of Windows, starting with XP, this is mostly useful to set the size of
25863 the main stack (environment task). The other task stacks are set with pragma
25864 Storage_Size or with the @emph{gnatbind -d} command.
25866 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
25867 reserve size of individual tasks, the link-time stack size applies to all
25868 tasks, and pragma Storage_Size has no effect.
25869 In particular, Stack Overflow checks are made against this
25870 link-time specified size.
25872 This setting can be done with @emph{gnatlink} using either of the following:
25875 @itemize *
25877 @item 
25878 @emph{-Xlinker} linker option
25880 @example
25881 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
25882 @end example
25884 This sets the stack reserve size to 0x10000 bytes and the stack commit
25885 size to 0x1000 bytes.
25887 @item 
25888 @emph{-Wl} linker option
25890 @example
25891 $ gnatlink hello -Wl,--stack=0x1000000
25892 @end example
25894 This sets the stack reserve size to 0x1000000 bytes. Note that with
25895 @emph{-Wl} option it is not possible to set the stack commit size
25896 because the coma is a separator for this option.
25897 @end itemize
25899 @node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
25900 @anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{135}@anchor{gnat_ugn/platform_specific_information id41}@anchor{223}
25901 @subsubsection Setting Heap Size from @emph{gnatlink}
25904 Under Windows systems, it is possible to specify the program heap size from
25905 @emph{gnatlink} using either of the following:
25908 @itemize *
25910 @item 
25911 @emph{-Xlinker} linker option
25913 @example
25914 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
25915 @end example
25917 This sets the heap reserve size to 0x10000 bytes and the heap commit
25918 size to 0x1000 bytes.
25920 @item 
25921 @emph{-Wl} linker option
25923 @example
25924 $ gnatlink hello -Wl,--heap=0x1000000
25925 @end example
25927 This sets the heap reserve size to 0x1000000 bytes. Note that with
25928 @emph{-Wl} option it is not possible to set the heap commit size
25929 because the coma is a separator for this option.
25930 @end itemize
25932 @node Windows Specific Add-Ons,,Mixed-Language Programming on Windows,Microsoft Windows Topics
25933 @anchor{gnat_ugn/platform_specific_information windows-specific-add-ons}@anchor{224}@anchor{gnat_ugn/platform_specific_information win32-specific-addons}@anchor{225}
25934 @subsection Windows Specific Add-Ons
25937 This section describes the Windows specific add-ons.
25939 @menu
25940 * Win32Ada:: 
25941 * wPOSIX:: 
25943 @end menu
25945 @node Win32Ada,wPOSIX,,Windows Specific Add-Ons
25946 @anchor{gnat_ugn/platform_specific_information win32ada}@anchor{226}@anchor{gnat_ugn/platform_specific_information id42}@anchor{227}
25947 @subsubsection Win32Ada
25950 Win32Ada is a binding for the Microsoft Win32 API. This binding can be
25951 easily installed from the provided installer. To use the Win32Ada
25952 binding you need to use a project file, and adding a single with_clause
25953 will give you full access to the Win32Ada binding sources and ensure
25954 that the proper libraries are passed to the linker.
25956 @quotation
25958 @example
25959 with "win32ada";
25960 project P is
25961    for Sources use ...;
25962 end P;
25963 @end example
25964 @end quotation
25966 To build the application you just need to call gprbuild for the
25967 application's project, here p.gpr:
25969 @quotation
25971 @example
25972 gprbuild p.gpr
25973 @end example
25974 @end quotation
25976 @node wPOSIX,,Win32Ada,Windows Specific Add-Ons
25977 @anchor{gnat_ugn/platform_specific_information id43}@anchor{228}@anchor{gnat_ugn/platform_specific_information wposix}@anchor{229}
25978 @subsubsection wPOSIX
25981 wPOSIX is a minimal POSIX binding whose goal is to help with building
25982 cross-platforms applications. This binding is not complete though, as
25983 the Win32 API does not provide the necessary support for all POSIX APIs.
25985 To use the wPOSIX binding you need to use a project file, and adding
25986 a single with_clause will give you full access to the wPOSIX binding
25987 sources and ensure that the proper libraries are passed to the linker.
25989 @quotation
25991 @example
25992 with "wposix";
25993 project P is
25994    for Sources use ...;
25995 end P;
25996 @end example
25997 @end quotation
25999 To build the application you just need to call gprbuild for the
26000 application's project, here p.gpr:
26002 @quotation
26004 @example
26005 gprbuild p.gpr
26006 @end example
26007 @end quotation
26009 @node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
26010 @anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{2d}@anchor{gnat_ugn/platform_specific_information id44}@anchor{22a}
26011 @section Mac OS Topics
26014 @geindex OS X
26016 This section describes topics that are specific to Apple's OS X
26017 platform.
26019 @menu
26020 * Codesigning the Debugger:: 
26022 @end menu
26024 @node Codesigning the Debugger,,,Mac OS Topics
26025 @anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{22b}
26026 @subsection Codesigning the Debugger
26029 The Darwin Kernel requires the debugger to have special permissions
26030 before it is allowed to control other processes. These permissions
26031 are granted by codesigning the GDB executable. Without these
26032 permissions, the debugger will report error messages such as:
26034 @example
26035 Starting program: /x/y/foo
26036 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
26037 (please check gdb is codesigned - see taskgated(8))
26038 @end example
26040 Codesigning requires a certificate.  The following procedure explains
26041 how to create one:
26044 @itemize *
26046 @item 
26047 Start the Keychain Access application (in
26048 /Applications/Utilities/Keychain Access.app)
26050 @item 
26051 Select the Keychain Access -> Certificate Assistant ->
26052 Create a Certificate... menu
26054 @item 
26055 Then:
26058 @itemize *
26060 @item 
26061 Choose a name for the new certificate (this procedure will use
26062 "gdb-cert" as an example)
26064 @item 
26065 Set "Identity Type" to "Self Signed Root"
26067 @item 
26068 Set "Certificate Type" to "Code Signing"
26070 @item 
26071 Activate the "Let me override defaults" option
26072 @end itemize
26074 @item 
26075 Click several times on "Continue" until the "Specify a Location
26076 For The Certificate" screen appears, then set "Keychain" to "System"
26078 @item 
26079 Click on "Continue" until the certificate is created
26081 @item 
26082 Finally, in the view, double-click on the new certificate,
26083 and set "When using this certificate" to "Always Trust"
26085 @item 
26086 Exit the Keychain Access application and restart the computer
26087 (this is unfortunately required)
26088 @end itemize
26090 Once a certificate has been created, the debugger can be codesigned
26091 as follow. In a Terminal, run the following command:
26093 @quotation
26095 @example
26096 $ codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
26097 @end example
26098 @end quotation
26100 where "gdb-cert" should be replaced by the actual certificate
26101 name chosen above, and <gnat_install_prefix> should be replaced by
26102 the location where you installed GNAT.  Also, be sure that users are
26103 in the Unix group @code{_developer}.
26105 @node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
26106 @anchor{gnat_ugn/example_of_binder_output example-of-binder-output-file}@anchor{e}@anchor{gnat_ugn/example_of_binder_output doc}@anchor{22c}@anchor{gnat_ugn/example_of_binder_output id1}@anchor{22d}
26107 @chapter Example of Binder Output File
26110 @geindex Binder output (example)
26112 This Appendix displays the source code for the output file
26113 generated by @emph{gnatbind} for a simple 'Hello World' program.
26114 Comments have been added for clarification purposes.
26116 @example
26117 --  The package is called Ada_Main unless this name is actually used
26118 --  as a unit name in the partition, in which case some other unique
26119 --  name is used.
26121 pragma Ada_95;
26122 with System;
26123 package ada_main is
26124    pragma Warnings (Off);
26126    --  The main program saves the parameters (argument count,
26127    --  argument values, environment pointer) in global variables
26128    --  for later access by other units including
26129    --  Ada.Command_Line.
26131    gnat_argc : Integer;
26132    gnat_argv : System.Address;
26133    gnat_envp : System.Address;
26135    --  The actual variables are stored in a library routine. This
26136    --  is useful for some shared library situations, where there
26137    --  are problems if variables are not in the library.
26139    pragma Import (C, gnat_argc);
26140    pragma Import (C, gnat_argv);
26141    pragma Import (C, gnat_envp);
26143    --  The exit status is similarly an external location
26145    gnat_exit_status : Integer;
26146    pragma Import (C, gnat_exit_status);
26148    GNAT_Version : constant String :=
26149                     "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
26150    pragma Export (C, GNAT_Version, "__gnat_version");
26152    Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
26153    pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
26155    --  This is the generated adainit routine that performs
26156    --  initialization at the start of execution. In the case
26157    --  where Ada is the main program, this main program makes
26158    --  a call to adainit at program startup.
26160    procedure adainit;
26161    pragma Export (C, adainit, "adainit");
26163    --  This is the generated adafinal routine that performs
26164    --  finalization at the end of execution. In the case where
26165    --  Ada is the main program, this main program makes a call
26166    --  to adafinal at program termination.
26168    procedure adafinal;
26169    pragma Export (C, adafinal, "adafinal");
26171    --  This routine is called at the start of execution. It is
26172    --  a dummy routine that is used by the debugger to breakpoint
26173    --  at the start of execution.
26175    --  This is the actual generated main program (it would be
26176    --  suppressed if the no main program switch were used). As
26177    --  required by standard system conventions, this program has
26178    --  the external name main.
26180    function main
26181      (argc : Integer;
26182       argv : System.Address;
26183       envp : System.Address)
26184       return Integer;
26185    pragma Export (C, main, "main");
26187    --  The following set of constants give the version
26188    --  identification values for every unit in the bound
26189    --  partition. This identification is computed from all
26190    --  dependent semantic units, and corresponds to the
26191    --  string that would be returned by use of the
26192    --  Body_Version or Version attributes.
26194    --  The following Export pragmas export the version numbers
26195    --  with symbolic names ending in B (for body) or S
26196    --  (for spec) so that they can be located in a link. The
26197    --  information provided here is sufficient to track down
26198    --  the exact versions of units used in a given build.
26200    type Version_32 is mod 2 ** 32;
26201    u00001 : constant Version_32 := 16#8ad6e54a#;
26202    pragma Export (C, u00001, "helloB");
26203    u00002 : constant Version_32 := 16#fbff4c67#;
26204    pragma Export (C, u00002, "system__standard_libraryB");
26205    u00003 : constant Version_32 := 16#1ec6fd90#;
26206    pragma Export (C, u00003, "system__standard_libraryS");
26207    u00004 : constant Version_32 := 16#3ffc8e18#;
26208    pragma Export (C, u00004, "adaS");
26209    u00005 : constant Version_32 := 16#28f088c2#;
26210    pragma Export (C, u00005, "ada__text_ioB");
26211    u00006 : constant Version_32 := 16#f372c8ac#;
26212    pragma Export (C, u00006, "ada__text_ioS");
26213    u00007 : constant Version_32 := 16#2c143749#;
26214    pragma Export (C, u00007, "ada__exceptionsB");
26215    u00008 : constant Version_32 := 16#f4f0cce8#;
26216    pragma Export (C, u00008, "ada__exceptionsS");
26217    u00009 : constant Version_32 := 16#a46739c0#;
26218    pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
26219    u00010 : constant Version_32 := 16#3aac8c92#;
26220    pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
26221    u00011 : constant Version_32 := 16#1d274481#;
26222    pragma Export (C, u00011, "systemS");
26223    u00012 : constant Version_32 := 16#a207fefe#;
26224    pragma Export (C, u00012, "system__soft_linksB");
26225    u00013 : constant Version_32 := 16#467d9556#;
26226    pragma Export (C, u00013, "system__soft_linksS");
26227    u00014 : constant Version_32 := 16#b01dad17#;
26228    pragma Export (C, u00014, "system__parametersB");
26229    u00015 : constant Version_32 := 16#630d49fe#;
26230    pragma Export (C, u00015, "system__parametersS");
26231    u00016 : constant Version_32 := 16#b19b6653#;
26232    pragma Export (C, u00016, "system__secondary_stackB");
26233    u00017 : constant Version_32 := 16#b6468be8#;
26234    pragma Export (C, u00017, "system__secondary_stackS");
26235    u00018 : constant Version_32 := 16#39a03df9#;
26236    pragma Export (C, u00018, "system__storage_elementsB");
26237    u00019 : constant Version_32 := 16#30e40e85#;
26238    pragma Export (C, u00019, "system__storage_elementsS");
26239    u00020 : constant Version_32 := 16#41837d1e#;
26240    pragma Export (C, u00020, "system__stack_checkingB");
26241    u00021 : constant Version_32 := 16#93982f69#;
26242    pragma Export (C, u00021, "system__stack_checkingS");
26243    u00022 : constant Version_32 := 16#393398c1#;
26244    pragma Export (C, u00022, "system__exception_tableB");
26245    u00023 : constant Version_32 := 16#b33e2294#;
26246    pragma Export (C, u00023, "system__exception_tableS");
26247    u00024 : constant Version_32 := 16#ce4af020#;
26248    pragma Export (C, u00024, "system__exceptionsB");
26249    u00025 : constant Version_32 := 16#75442977#;
26250    pragma Export (C, u00025, "system__exceptionsS");
26251    u00026 : constant Version_32 := 16#37d758f1#;
26252    pragma Export (C, u00026, "system__exceptions__machineS");
26253    u00027 : constant Version_32 := 16#b895431d#;
26254    pragma Export (C, u00027, "system__exceptions_debugB");
26255    u00028 : constant Version_32 := 16#aec55d3f#;
26256    pragma Export (C, u00028, "system__exceptions_debugS");
26257    u00029 : constant Version_32 := 16#570325c8#;
26258    pragma Export (C, u00029, "system__img_intB");
26259    u00030 : constant Version_32 := 16#1ffca443#;
26260    pragma Export (C, u00030, "system__img_intS");
26261    u00031 : constant Version_32 := 16#b98c3e16#;
26262    pragma Export (C, u00031, "system__tracebackB");
26263    u00032 : constant Version_32 := 16#831a9d5a#;
26264    pragma Export (C, u00032, "system__tracebackS");
26265    u00033 : constant Version_32 := 16#9ed49525#;
26266    pragma Export (C, u00033, "system__traceback_entriesB");
26267    u00034 : constant Version_32 := 16#1d7cb2f1#;
26268    pragma Export (C, u00034, "system__traceback_entriesS");
26269    u00035 : constant Version_32 := 16#8c33a517#;
26270    pragma Export (C, u00035, "system__wch_conB");
26271    u00036 : constant Version_32 := 16#065a6653#;
26272    pragma Export (C, u00036, "system__wch_conS");
26273    u00037 : constant Version_32 := 16#9721e840#;
26274    pragma Export (C, u00037, "system__wch_stwB");
26275    u00038 : constant Version_32 := 16#2b4b4a52#;
26276    pragma Export (C, u00038, "system__wch_stwS");
26277    u00039 : constant Version_32 := 16#92b797cb#;
26278    pragma Export (C, u00039, "system__wch_cnvB");
26279    u00040 : constant Version_32 := 16#09eddca0#;
26280    pragma Export (C, u00040, "system__wch_cnvS");
26281    u00041 : constant Version_32 := 16#6033a23f#;
26282    pragma Export (C, u00041, "interfacesS");
26283    u00042 : constant Version_32 := 16#ece6fdb6#;
26284    pragma Export (C, u00042, "system__wch_jisB");
26285    u00043 : constant Version_32 := 16#899dc581#;
26286    pragma Export (C, u00043, "system__wch_jisS");
26287    u00044 : constant Version_32 := 16#10558b11#;
26288    pragma Export (C, u00044, "ada__streamsB");
26289    u00045 : constant Version_32 := 16#2e6701ab#;
26290    pragma Export (C, u00045, "ada__streamsS");
26291    u00046 : constant Version_32 := 16#db5c917c#;
26292    pragma Export (C, u00046, "ada__io_exceptionsS");
26293    u00047 : constant Version_32 := 16#12c8cd7d#;
26294    pragma Export (C, u00047, "ada__tagsB");
26295    u00048 : constant Version_32 := 16#ce72c228#;
26296    pragma Export (C, u00048, "ada__tagsS");
26297    u00049 : constant Version_32 := 16#c3335bfd#;
26298    pragma Export (C, u00049, "system__htableB");
26299    u00050 : constant Version_32 := 16#99e5f76b#;
26300    pragma Export (C, u00050, "system__htableS");
26301    u00051 : constant Version_32 := 16#089f5cd0#;
26302    pragma Export (C, u00051, "system__string_hashB");
26303    u00052 : constant Version_32 := 16#3bbb9c15#;
26304    pragma Export (C, u00052, "system__string_hashS");
26305    u00053 : constant Version_32 := 16#807fe041#;
26306    pragma Export (C, u00053, "system__unsigned_typesS");
26307    u00054 : constant Version_32 := 16#d27be59e#;
26308    pragma Export (C, u00054, "system__val_lluB");
26309    u00055 : constant Version_32 := 16#fa8db733#;
26310    pragma Export (C, u00055, "system__val_lluS");
26311    u00056 : constant Version_32 := 16#27b600b2#;
26312    pragma Export (C, u00056, "system__val_utilB");
26313    u00057 : constant Version_32 := 16#b187f27f#;
26314    pragma Export (C, u00057, "system__val_utilS");
26315    u00058 : constant Version_32 := 16#d1060688#;
26316    pragma Export (C, u00058, "system__case_utilB");
26317    u00059 : constant Version_32 := 16#392e2d56#;
26318    pragma Export (C, u00059, "system__case_utilS");
26319    u00060 : constant Version_32 := 16#84a27f0d#;
26320    pragma Export (C, u00060, "interfaces__c_streamsB");
26321    u00061 : constant Version_32 := 16#8bb5f2c0#;
26322    pragma Export (C, u00061, "interfaces__c_streamsS");
26323    u00062 : constant Version_32 := 16#6db6928f#;
26324    pragma Export (C, u00062, "system__crtlS");
26325    u00063 : constant Version_32 := 16#4e6a342b#;
26326    pragma Export (C, u00063, "system__file_ioB");
26327    u00064 : constant Version_32 := 16#ba56a5e4#;
26328    pragma Export (C, u00064, "system__file_ioS");
26329    u00065 : constant Version_32 := 16#b7ab275c#;
26330    pragma Export (C, u00065, "ada__finalizationB");
26331    u00066 : constant Version_32 := 16#19f764ca#;
26332    pragma Export (C, u00066, "ada__finalizationS");
26333    u00067 : constant Version_32 := 16#95817ed8#;
26334    pragma Export (C, u00067, "system__finalization_rootB");
26335    u00068 : constant Version_32 := 16#52d53711#;
26336    pragma Export (C, u00068, "system__finalization_rootS");
26337    u00069 : constant Version_32 := 16#769e25e6#;
26338    pragma Export (C, u00069, "interfaces__cB");
26339    u00070 : constant Version_32 := 16#4a38bedb#;
26340    pragma Export (C, u00070, "interfaces__cS");
26341    u00071 : constant Version_32 := 16#07e6ee66#;
26342    pragma Export (C, u00071, "system__os_libB");
26343    u00072 : constant Version_32 := 16#d7b69782#;
26344    pragma Export (C, u00072, "system__os_libS");
26345    u00073 : constant Version_32 := 16#1a817b8e#;
26346    pragma Export (C, u00073, "system__stringsB");
26347    u00074 : constant Version_32 := 16#639855e7#;
26348    pragma Export (C, u00074, "system__stringsS");
26349    u00075 : constant Version_32 := 16#e0b8de29#;
26350    pragma Export (C, u00075, "system__file_control_blockS");
26351    u00076 : constant Version_32 := 16#b5b2aca1#;
26352    pragma Export (C, u00076, "system__finalization_mastersB");
26353    u00077 : constant Version_32 := 16#69316dc1#;
26354    pragma Export (C, u00077, "system__finalization_mastersS");
26355    u00078 : constant Version_32 := 16#57a37a42#;
26356    pragma Export (C, u00078, "system__address_imageB");
26357    u00079 : constant Version_32 := 16#bccbd9bb#;
26358    pragma Export (C, u00079, "system__address_imageS");
26359    u00080 : constant Version_32 := 16#7268f812#;
26360    pragma Export (C, u00080, "system__img_boolB");
26361    u00081 : constant Version_32 := 16#e8fe356a#;
26362    pragma Export (C, u00081, "system__img_boolS");
26363    u00082 : constant Version_32 := 16#d7aac20c#;
26364    pragma Export (C, u00082, "system__ioB");
26365    u00083 : constant Version_32 := 16#8365b3ce#;
26366    pragma Export (C, u00083, "system__ioS");
26367    u00084 : constant Version_32 := 16#6d4d969a#;
26368    pragma Export (C, u00084, "system__storage_poolsB");
26369    u00085 : constant Version_32 := 16#e87cc305#;
26370    pragma Export (C, u00085, "system__storage_poolsS");
26371    u00086 : constant Version_32 := 16#e34550ca#;
26372    pragma Export (C, u00086, "system__pool_globalB");
26373    u00087 : constant Version_32 := 16#c88d2d16#;
26374    pragma Export (C, u00087, "system__pool_globalS");
26375    u00088 : constant Version_32 := 16#9d39c675#;
26376    pragma Export (C, u00088, "system__memoryB");
26377    u00089 : constant Version_32 := 16#445a22b5#;
26378    pragma Export (C, u00089, "system__memoryS");
26379    u00090 : constant Version_32 := 16#6a859064#;
26380    pragma Export (C, u00090, "system__storage_pools__subpoolsB");
26381    u00091 : constant Version_32 := 16#e3b008dc#;
26382    pragma Export (C, u00091, "system__storage_pools__subpoolsS");
26383    u00092 : constant Version_32 := 16#63f11652#;
26384    pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
26385    u00093 : constant Version_32 := 16#fe2f4b3a#;
26386    pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
26388    --  BEGIN ELABORATION ORDER
26389    --  ada%s
26390    --  interfaces%s
26391    --  system%s
26392    --  system.case_util%s
26393    --  system.case_util%b
26394    --  system.htable%s
26395    --  system.img_bool%s
26396    --  system.img_bool%b
26397    --  system.img_int%s
26398    --  system.img_int%b
26399    --  system.io%s
26400    --  system.io%b
26401    --  system.parameters%s
26402    --  system.parameters%b
26403    --  system.crtl%s
26404    --  interfaces.c_streams%s
26405    --  interfaces.c_streams%b
26406    --  system.standard_library%s
26407    --  system.exceptions_debug%s
26408    --  system.exceptions_debug%b
26409    --  system.storage_elements%s
26410    --  system.storage_elements%b
26411    --  system.stack_checking%s
26412    --  system.stack_checking%b
26413    --  system.string_hash%s
26414    --  system.string_hash%b
26415    --  system.htable%b
26416    --  system.strings%s
26417    --  system.strings%b
26418    --  system.os_lib%s
26419    --  system.traceback_entries%s
26420    --  system.traceback_entries%b
26421    --  ada.exceptions%s
26422    --  system.soft_links%s
26423    --  system.unsigned_types%s
26424    --  system.val_llu%s
26425    --  system.val_util%s
26426    --  system.val_util%b
26427    --  system.val_llu%b
26428    --  system.wch_con%s
26429    --  system.wch_con%b
26430    --  system.wch_cnv%s
26431    --  system.wch_jis%s
26432    --  system.wch_jis%b
26433    --  system.wch_cnv%b
26434    --  system.wch_stw%s
26435    --  system.wch_stw%b
26436    --  ada.exceptions.last_chance_handler%s
26437    --  ada.exceptions.last_chance_handler%b
26438    --  system.address_image%s
26439    --  system.exception_table%s
26440    --  system.exception_table%b
26441    --  ada.io_exceptions%s
26442    --  ada.tags%s
26443    --  ada.streams%s
26444    --  ada.streams%b
26445    --  interfaces.c%s
26446    --  system.exceptions%s
26447    --  system.exceptions%b
26448    --  system.exceptions.machine%s
26449    --  system.finalization_root%s
26450    --  system.finalization_root%b
26451    --  ada.finalization%s
26452    --  ada.finalization%b
26453    --  system.storage_pools%s
26454    --  system.storage_pools%b
26455    --  system.finalization_masters%s
26456    --  system.storage_pools.subpools%s
26457    --  system.storage_pools.subpools.finalization%s
26458    --  system.storage_pools.subpools.finalization%b
26459    --  system.memory%s
26460    --  system.memory%b
26461    --  system.standard_library%b
26462    --  system.pool_global%s
26463    --  system.pool_global%b
26464    --  system.file_control_block%s
26465    --  system.file_io%s
26466    --  system.secondary_stack%s
26467    --  system.file_io%b
26468    --  system.storage_pools.subpools%b
26469    --  system.finalization_masters%b
26470    --  interfaces.c%b
26471    --  ada.tags%b
26472    --  system.soft_links%b
26473    --  system.os_lib%b
26474    --  system.secondary_stack%b
26475    --  system.address_image%b
26476    --  system.traceback%s
26477    --  ada.exceptions%b
26478    --  system.traceback%b
26479    --  ada.text_io%s
26480    --  ada.text_io%b
26481    --  hello%b
26482    --  END ELABORATION ORDER
26484 end ada_main;
26485 @end example
26487 @example
26488 pragma Ada_95;
26489 --  The following source file name pragmas allow the generated file
26490 --  names to be unique for different main programs. They are needed
26491 --  since the package name will always be Ada_Main.
26493 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26494 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26496 pragma Suppress (Overflow_Check);
26497 with Ada.Exceptions;
26499 --  Generated package body for Ada_Main starts here
26501 package body ada_main is
26502    pragma Warnings (Off);
26504    --  These values are reference counter associated to units which have
26505    --  been elaborated. It is also used to avoid elaborating the
26506    --  same unit twice.
26508    E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
26509    E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
26510    E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
26511    E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
26512    E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
26513    E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
26514    E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
26515    E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
26516    E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
26517    E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
26518    E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
26519    E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
26520    E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
26521    E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
26522    E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
26523    E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
26524    E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
26525    E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
26527    Local_Priority_Specific_Dispatching : constant String := "";
26528    Local_Interrupt_States : constant String := "";
26530    Is_Elaborated : Boolean := False;
26532    procedure finalize_library is
26533    begin
26534       E06 := E06 - 1;
26535       declare
26536          procedure F1;
26537          pragma Import (Ada, F1, "ada__text_io__finalize_spec");
26538       begin
26539          F1;
26540       end;
26541       E77 := E77 - 1;
26542       E91 := E91 - 1;
26543       declare
26544          procedure F2;
26545          pragma Import (Ada, F2, "system__file_io__finalize_body");
26546       begin
26547          E64 := E64 - 1;
26548          F2;
26549       end;
26550       declare
26551          procedure F3;
26552          pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
26553       begin
26554          E75 := E75 - 1;
26555          F3;
26556       end;
26557       E87 := E87 - 1;
26558       declare
26559          procedure F4;
26560          pragma Import (Ada, F4, "system__pool_global__finalize_spec");
26561       begin
26562          F4;
26563       end;
26564       declare
26565          procedure F5;
26566          pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
26567       begin
26568          F5;
26569       end;
26570       declare
26571          procedure F6;
26572          pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
26573       begin
26574          F6;
26575       end;
26576       declare
26577          procedure Reraise_Library_Exception_If_Any;
26578          pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
26579       begin
26580          Reraise_Library_Exception_If_Any;
26581       end;
26582    end finalize_library;
26584    -------------
26585    -- adainit --
26586    -------------
26588    procedure adainit is
26590       Main_Priority : Integer;
26591       pragma Import (C, Main_Priority, "__gl_main_priority");
26592       Time_Slice_Value : Integer;
26593       pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
26594       WC_Encoding : Character;
26595       pragma Import (C, WC_Encoding, "__gl_wc_encoding");
26596       Locking_Policy : Character;
26597       pragma Import (C, Locking_Policy, "__gl_locking_policy");
26598       Queuing_Policy : Character;
26599       pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
26600       Task_Dispatching_Policy : Character;
26601       pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
26602       Priority_Specific_Dispatching : System.Address;
26603       pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
26604       Num_Specific_Dispatching : Integer;
26605       pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
26606       Main_CPU : Integer;
26607       pragma Import (C, Main_CPU, "__gl_main_cpu");
26608       Interrupt_States : System.Address;
26609       pragma Import (C, Interrupt_States, "__gl_interrupt_states");
26610       Num_Interrupt_States : Integer;
26611       pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
26612       Unreserve_All_Interrupts : Integer;
26613       pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
26614       Detect_Blocking : Integer;
26615       pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
26616       Default_Stack_Size : Integer;
26617       pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
26618       Leap_Seconds_Support : Integer;
26619       pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
26621       procedure Runtime_Initialize;
26622       pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
26624       Finalize_Library_Objects : No_Param_Proc;
26625       pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
26627    --  Start of processing for adainit
26629    begin
26631       --  Record various information for this partition.  The values
26632       --  are derived by the binder from information stored in the ali
26633       --  files by the compiler.
26635       if Is_Elaborated then
26636          return;
26637       end if;
26638       Is_Elaborated := True;
26639       Main_Priority := -1;
26640       Time_Slice_Value := -1;
26641       WC_Encoding := 'b';
26642       Locking_Policy := ' ';
26643       Queuing_Policy := ' ';
26644       Task_Dispatching_Policy := ' ';
26645       Priority_Specific_Dispatching :=
26646         Local_Priority_Specific_Dispatching'Address;
26647       Num_Specific_Dispatching := 0;
26648       Main_CPU := -1;
26649       Interrupt_States := Local_Interrupt_States'Address;
26650       Num_Interrupt_States := 0;
26651       Unreserve_All_Interrupts := 0;
26652       Detect_Blocking := 0;
26653       Default_Stack_Size := -1;
26654       Leap_Seconds_Support := 0;
26656       Runtime_Initialize;
26658       Finalize_Library_Objects := finalize_library'access;
26660       --  Now we have the elaboration calls for all units in the partition.
26661       --  The Elab_Spec and Elab_Body attributes generate references to the
26662       --  implicit elaboration procedures generated by the compiler for
26663       --  each unit that requires elaboration. Increment a counter of
26664       --  reference for each unit.
26666       System.Soft_Links'Elab_Spec;
26667       System.Exception_Table'Elab_Body;
26668       E23 := E23 + 1;
26669       Ada.Io_Exceptions'Elab_Spec;
26670       E46 := E46 + 1;
26671       Ada.Tags'Elab_Spec;
26672       Ada.Streams'Elab_Spec;
26673       E45 := E45 + 1;
26674       Interfaces.C'Elab_Spec;
26675       System.Exceptions'Elab_Spec;
26676       E25 := E25 + 1;
26677       System.Finalization_Root'Elab_Spec;
26678       E68 := E68 + 1;
26679       Ada.Finalization'Elab_Spec;
26680       E66 := E66 + 1;
26681       System.Storage_Pools'Elab_Spec;
26682       E85 := E85 + 1;
26683       System.Finalization_Masters'Elab_Spec;
26684       System.Storage_Pools.Subpools'Elab_Spec;
26685       System.Pool_Global'Elab_Spec;
26686       E87 := E87 + 1;
26687       System.File_Control_Block'Elab_Spec;
26688       E75 := E75 + 1;
26689       System.File_Io'Elab_Body;
26690       E64 := E64 + 1;
26691       E91 := E91 + 1;
26692       System.Finalization_Masters'Elab_Body;
26693       E77 := E77 + 1;
26694       E70 := E70 + 1;
26695       Ada.Tags'Elab_Body;
26696       E48 := E48 + 1;
26697       System.Soft_Links'Elab_Body;
26698       E13 := E13 + 1;
26699       System.Os_Lib'Elab_Body;
26700       E72 := E72 + 1;
26701       System.Secondary_Stack'Elab_Body;
26702       E17 := E17 + 1;
26703       Ada.Text_Io'Elab_Spec;
26704       Ada.Text_Io'Elab_Body;
26705       E06 := E06 + 1;
26706    end adainit;
26708    --------------
26709    -- adafinal --
26710    --------------
26712    procedure adafinal is
26713       procedure s_stalib_adafinal;
26714       pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
26716       procedure Runtime_Finalize;
26717       pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
26719    begin
26720       if not Is_Elaborated then
26721          return;
26722       end if;
26723       Is_Elaborated := False;
26724       Runtime_Finalize;
26725       s_stalib_adafinal;
26726    end adafinal;
26728    --  We get to the main program of the partition by using
26729    --  pragma Import because if we try to with the unit and
26730    --  call it Ada style, then not only do we waste time
26731    --  recompiling it, but also, we don't really know the right
26732    --  switches (e.g.@@: identifier character set) to be used
26733    --  to compile it.
26735    procedure Ada_Main_Program;
26736    pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26738    ----------
26739    -- main --
26740    ----------
26742    --  main is actually a function, as in the ANSI C standard,
26743    --  defined to return the exit status. The three parameters
26744    --  are the argument count, argument values and environment
26745    --  pointer.
26747    function main
26748      (argc : Integer;
26749       argv : System.Address;
26750       envp : System.Address)
26751       return Integer
26752    is
26753       --  The initialize routine performs low level system
26754       --  initialization using a standard library routine which
26755       --  sets up signal handling and performs any other
26756       --  required setup. The routine can be found in file
26757       --  a-init.c.
26759       procedure initialize;
26760       pragma Import (C, initialize, "__gnat_initialize");
26762       --  The finalize routine performs low level system
26763       --  finalization using a standard library routine. The
26764       --  routine is found in file a-final.c and in the standard
26765       --  distribution is a dummy routine that does nothing, so
26766       --  really this is a hook for special user finalization.
26768       procedure finalize;
26769       pragma Import (C, finalize, "__gnat_finalize");
26771       --  The following is to initialize the SEH exceptions
26773       SEH : aliased array (1 .. 2) of Integer;
26775       Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
26776       pragma Volatile (Ensure_Reference);
26778    --  Start of processing for main
26780    begin
26781       --  Save global variables
26783       gnat_argc := argc;
26784       gnat_argv := argv;
26785       gnat_envp := envp;
26787       --  Call low level system initialization
26789       Initialize (SEH'Address);
26791       --  Call our generated Ada initialization routine
26793       adainit;
26795       --  Now we call the main program of the partition
26797       Ada_Main_Program;
26799       --  Perform Ada finalization
26801       adafinal;
26803       --  Perform low level system finalization
26805       Finalize;
26807       --  Return the proper exit status
26808       return (gnat_exit_status);
26809    end;
26811 --  This section is entirely comments, so it has no effect on the
26812 --  compilation of the Ada_Main package. It provides the list of
26813 --  object files and linker options, as well as some standard
26814 --  libraries needed for the link. The gnatlink utility parses
26815 --  this b~hello.adb file to read these comment lines to generate
26816 --  the appropriate command line arguments for the call to the
26817 --  system linker. The BEGIN/END lines are used for sentinels for
26818 --  this parsing operation.
26820 --  The exact file names will of course depend on the environment,
26821 --  host/target and location of files on the host system.
26823 -- BEGIN Object file/option list
26824    --   ./hello.o
26825    --   -L./
26826    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
26827    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
26828 -- END Object file/option list
26830 end ada_main;
26831 @end example
26833 The Ada code in the above example is exactly what is generated by the
26834 binder. We have added comments to more clearly indicate the function
26835 of each part of the generated @cite{Ada_Main} package.
26837 The code is standard Ada in all respects, and can be processed by any
26838 tools that handle Ada. In particular, it is possible to use the debugger
26839 in Ada mode to debug the generated @cite{Ada_Main} package. For example,
26840 suppose that for reasons that you do not understand, your program is crashing
26841 during elaboration of the body of @cite{Ada.Text_IO}. To locate this bug,
26842 you can place a breakpoint on the call:
26844 @quotation
26846 @example
26847 Ada.Text_Io'Elab_Body;
26848 @end example
26849 @end quotation
26851 and trace the elaboration routine for this package to find out where
26852 the problem might be (more usually of course you would be debugging
26853 elaboration code in your own application).
26855 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
26857 @node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
26858 @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{22e}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id1}@anchor{22f}
26859 @chapter Elaboration Order Handling in GNAT
26862 @geindex Order of elaboration
26864 @geindex Elaboration control
26866 This appendix describes the handling of elaboration code in Ada and
26867 in GNAT, and discusses how the order of elaboration of program units can
26868 be controlled in GNAT, either automatically or with explicit programming
26869 features.
26871 @menu
26872 * Elaboration Code:: 
26873 * Checking the Elaboration Order:: 
26874 * Controlling the Elaboration Order:: 
26875 * Controlling Elaboration in GNAT - Internal Calls:: 
26876 * Controlling Elaboration in GNAT - External Calls:: 
26877 * Default Behavior in GNAT - Ensuring Safety:: 
26878 * Treatment of Pragma Elaborate:: 
26879 * Elaboration Issues for Library Tasks:: 
26880 * Mixing Elaboration Models:: 
26881 * What to Do If the Default Elaboration Behavior Fails:: 
26882 * Elaboration for Indirect Calls:: 
26883 * Summary of Procedures for Elaboration Control:: 
26884 * Other Elaboration Order Considerations:: 
26885 * Determining the Chosen Elaboration Order:: 
26887 @end menu
26889 @node Elaboration Code,Checking the Elaboration Order,,Elaboration Order Handling in GNAT
26890 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{230}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{231}
26891 @section Elaboration Code
26894 Ada provides rather general mechanisms for executing code at elaboration
26895 time, that is to say before the main program starts executing. Such code arises
26896 in three contexts:
26899 @itemize *
26901 @item 
26902 @emph{Initializers for variables}
26904 Variables declared at the library level, in package specs or bodies, can
26905 require initialization that is performed at elaboration time, as in:
26907 @example
26908 Sqrt_Half : Float := Sqrt (0.5);
26909 @end example
26911 @item 
26912 @emph{Package initialization code}
26914 Code in a @cite{BEGIN-END} section at the outer level of a package body is
26915 executed as part of the package body elaboration code.
26917 @item 
26918 @emph{Library level task allocators}
26920 Tasks that are declared using task allocators at the library level
26921 start executing immediately and hence can execute at elaboration time.
26922 @end itemize
26924 Subprogram calls are possible in any of these contexts, which means that
26925 any arbitrary part of the program may be executed as part of the elaboration
26926 code. It is even possible to write a program which does all its work at
26927 elaboration time, with a null main program, although stylistically this
26928 would usually be considered an inappropriate way to structure
26929 a program.
26931 An important concern arises in the context of elaboration code:
26932 we have to be sure that it is executed in an appropriate order. What we
26933 have is a series of elaboration code sections, potentially one section
26934 for each unit in the program. It is important that these execute
26935 in the correct order. Correctness here means that, taking the above
26936 example of the declaration of @cite{Sqrt_Half},
26937 if some other piece of
26938 elaboration code references @cite{Sqrt_Half},
26939 then it must run after the
26940 section of elaboration code that contains the declaration of
26941 @cite{Sqrt_Half}.
26943 There would never be any order of elaboration problem if we made a rule
26944 that whenever you @emph{with} a unit, you must elaborate both the spec and body
26945 of that unit before elaborating the unit doing the @emph{with}ing:
26947 @example
26948 with Unit_1;
26949 package Unit_2 is ...
26950 @end example
26952 would require that both the body and spec of @cite{Unit_1} be elaborated
26953 before the spec of @cite{Unit_2}. However, a rule like that would be far too
26954 restrictive. In particular, it would make it impossible to have routines
26955 in separate packages that were mutually recursive.
26957 You might think that a clever enough compiler could look at the actual
26958 elaboration code and determine an appropriate correct order of elaboration,
26959 but in the general case, this is not possible. Consider the following
26960 example.
26962 In the body of @cite{Unit_1}, we have a procedure @cite{Func_1}
26963 that references
26964 the variable @cite{Sqrt_1}, which is declared in the elaboration code
26965 of the body of @cite{Unit_1}:
26967 @example
26968 Sqrt_1 : Float := Sqrt (0.1);
26969 @end example
26971 The elaboration code of the body of @cite{Unit_1} also contains:
26973 @example
26974 if expression_1 = 1 then
26975    Q := Unit_2.Func_2;
26976 end if;
26977 @end example
26979 @cite{Unit_2} is exactly parallel,
26980 it has a procedure @cite{Func_2} that references
26981 the variable @cite{Sqrt_2}, which is declared in the elaboration code of
26982 the body @cite{Unit_2}:
26984 @example
26985 Sqrt_2 : Float := Sqrt (0.1);
26986 @end example
26988 The elaboration code of the body of @cite{Unit_2} also contains:
26990 @example
26991 if expression_2 = 2 then
26992    Q := Unit_1.Func_1;
26993 end if;
26994 @end example
26996 Now the question is, which of the following orders of elaboration is
26997 acceptable:
26999 @example
27000 Spec of Unit_1
27001 Spec of Unit_2
27002 Body of Unit_1
27003 Body of Unit_2
27004 @end example
27008 @example
27009 Spec of Unit_2
27010 Spec of Unit_1
27011 Body of Unit_2
27012 Body of Unit_1
27013 @end example
27015 If you carefully analyze the flow here, you will see that you cannot tell
27016 at compile time the answer to this question.
27017 If @cite{expression_1} is not equal to 1,
27018 and @cite{expression_2} is not equal to 2,
27019 then either order is acceptable, because neither of the function calls is
27020 executed. If both tests evaluate to true, then neither order is acceptable
27021 and in fact there is no correct order.
27023 If one of the two expressions is true, and the other is false, then one
27024 of the above orders is correct, and the other is incorrect. For example,
27025 if @cite{expression_1} /= 1 and @cite{expression_2} = 2,
27026 then the call to @cite{Func_1}
27027 will occur, but not the call to @cite{Func_2.}
27028 This means that it is essential
27029 to elaborate the body of @cite{Unit_1} before
27030 the body of @cite{Unit_2}, so the first
27031 order of elaboration is correct and the second is wrong.
27033 By making @cite{expression_1} and @cite{expression_2}
27034 depend on input data, or perhaps
27035 the time of day, we can make it impossible for the compiler or binder
27036 to figure out which of these expressions will be true, and hence it
27037 is impossible to guarantee a safe order of elaboration at run time.
27039 @node Checking the Elaboration Order,Controlling the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
27040 @anchor{gnat_ugn/elaboration_order_handling_in_gnat checking-the-elaboration-order}@anchor{232}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{233}
27041 @section Checking the Elaboration Order
27044 In some languages that involve the same kind of elaboration problems,
27045 e.g., Java and C++, the programmer needs to take these
27046 ordering problems into account, and it is common to
27047 write a program in which an incorrect elaboration order  gives
27048 surprising results, because it references variables before they
27049 are initialized.
27050 Ada is designed to be a safe language, and a programmer-beware approach is
27051 clearly not sufficient. Consequently, the language provides three lines
27052 of defense:
27055 @itemize *
27057 @item 
27058 @emph{Standard rules}
27060 Some standard rules restrict the possible choice of elaboration
27061 order. In particular, if you @emph{with} a unit, then its spec is always
27062 elaborated before the unit doing the @emph{with}. Similarly, a parent
27063 spec is always elaborated before the child spec, and finally
27064 a spec is always elaborated before its corresponding body.
27065 @end itemize
27067 @geindex Elaboration checks
27069 @geindex Checks
27070 @geindex elaboration
27073 @itemize *
27075 @item 
27076 @emph{Dynamic elaboration checks}
27078 Dynamic checks are made at run time, so that if some entity is accessed
27079 before it is elaborated (typically  by means of a subprogram call)
27080 then the exception (@cite{Program_Error}) is raised.
27082 @item 
27083 @emph{Elaboration control}
27085 Facilities are provided for the programmer to specify the desired order
27086 of elaboration.
27087 @end itemize
27089 Let's look at these facilities in more detail. First, the rules for
27090 dynamic checking. One possible rule would be simply to say that the
27091 exception is raised if you access a variable which has not yet been
27092 elaborated. The trouble with this approach is that it could require
27093 expensive checks on every variable reference. Instead Ada has two
27094 rules which are a little more restrictive, but easier to check, and
27095 easier to state:
27098 @itemize *
27100 @item 
27101 @emph{Restrictions on calls}
27103 A subprogram can only be called at elaboration time if its body
27104 has been elaborated. The rules for elaboration given above guarantee
27105 that the spec of the subprogram has been elaborated before the
27106 call, but not the body. If this rule is violated, then the
27107 exception @cite{Program_Error} is raised.
27109 @item 
27110 @emph{Restrictions on instantiations}
27112 A generic unit can only be instantiated if the body of the generic
27113 unit has been elaborated. Again, the rules for elaboration given above
27114 guarantee that the spec of the generic unit has been elaborated
27115 before the instantiation, but not the body. If this rule is
27116 violated, then the exception @cite{Program_Error} is raised.
27117 @end itemize
27119 The idea is that if the body has been elaborated, then any variables
27120 it references must have been elaborated; by checking for the body being
27121 elaborated we guarantee that none of its references causes any
27122 trouble. As we noted above, this is a little too restrictive, because a
27123 subprogram that has no non-local references in its body may in fact be safe
27124 to call. However, it really would be unsafe to rely on this, because
27125 it would mean that the caller was aware of details of the implementation
27126 in the body. This goes against the basic tenets of Ada.
27128 A plausible implementation can be described as follows.
27129 A Boolean variable is associated with each subprogram
27130 and each generic unit. This variable is initialized to False, and is set to
27131 True at the point body is elaborated. Every call or instantiation checks the
27132 variable, and raises @cite{Program_Error} if the variable is False.
27134 Note that one might think that it would be good enough to have one Boolean
27135 variable for each package, but that would not deal with cases of trying
27136 to call a body in the same package as the call
27137 that has not been elaborated yet.
27138 Of course a compiler may be able to do enough analysis to optimize away
27139 some of the Boolean variables as unnecessary, and @cite{GNAT} indeed
27140 does such optimizations, but still the easiest conceptual model is to
27141 think of there being one variable per subprogram.
27143 @node Controlling the Elaboration Order,Controlling Elaboration in GNAT - Internal Calls,Checking the Elaboration Order,Elaboration Order Handling in GNAT
27144 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id4}@anchor{234}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order}@anchor{235}
27145 @section Controlling the Elaboration Order
27148 In the previous section we discussed the rules in Ada which ensure
27149 that @cite{Program_Error} is raised if an incorrect elaboration order is
27150 chosen. This prevents erroneous executions, but we need mechanisms to
27151 specify a correct execution and avoid the exception altogether.
27152 To achieve this, Ada provides a number of features for controlling
27153 the order of elaboration. We discuss these features in this section.
27155 First, there are several ways of indicating to the compiler that a given
27156 unit has no elaboration problems:
27159 @itemize *
27161 @item 
27162 @emph{packages that do not require a body}
27164 A library package that does not require a body does not permit
27165 a body (this rule was introduced in Ada 95).
27166 Thus if we have a such a package, as in:
27168 @example
27169 package Definitions is
27170    generic
27171       type m is new integer;
27172    package Subp is
27173       type a is array (1 .. 10) of m;
27174       type b is array (1 .. 20) of m;
27175    end Subp;
27176 end Definitions;
27177 @end example
27179 A package that @emph{with}s @cite{Definitions} may safely instantiate
27180 @cite{Definitions.Subp} because the compiler can determine that there
27181 definitely is no package body to worry about in this case
27182 @end itemize
27184 @geindex pragma Pure
27187 @itemize *
27189 @item 
27190 @emph{pragma Pure}
27192 This pragma places sufficient restrictions on a unit to guarantee that
27193 no call to any subprogram in the unit can result in an
27194 elaboration problem. This means that the compiler does not need
27195 to worry about the point of elaboration of such units, and in
27196 particular, does not need to check any calls to any subprograms
27197 in this unit.
27198 @end itemize
27200 @geindex pragma Preelaborate
27203 @itemize *
27205 @item 
27206 @emph{pragma Preelaborate}
27208 This pragma places slightly less stringent restrictions on a unit than
27209 does pragma Pure,
27210 but these restrictions are still sufficient to ensure that there
27211 are no elaboration problems with any calls to the unit.
27212 @end itemize
27214 @geindex pragma Elaborate_Body
27217 @itemize *
27219 @item 
27220 @emph{pragma Elaborate_Body}
27222 This pragma requires that the body of a unit be elaborated immediately
27223 after its spec. Suppose a unit @cite{A} has such a pragma,
27224 and unit @cite{B} does
27225 a @emph{with} of unit @cite{A}. Recall that the standard rules require
27226 the spec of unit @cite{A}
27227 to be elaborated before the @emph{with}ing unit; given the pragma in
27228 @cite{A}, we also know that the body of @cite{A}
27229 will be elaborated before @cite{B}, so
27230 that calls to @cite{A} are safe and do not need a check.
27232 Note that, unlike pragma @cite{Pure} and pragma @cite{Preelaborate},
27233 the use of @cite{Elaborate_Body} does not guarantee that the program is
27234 free of elaboration problems, because it may not be possible
27235 to satisfy the requested elaboration order.
27236 Let's go back to the example with @cite{Unit_1} and @cite{Unit_2}.
27237 If a programmer marks @cite{Unit_1} as @cite{Elaborate_Body},
27238 and not @cite{Unit_2@comma{}} then the order of
27239 elaboration will be:
27241 @example
27242 Spec of Unit_2
27243 Spec of Unit_1
27244 Body of Unit_1
27245 Body of Unit_2
27246 @end example
27248 Now that means that the call to @cite{Func_1} in @cite{Unit_2}
27249 need not be checked,
27250 it must be safe. But the call to @cite{Func_2} in
27251 @cite{Unit_1} may still fail if
27252 @cite{Expression_1} is equal to 1,
27253 and the programmer must still take
27254 responsibility for this not being the case.
27256 If all units carry a pragma @cite{Elaborate_Body}, then all problems are
27257 eliminated, except for calls entirely within a body, which are
27258 in any case fully under programmer control. However, using the pragma
27259 everywhere is not always possible.
27260 In particular, for our @cite{Unit_1}/@cite{Unit_2} example, if
27261 we marked both of them as having pragma @cite{Elaborate_Body}, then
27262 clearly there would be no possible elaboration order.
27263 @end itemize
27265 The above pragmas allow a server to guarantee safe use by clients, and
27266 clearly this is the preferable approach. Consequently a good rule
27267 is to mark units as @cite{Pure} or @cite{Preelaborate} if possible,
27268 and if this is not possible,
27269 mark them as @cite{Elaborate_Body} if possible.
27270 As we have seen, there are situations where neither of these
27271 three pragmas can be used.
27272 So we also provide methods for clients to control the
27273 order of elaboration of the servers on which they depend:
27275 @geindex pragma Elaborate
27278 @itemize *
27280 @item 
27281 @emph{pragma Elaborate (unit)}
27283 This pragma is placed in the context clause, after a @emph{with} clause,
27284 and it requires that the body of the named unit be elaborated before
27285 the unit in which the pragma occurs. The idea is to use this pragma
27286 if the current unit calls at elaboration time, directly or indirectly,
27287 some subprogram in the named unit.
27288 @end itemize
27290 @geindex pragma Elaborate_All
27293 @itemize *
27295 @item 
27296 @emph{pragma Elaborate_All (unit)}
27298 This is a stronger version of the Elaborate pragma. Consider the
27299 following example:
27301 @example
27302 Unit A |withs| unit B and calls B.Func in elab code
27303 Unit B |withs| unit C, and B.Func calls C.Func
27304 @end example
27306 Now if we put a pragma @cite{Elaborate (B)}
27307 in unit @cite{A}, this ensures that the
27308 body of @cite{B} is elaborated before the call, but not the
27309 body of @cite{C}, so
27310 the call to @cite{C.Func} could still cause @cite{Program_Error} to
27311 be raised.
27313 The effect of a pragma @cite{Elaborate_All} is stronger, it requires
27314 not only that the body of the named unit be elaborated before the
27315 unit doing the @emph{with}, but also the bodies of all units that the
27316 named unit uses, following @emph{with} links transitively. For example,
27317 if we put a pragma @cite{Elaborate_All (B)} in unit @cite{A},
27318 then it requires not only that the body of @cite{B} be elaborated before @cite{A},
27319 but also the body of @cite{C}, because @cite{B} @emph{with}s @cite{C}.
27320 @end itemize
27322 We are now in a position to give a usage rule in Ada for avoiding
27323 elaboration problems, at least if dynamic dispatching and access to
27324 subprogram values are not used. We will handle these cases separately
27325 later.
27327 The rule is simple:
27329 @emph{If a unit has elaboration code that can directly or
27330 indirectly make a call to a subprogram in a |withed| unit, or instantiate
27331 a generic package in a |withed| unit,
27332 then if the |withed| unit does not have
27333 pragma `Pure` or `Preelaborate`, then the client should have
27334 a pragma `Elaborate_All`for the |withed| unit.*}
27336 By following this rule a client is
27337 assured that calls can be made without risk of an exception.
27339 For generic subprogram instantiations, the rule can be relaxed to
27340 require only a pragma @cite{Elaborate} since elaborating the body
27341 of a subprogram cannot cause any transitive elaboration (we are
27342 not calling the subprogram in this case, just elaborating its
27343 declaration).
27345 If this rule is not followed, then a program may be in one of four
27346 states:
27349 @itemize *
27351 @item 
27352 @emph{No order exists}
27354 No order of elaboration exists which follows the rules, taking into
27355 account any @cite{Elaborate}, @cite{Elaborate_All},
27356 or @cite{Elaborate_Body} pragmas. In
27357 this case, an Ada compiler must diagnose the situation at bind
27358 time, and refuse to build an executable program.
27360 @item 
27361 @emph{One or more orders exist, all incorrect}
27363 One or more acceptable elaboration orders exist, and all of them
27364 generate an elaboration order problem. In this case, the binder
27365 can build an executable program, but @cite{Program_Error} will be raised
27366 when the program is run.
27368 @item 
27369 @emph{Several orders exist, some right, some incorrect}
27371 One or more acceptable elaboration orders exists, and some of them
27372 work, and some do not. The programmer has not controlled
27373 the order of elaboration, so the binder may or may not pick one of
27374 the correct orders, and the program may or may not raise an
27375 exception when it is run. This is the worst case, because it means
27376 that the program may fail when moved to another compiler, or even
27377 another version of the same compiler.
27379 @item 
27380 @emph{One or more orders exists, all correct}
27382 One ore more acceptable elaboration orders exist, and all of them
27383 work. In this case the program runs successfully. This state of
27384 affairs can be guaranteed by following the rule we gave above, but
27385 may be true even if the rule is not followed.
27386 @end itemize
27388 Note that one additional advantage of following our rules on the use
27389 of @cite{Elaborate} and @cite{Elaborate_All}
27390 is that the program continues to stay in the ideal (all orders OK) state
27391 even if maintenance
27392 changes some bodies of some units. Conversely, if a program that does
27393 not follow this rule happens to be safe at some point, this state of affairs
27394 may deteriorate silently as a result of maintenance changes.
27396 You may have noticed that the above discussion did not mention
27397 the use of @cite{Elaborate_Body}. This was a deliberate omission. If you
27398 @emph{with} an @cite{Elaborate_Body} unit, it still may be the case that
27399 code in the body makes calls to some other unit, so it is still necessary
27400 to use @cite{Elaborate_All} on such units.
27402 @node Controlling Elaboration in GNAT - Internal Calls,Controlling Elaboration in GNAT - External Calls,Controlling the Elaboration Order,Elaboration Order Handling in GNAT
27403 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id5}@anchor{236}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-elaboration-in-gnat-internal-calls}@anchor{237}
27404 @section Controlling Elaboration in GNAT - Internal Calls
27407 In the case of internal calls, i.e., calls within a single package, the
27408 programmer has full control over the order of elaboration, and it is up
27409 to the programmer to elaborate declarations in an appropriate order. For
27410 example writing:
27412 @example
27413 function One return Float;
27415 Q : Float := One;
27417 function One return Float is
27418 begin
27419      return 1.0;
27420 end One;
27421 @end example
27423 will obviously raise @cite{Program_Error} at run time, because function
27424 One will be called before its body is elaborated. In this case GNAT will
27425 generate a warning that the call will raise @cite{Program_Error}:
27427 @example
27428  1. procedure y is
27429  2.    function One return Float;
27430  3.
27431  4.    Q : Float := One;
27432                     |
27433     >>> warning: cannot call "One" before body is elaborated
27434     >>> warning: Program_Error will be raised at run time
27436  5.
27437  6.    function One return Float is
27438  7.    begin
27439  8.         return 1.0;
27440  9.    end One;
27442 11. begin
27443 12.    null;
27444 13. end;
27445 @end example
27447 Note that in this particular case, it is likely that the call is safe, because
27448 the function @cite{One} does not access any global variables.
27449 Nevertheless in Ada, we do not want the validity of the check to depend on
27450 the contents of the body (think about the separate compilation case), so this
27451 is still wrong, as we discussed in the previous sections.
27453 The error is easily corrected by rearranging the declarations so that the
27454 body of @cite{One} appears before the declaration containing the call
27455 (note that in Ada 95 as well as later versions of the Ada standard,
27456 declarations can appear in any order, so there is no restriction that
27457 would prevent this reordering, and if we write:
27459 @example
27460 function One return Float;
27462 function One return Float is
27463 begin
27464      return 1.0;
27465 end One;
27467 Q : Float := One;
27468 @end example
27470 then all is well, no warning is generated, and no
27471 @cite{Program_Error} exception
27472 will be raised.
27473 Things are more complicated when a chain of subprograms is executed:
27475 @example
27476 function A return Integer;
27477 function B return Integer;
27478 function C return Integer;
27480 function B return Integer is begin return A; end;
27481 function C return Integer is begin return B; end;
27483 X : Integer := C;
27485 function A return Integer is begin return 1; end;
27486 @end example
27488 Now the call to @cite{C}
27489 at elaboration time in the declaration of @cite{X} is correct, because
27490 the body of @cite{C} is already elaborated,
27491 and the call to @cite{B} within the body of
27492 @cite{C} is correct, but the call
27493 to @cite{A} within the body of @cite{B} is incorrect, because the body
27494 of @cite{A} has not been elaborated, so @cite{Program_Error}
27495 will be raised on the call to @cite{A}.
27496 In this case GNAT will generate a
27497 warning that @cite{Program_Error} may be
27498 raised at the point of the call. Let's look at the warning:
27500 @example
27501  1. procedure x is
27502  2.    function A return Integer;
27503  3.    function B return Integer;
27504  4.    function C return Integer;
27505  5.
27506  6.    function B return Integer is begin return A; end;
27507                                                     |
27508     >>> warning: call to "A" before body is elaborated may
27509                  raise Program_Error
27510     >>> warning: "B" called at line 7
27511     >>> warning: "C" called at line 9
27513  7.    function C return Integer is begin return B; end;
27514  8.
27515  9.    X : Integer := C;
27517 11.    function A return Integer is begin return 1; end;
27519 13. begin
27520 14.    null;
27521 15. end;
27522 @end example
27524 Note that the message here says 'may raise', instead of the direct case,
27525 where the message says 'will be raised'. That's because whether
27526 @cite{A} is
27527 actually called depends in general on run-time flow of control.
27528 For example, if the body of @cite{B} said
27530 @example
27531 function B return Integer is
27532 begin
27533    if some-condition-depending-on-input-data then
27534       return A;
27535    else
27536       return 1;
27537    end if;
27538 end B;
27539 @end example
27541 then we could not know until run time whether the incorrect call to A would
27542 actually occur, so @cite{Program_Error} might
27543 or might not be raised. It is possible for a compiler to
27544 do a better job of analyzing bodies, to
27545 determine whether or not @cite{Program_Error}
27546 might be raised, but it certainly
27547 couldn't do a perfect job (that would require solving the halting problem
27548 and is provably impossible), and because this is a warning anyway, it does
27549 not seem worth the effort to do the analysis. Cases in which it
27550 would be relevant are rare.
27552 In practice, warnings of either of the forms given
27553 above will usually correspond to
27554 real errors, and should be examined carefully and eliminated.
27555 In the rare case where a warning is bogus, it can be suppressed by any of
27556 the following methods:
27559 @itemize *
27561 @item 
27562 Compile with the @emph{-gnatws} switch set
27564 @item 
27565 Suppress @cite{Elaboration_Check} for the called subprogram
27567 @item 
27568 Use pragma @cite{Warnings_Off} to turn warnings off for the call
27569 @end itemize
27571 For the internal elaboration check case,
27572 GNAT by default generates the
27573 necessary run-time checks to ensure
27574 that @cite{Program_Error} is raised if any
27575 call fails an elaboration check. Of course this can only happen if a
27576 warning has been issued as described above. The use of pragma
27577 @cite{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
27578 some of these checks, meaning that it may be possible (but is not
27579 guaranteed) for a program to be able to call a subprogram whose body
27580 is not yet elaborated, without raising a @cite{Program_Error} exception.
27582 @node Controlling Elaboration in GNAT - External Calls,Default Behavior in GNAT - Ensuring Safety,Controlling Elaboration in GNAT - Internal Calls,Elaboration Order Handling in GNAT
27583 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id6}@anchor{238}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-elaboration-in-gnat-external-calls}@anchor{239}
27584 @section Controlling Elaboration in GNAT - External Calls
27587 The previous section discussed the case in which the execution of a
27588 particular thread of elaboration code occurred entirely within a
27589 single unit. This is the easy case to handle, because a programmer
27590 has direct and total control over the order of elaboration, and
27591 furthermore, checks need only be generated in cases which are rare
27592 and which the compiler can easily detect.
27593 The situation is more complex when separate compilation is taken into account.
27594 Consider the following:
27596 @example
27597 package Math is
27598    function Sqrt (Arg : Float) return Float;
27599 end Math;
27601 package body Math is
27602    function Sqrt (Arg : Float) return Float is
27603    begin
27604          ...
27605    end Sqrt;
27606 end Math;
27608 with Math;
27609 package Stuff is
27610    X : Float := Math.Sqrt (0.5);
27611 end Stuff;
27613 with Stuff;
27614 procedure Main is
27615 begin
27616    ...
27617 end Main;
27618 @end example
27620 where @cite{Main} is the main program. When this program is executed, the
27621 elaboration code must first be executed, and one of the jobs of the
27622 binder is to determine the order in which the units of a program are
27623 to be elaborated. In this case we have four units: the spec and body
27624 of @cite{Math},
27625 the spec of @cite{Stuff} and the body of @cite{Main}).
27626 In what order should the four separate sections of elaboration code
27627 be executed?
27629 There are some restrictions in the order of elaboration that the binder
27630 can choose. In particular, if unit U has a @emph{with}
27631 for a package @cite{X}, then you
27632 are assured that the spec of @cite{X}
27633 is elaborated before U , but you are
27634 not assured that the body of @cite{X}
27635 is elaborated before U.
27636 This means that in the above case, the binder is allowed to choose the
27637 order:
27639 @example
27640 spec of Math
27641 spec of Stuff
27642 body of Math
27643 body of Main
27644 @end example
27646 but that's not good, because now the call to @cite{Math.Sqrt}
27647 that happens during
27648 the elaboration of the @cite{Stuff}
27649 spec happens before the body of @cite{Math.Sqrt} is
27650 elaborated, and hence causes @cite{Program_Error} exception to be raised.
27651 At first glance, one might say that the binder is misbehaving, because
27652 obviously you want to elaborate the body of something you @emph{with} first, but
27653 that is not a general rule that can be followed in all cases. Consider
27655 @example
27656 package X is ...
27658 package Y is ...
27660 with X;
27661 package body Y is ...
27663 with Y;
27664 package body X is ...
27665 @end example
27667 This is a common arrangement, and, apart from the order of elaboration
27668 problems that might arise in connection with elaboration code, this works fine.
27669 A rule that says that you must first elaborate the body of anything you
27670 @emph{with} cannot work in this case:
27671 the body of @cite{X} @emph{with}s @cite{Y},
27672 which means you would have to
27673 elaborate the body of @cite{Y} first, but that @emph{with}s @cite{X},
27674 which means
27675 you have to elaborate the body of @cite{X} first, but ... and we have a
27676 loop that cannot be broken.
27678 It is true that the binder can in many cases guess an order of elaboration
27679 that is unlikely to cause a @cite{Program_Error}
27680 exception to be raised, and it tries to do so (in the
27681 above example of @cite{Math/Stuff/Spec}, the GNAT binder will
27682 by default
27683 elaborate the body of @cite{Math} right after its spec, so all will be well).
27685 However, a program that blindly relies on the binder to be helpful can
27686 get into trouble, as we discussed in the previous sections, so GNAT
27687 provides a number of facilities for assisting the programmer in
27688 developing programs that are robust with respect to elaboration order.
27690 @node Default Behavior in GNAT - Ensuring Safety,Treatment of Pragma Elaborate,Controlling Elaboration in GNAT - External Calls,Elaboration Order Handling in GNAT
27691 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{23a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat default-behavior-in-gnat-ensuring-safety}@anchor{23b}
27692 @section Default Behavior in GNAT - Ensuring Safety
27695 The default behavior in GNAT ensures elaboration safety. In its
27696 default mode GNAT implements the
27697 rule we previously described as the right approach. Let's restate it:
27699 @emph{If a unit has elaboration code that can directly or indirectly make a
27700 call to a subprogram in a |withed| unit, or instantiate a generic
27701 package in a |withed| unit, then if the |withed| unit
27702 does not have pragma `Pure` or `Preelaborate`, then the client should have an
27703 `Elaborate_All` pragma for the |withed| unit.}
27705 @emph{In the case of instantiating a generic subprogram, it is always
27706 sufficient to have only an `Elaborate` pragma for the
27707 |withed| unit.}
27709 By following this rule a client is assured that calls and instantiations
27710 can be made without risk of an exception.
27712 In this mode GNAT traces all calls that are potentially made from
27713 elaboration code, and puts in any missing implicit @cite{Elaborate}
27714 and @cite{Elaborate_All} pragmas.
27715 The advantage of this approach is that no elaboration problems
27716 are possible if the binder can find an elaboration order that is
27717 consistent with these implicit @cite{Elaborate} and
27718 @cite{Elaborate_All} pragmas. The
27719 disadvantage of this approach is that no such order may exist.
27721 If the binder does not generate any diagnostics, then it means that it has
27722 found an elaboration order that is guaranteed to be safe. However, the binder
27723 may still be relying on implicitly generated @cite{Elaborate} and
27724 @cite{Elaborate_All} pragmas so portability to other compilers than GNAT is not
27725 guaranteed.
27727 If it is important to guarantee portability, then the compilations should
27728 use the @emph{-gnatel}
27729 (info messages for elaboration pragmas) switch. This will cause info messages
27730 to be generated indicating the missing @cite{Elaborate} and
27731 @cite{Elaborate_All} pragmas.
27732 Consider the following source program:
27734 @example
27735 with k;
27736 package j is
27737   m : integer := k.r;
27738 end;
27739 @end example
27741 where it is clear that there
27742 should be a pragma @cite{Elaborate_All}
27743 for unit @cite{k}. An implicit pragma will be generated, and it is
27744 likely that the binder will be able to honor it. However, if you want
27745 to port this program to some other Ada compiler than GNAT.
27746 it is safer to include the pragma explicitly in the source. If this
27747 unit is compiled with the @emph{-gnatel}
27748 switch, then the compiler outputs an information message:
27750 @example
27751 1. with k;
27752 2. package j is
27753 3.   m : integer := k.r;
27754                      |
27755    >>> info: call to "r" may raise Program_Error
27756    >>> info: missing pragma Elaborate_All for "k"
27758 4. end;
27759 @end example
27761 and these messages can be used as a guide for supplying manually
27762 the missing pragmas. It is usually a bad idea to use this
27763 option during development. That's because it will tell you when
27764 you need to put in a pragma, but cannot tell you when it is time
27765 to take it out. So the use of pragma @cite{Elaborate_All} may lead to
27766 unnecessary dependencies and even false circularities.
27768 This default mode is more restrictive than the Ada Reference
27769 Manual, and it is possible to construct programs which will compile
27770 using the dynamic model described there, but will run into a
27771 circularity using the safer static model we have described.
27773 Of course any Ada compiler must be able to operate in a mode
27774 consistent with the requirements of the Ada Reference Manual,
27775 and in particular must have the capability of implementing the
27776 standard dynamic model of elaboration with run-time checks.
27778 In GNAT, this standard mode can be achieved either by the use of
27779 the @emph{-gnatE} switch on the compiler (@emph{gcc} or
27780 @emph{gnatmake}) command, or by the use of the configuration pragma:
27782 @example
27783 pragma Elaboration_Checks (DYNAMIC);
27784 @end example
27786 Either approach will cause the unit affected to be compiled using the
27787 standard dynamic run-time elaboration checks described in the Ada
27788 Reference Manual. The static model is generally preferable, since it
27789 is clearly safer to rely on compile and link time checks rather than
27790 run-time checks. However, in the case of legacy code, it may be
27791 difficult to meet the requirements of the static model. This
27792 issue is further discussed in
27793 @ref{23c,,What to Do If the Default Elaboration Behavior Fails}.
27795 Note that the static model provides a strict subset of the allowed
27796 behavior and programs of the Ada Reference Manual, so if you do
27797 adhere to the static model and no circularities exist,
27798 then you are assured that your program will
27799 work using the dynamic model, providing that you remove any
27800 pragma Elaborate statements from the source.
27802 @node Treatment of Pragma Elaborate,Elaboration Issues for Library Tasks,Default Behavior in GNAT - Ensuring Safety,Elaboration Order Handling in GNAT
27803 @anchor{gnat_ugn/elaboration_order_handling_in_gnat treatment-of-pragma-elaborate}@anchor{23d}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{23e}
27804 @section Treatment of Pragma Elaborate
27807 @geindex Pragma Elaborate
27809 The use of @cite{pragma Elaborate}
27810 should generally be avoided in Ada 95 and Ada 2005 programs,
27811 since there is no guarantee that transitive calls
27812 will be properly handled. Indeed at one point, this pragma was placed
27813 in Annex J (Obsolescent Features), on the grounds that it is never useful.
27815 Now that's a bit restrictive. In practice, the case in which
27816 @cite{pragma Elaborate} is useful is when the caller knows that there
27817 are no transitive calls, or that the called unit contains all necessary
27818 transitive @cite{pragma Elaborate} statements, and legacy code often
27819 contains such uses.
27821 Strictly speaking the static mode in GNAT should ignore such pragmas,
27822 since there is no assurance at compile time that the necessary safety
27823 conditions are met. In practice, this would cause GNAT to be incompatible
27824 with correctly written Ada 83 code that had all necessary
27825 @cite{pragma Elaborate} statements in place. Consequently, we made the
27826 decision that GNAT in its default mode will believe that if it encounters
27827 a @cite{pragma Elaborate} then the programmer knows what they are doing,
27828 and it will trust that no elaboration errors can occur.
27830 The result of this decision is two-fold. First to be safe using the
27831 static mode, you should remove all @cite{pragma Elaborate} statements.
27832 Second, when fixing circularities in existing code, you can selectively
27833 use @cite{pragma Elaborate} statements to convince the static mode of
27834 GNAT that it need not generate an implicit @cite{pragma Elaborate_All}
27835 statement.
27837 When using the static mode with @emph{-gnatwl}, any use of
27838 @cite{pragma Elaborate} will generate a warning about possible
27839 problems.
27841 @node Elaboration Issues for Library Tasks,Mixing Elaboration Models,Treatment of Pragma Elaborate,Elaboration Order Handling in GNAT
27842 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-issues-for-library-tasks}@anchor{23f}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{240}
27843 @section Elaboration Issues for Library Tasks
27846 @geindex Library tasks
27847 @geindex elaboration issues
27849 @geindex Elaboration of library tasks
27851 In this section we examine special elaboration issues that arise for
27852 programs that declare library level tasks.
27854 Generally the model of execution of an Ada program is that all units are
27855 elaborated, and then execution of the program starts. However, the
27856 declaration of library tasks definitely does not fit this model. The
27857 reason for this is that library tasks start as soon as they are declared
27858 (more precisely, as soon as the statement part of the enclosing package
27859 body is reached), that is to say before elaboration
27860 of the program is complete. This means that if such a task calls a
27861 subprogram, or an entry in another task, the callee may or may not be
27862 elaborated yet, and in the standard
27863 Reference Manual model of dynamic elaboration checks, you can even
27864 get timing dependent Program_Error exceptions, since there can be
27865 a race between the elaboration code and the task code.
27867 The static model of elaboration in GNAT seeks to avoid all such
27868 dynamic behavior, by being conservative, and the conservative
27869 approach in this particular case is to assume that all the code
27870 in a task body is potentially executed at elaboration time if
27871 a task is declared at the library level.
27873 This can definitely result in unexpected circularities. Consider
27874 the following example
27876 @example
27877 package Decls is
27878   task Lib_Task is
27879      entry Start;
27880   end Lib_Task;
27882   type My_Int is new Integer;
27884   function Ident (M : My_Int) return My_Int;
27885 end Decls;
27887 with Utils;
27888 package body Decls is
27889   task body Lib_Task is
27890   begin
27891      accept Start;
27892      Utils.Put_Val (2);
27893   end Lib_Task;
27895   function Ident (M : My_Int) return My_Int is
27896   begin
27897      return M;
27898   end Ident;
27899 end Decls;
27901 with Decls;
27902 package Utils is
27903   procedure Put_Val (Arg : Decls.My_Int);
27904 end Utils;
27906 with Text_IO;
27907 package body Utils is
27908   procedure Put_Val (Arg : Decls.My_Int) is
27909   begin
27910      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27911   end Put_Val;
27912 end Utils;
27914 with Decls;
27915 procedure Main is
27916 begin
27917    Decls.Lib_Task.Start;
27918 end;
27919 @end example
27921 If the above example is compiled in the default static elaboration
27922 mode, then a circularity occurs. The circularity comes from the call
27923 @cite{Utils.Put_Val} in the task body of @cite{Decls.Lib_Task}. Since
27924 this call occurs in elaboration code, we need an implicit pragma
27925 @cite{Elaborate_All} for @cite{Utils}. This means that not only must
27926 the spec and body of @cite{Utils} be elaborated before the body
27927 of @cite{Decls}, but also the spec and body of any unit that is
27928 @emph{with}ed by the body of @cite{Utils} must also be elaborated before
27929 the body of @cite{Decls}. This is the transitive implication of
27930 pragma @cite{Elaborate_All} and it makes sense, because in general
27931 the body of @cite{Put_Val} might have a call to something in a
27932 @emph{with}ed unit.
27934 In this case, the body of Utils (actually its spec) @emph{with}s
27935 @cite{Decls}. Unfortunately this means that the body of @cite{Decls}
27936 must be elaborated before itself, in case there is a call from the
27937 body of @cite{Utils}.
27939 Here is the exact chain of events we are worrying about:
27942 @itemize *
27944 @item 
27945 In the body of @cite{Decls} a call is made from within the body of a library
27946 task to a subprogram in the package @cite{Utils}. Since this call may
27947 occur at elaboration time (given that the task is activated at elaboration
27948 time), we have to assume the worst, i.e., that the
27949 call does happen at elaboration time.
27951 @item 
27952 This means that the body and spec of @cite{Util} must be elaborated before
27953 the body of @cite{Decls} so that this call does not cause an access before
27954 elaboration.
27956 @item 
27957 Within the body of @cite{Util}, specifically within the body of
27958 @cite{Util.Put_Val} there may be calls to any unit @emph{with}ed
27959 by this package.
27961 @item 
27962 One such @emph{with}ed package is package @cite{Decls}, so there
27963 might be a call to a subprogram in @cite{Decls} in @cite{Put_Val}.
27964 In fact there is such a call in this example, but we would have to
27965 assume that there was such a call even if it were not there, since
27966 we are not supposed to write the body of @cite{Decls} knowing what
27967 is in the body of @cite{Utils}; certainly in the case of the
27968 static elaboration model, the compiler does not know what is in
27969 other bodies and must assume the worst.
27971 @item 
27972 This means that the spec and body of @cite{Decls} must also be
27973 elaborated before we elaborate the unit containing the call, but
27974 that unit is @cite{Decls}! This means that the body of @cite{Decls}
27975 must be elaborated before itself, and that's a circularity.
27976 @end itemize
27978 Indeed, if you add an explicit pragma @cite{Elaborate_All} for @cite{Utils} in
27979 the body of @cite{Decls} you will get a true Ada Reference Manual
27980 circularity that makes the program illegal.
27982 In practice, we have found that problems with the static model of
27983 elaboration in existing code often arise from library tasks, so
27984 we must address this particular situation.
27986 Note that if we compile and run the program above, using the dynamic model of
27987 elaboration (that is to say use the @emph{-gnatE} switch),
27988 then it compiles, binds,
27989 links, and runs, printing the expected result of 2. Therefore in some sense
27990 the circularity here is only apparent, and we need to capture
27991 the properties of this program that  distinguish it from other library-level
27992 tasks that have real elaboration problems.
27994 We have four possible answers to this question:
27997 @itemize *
27999 @item 
28000 Use the dynamic model of elaboration.
28002 If we use the @emph{-gnatE} switch, then as noted above, the program works.
28003 Why is this? If we examine the task body, it is apparent that the task cannot
28004 proceed past the
28005 @cite{accept} statement until after elaboration has been completed, because
28006 the corresponding entry call comes from the main program, not earlier.
28007 This is why the dynamic model works here. But that's really giving
28008 up on a precise analysis, and we prefer to take this approach only if we cannot
28009 solve the
28010 problem in any other manner. So let us examine two ways to reorganize
28011 the program to avoid the potential elaboration problem.
28013 @item 
28014 Split library tasks into separate packages.
28016 Write separate packages, so that library tasks are isolated from
28017 other declarations as much as possible. Let us look at a variation on
28018 the above program.
28020 @example
28021 package Decls1 is
28022   task Lib_Task is
28023      entry Start;
28024   end Lib_Task;
28025 end Decls1;
28027 with Utils;
28028 package body Decls1 is
28029   task body Lib_Task is
28030   begin
28031      accept Start;
28032      Utils.Put_Val (2);
28033   end Lib_Task;
28034 end Decls1;
28036 package Decls2 is
28037   type My_Int is new Integer;
28038   function Ident (M : My_Int) return My_Int;
28039 end Decls2;
28041 with Utils;
28042 package body Decls2 is
28043   function Ident (M : My_Int) return My_Int is
28044   begin
28045      return M;
28046   end Ident;
28047 end Decls2;
28049 with Decls2;
28050 package Utils is
28051   procedure Put_Val (Arg : Decls2.My_Int);
28052 end Utils;
28054 with Text_IO;
28055 package body Utils is
28056   procedure Put_Val (Arg : Decls2.My_Int) is
28057   begin
28058      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
28059   end Put_Val;
28060 end Utils;
28062 with Decls1;
28063 procedure Main is
28064 begin
28065    Decls1.Lib_Task.Start;
28066 end;
28067 @end example
28069 All we have done is to split @cite{Decls} into two packages, one
28070 containing the library task, and one containing everything else. Now
28071 there is no cycle, and the program compiles, binds, links and executes
28072 using the default static model of elaboration.
28074 @item 
28075 Declare separate task types.
28077 A significant part of the problem arises because of the use of the
28078 single task declaration form. This means that the elaboration of
28079 the task type, and the elaboration of the task itself (i.e., the
28080 creation of the task) happen at the same time. A good rule
28081 of style in Ada is to always create explicit task types. By
28082 following the additional step of placing task objects in separate
28083 packages from the task type declaration, many elaboration problems
28084 are avoided. Here is another modified example of the example program:
28086 @example
28087 package Decls is
28088   task type Lib_Task_Type is
28089      entry Start;
28090   end Lib_Task_Type;
28092   type My_Int is new Integer;
28094   function Ident (M : My_Int) return My_Int;
28095 end Decls;
28097 with Utils;
28098 package body Decls is
28099   task body Lib_Task_Type is
28100   begin
28101      accept Start;
28102      Utils.Put_Val (2);
28103   end Lib_Task_Type;
28105   function Ident (M : My_Int) return My_Int is
28106   begin
28107      return M;
28108   end Ident;
28109 end Decls;
28111 with Decls;
28112 package Utils is
28113   procedure Put_Val (Arg : Decls.My_Int);
28114 end Utils;
28116 with Text_IO;
28117 package body Utils is
28118   procedure Put_Val (Arg : Decls.My_Int) is
28119   begin
28120      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28121   end Put_Val;
28122 end Utils;
28124 with Decls;
28125 package Declst is
28126    Lib_Task : Decls.Lib_Task_Type;
28127 end Declst;
28129 with Declst;
28130 procedure Main is
28131 begin
28132    Declst.Lib_Task.Start;
28133 end;
28134 @end example
28136 What we have done here is to replace the @cite{task} declaration in
28137 package @cite{Decls} with a @cite{task type} declaration. Then we
28138 introduce a separate package @cite{Declst} to contain the actual
28139 task object. This separates the elaboration issues for
28140 the @cite{task type}
28141 declaration, which causes no trouble, from the elaboration issues
28142 of the task object, which is also unproblematic, since it is now independent
28143 of the elaboration of  @cite{Utils}.
28144 This separation of concerns also corresponds to
28145 a generally sound engineering principle of separating declarations
28146 from instances. This version of the program also compiles, binds, links,
28147 and executes, generating the expected output.
28148 @end itemize
28150 @geindex No_Entry_Calls_In_Elaboration_Code restriction
28153 @itemize *
28155 @item 
28156 Use No_Entry_Calls_In_Elaboration_Code restriction.
28158 The previous two approaches described how a program can be restructured
28159 to avoid the special problems caused by library task bodies. in practice,
28160 however, such restructuring may be difficult to apply to existing legacy code,
28161 so we must consider solutions that do not require massive rewriting.
28163 Let us consider more carefully why our original sample program works
28164 under the dynamic model of elaboration. The reason is that the code
28165 in the task body blocks immediately on the @cite{accept}
28166 statement. Now of course there is nothing to prohibit elaboration
28167 code from making entry calls (for example from another library level task),
28168 so we cannot tell in isolation that
28169 the task will not execute the accept statement  during elaboration.
28171 However, in practice it is very unusual to see elaboration code
28172 make any entry calls, and the pattern of tasks starting
28173 at elaboration time and then immediately blocking on @cite{accept} or
28174 @cite{select} statements is very common. What this means is that
28175 the compiler is being too pessimistic when it analyzes the
28176 whole package body as though it might be executed at elaboration
28177 time.
28179 If we know that the elaboration code contains no entry calls, (a very safe
28180 assumption most of the time, that could almost be made the default
28181 behavior), then we can compile all units of the program under control
28182 of the following configuration pragma:
28184 @example
28185 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28186 @end example
28188 This pragma can be placed in the @code{gnat.adc} file in the usual
28189 manner. If we take our original unmodified program and compile it
28190 in the presence of a @code{gnat.adc} containing the above pragma,
28191 then once again, we can compile, bind, link, and execute, obtaining
28192 the expected result. In the presence of this pragma, the compiler does
28193 not trace calls in a task body, that appear after the first @cite{accept}
28194 or @cite{select} statement, and therefore does not report a potential
28195 circularity in the original program.
28197 The compiler will check to the extent it can that the above
28198 restriction is not violated, but it is not always possible to do a
28199 complete check at compile time, so it is important to use this
28200 pragma only if the stated restriction is in fact met, that is to say
28201 no task receives an entry call before elaboration of all units is completed.
28202 @end itemize
28204 @node Mixing Elaboration Models,What to Do If the Default Elaboration Behavior Fails,Elaboration Issues for Library Tasks,Elaboration Order Handling in GNAT
28205 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{241}@anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{242}
28206 @section Mixing Elaboration Models
28209 So far, we have assumed that the entire program is either compiled
28210 using the dynamic model or static model, ensuring consistency. It
28211 is possible to mix the two models, but rules have to be followed
28212 if this mixing is done to ensure that elaboration checks are not
28213 omitted.
28215 The basic rule is that
28216 @strong{a unit compiled with the static model cannot
28217 be |withed| by a unit compiled with the dynamic model}.
28218 The reason for this is that in the static model, a unit assumes that
28219 its clients guarantee to use (the equivalent of) pragma
28220 @cite{Elaborate_All} so that no elaboration checks are required
28221 in inner subprograms, and this assumption is violated if the
28222 client is compiled with dynamic checks.
28224 The precise rule is as follows. A unit that is compiled with dynamic
28225 checks can only @emph{with} a unit that meets at least one of the
28226 following criteria:
28229 @itemize *
28231 @item 
28232 The @emph{with}ed unit is itself compiled with dynamic elaboration
28233 checks (that is with the @emph{-gnatE} switch.
28235 @item 
28236 The @emph{with}ed unit is an internal GNAT implementation unit from
28237 the System, Interfaces, Ada, or GNAT hierarchies.
28239 @item 
28240 The @emph{with}ed unit has pragma Preelaborate or pragma Pure.
28242 @item 
28243 The @emph{with}ing unit (that is the client) has an explicit pragma
28244 @cite{Elaborate_All} for the @emph{with}ed unit.
28245 @end itemize
28247 If this rule is violated, that is if a unit with dynamic elaboration
28248 checks @emph{with}s a unit that does not meet one of the above four
28249 criteria, then the binder (@cite{gnatbind}) will issue a warning
28250 similar to that in the following example:
28252 @example
28253 warning: "x.ads" has dynamic elaboration checks and with's
28254 warning:   "y.ads" which has static elaboration checks
28255 @end example
28257 These warnings indicate that the rule has been violated, and that as a result
28258 elaboration checks may be missed in the resulting executable file.
28259 This warning may be suppressed using the @emph{-ws} binder switch
28260 in the usual manner.
28262 One useful application of this mixing rule is in the case of a subsystem
28263 which does not itself @emph{with} units from the remainder of the
28264 application. In this case, the entire subsystem can be compiled with
28265 dynamic checks to resolve a circularity in the subsystem, while
28266 allowing the main application that uses this subsystem to be compiled
28267 using the more reliable default static model.
28269 @node What to Do If the Default Elaboration Behavior Fails,Elaboration for Indirect Calls,Mixing Elaboration Models,Elaboration Order Handling in GNAT
28270 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{243}@anchor{gnat_ugn/elaboration_order_handling_in_gnat what-to-do-if-the-default-elaboration-behavior-fails}@anchor{23c}
28271 @section What to Do If the Default Elaboration Behavior Fails
28274 If the binder cannot find an acceptable order, it outputs detailed
28275 diagnostics. For example:
28277 @example
28278 error: elaboration circularity detected
28279 info:   "proc (body)" must be elaborated before "pack (body)"
28280 info:     reason: Elaborate_All probably needed in unit "pack (body)"
28281 info:     recompile "pack (body)" with -gnatel
28282 info:                             for full details
28283 info:       "proc (body)"
28284 info:         is needed by its spec:
28285 info:       "proc (spec)"
28286 info:         which is withed by:
28287 info:       "pack (body)"
28288 info:  "pack (body)" must be elaborated before "proc (body)"
28289 info:     reason: pragma Elaborate in unit "proc (body)"
28290 @end example
28292 In this case we have a cycle that the binder cannot break. On the one
28293 hand, there is an explicit pragma Elaborate in @cite{proc} for
28294 @cite{pack}. This means that the body of @cite{pack} must be elaborated
28295 before the body of @cite{proc}. On the other hand, there is elaboration
28296 code in @cite{pack} that calls a subprogram in @cite{proc}. This means
28297 that for maximum safety, there should really be a pragma
28298 Elaborate_All in @cite{pack} for @cite{proc} which would require that
28299 the body of @cite{proc} be elaborated before the body of
28300 @cite{pack}. Clearly both requirements cannot be satisfied.
28301 Faced with a circularity of this kind, you have three different options.
28304 @itemize *
28306 @item 
28307 @emph{Fix the program}
28309 The most desirable option from the point of view of long-term maintenance
28310 is to rearrange the program so that the elaboration problems are avoided.
28311 One useful technique is to place the elaboration code into separate
28312 child packages. Another is to move some of the initialization code to
28313 explicitly called subprograms, where the program controls the order
28314 of initialization explicitly. Although this is the most desirable option,
28315 it may be impractical and involve too much modification, especially in
28316 the case of complex legacy code.
28318 @item 
28319 @emph{Perform dynamic checks}
28321 If the compilations are done using the @emph{-gnatE}
28322 (dynamic elaboration check) switch, then GNAT behaves in a quite different
28323 manner. Dynamic checks are generated for all calls that could possibly result
28324 in raising an exception. With this switch, the compiler does not generate
28325 implicit @cite{Elaborate} or @cite{Elaborate_All} pragmas. The behavior then is
28326 exactly as specified in the @cite{Ada Reference Manual}.
28327 The binder will generate
28328 an executable program that may or may not raise @cite{Program_Error}, and then
28329 it is the programmer's job to ensure that it does not raise an exception. Note
28330 that it is important to compile all units with the switch, it cannot be used
28331 selectively.
28333 @item 
28334 @emph{Suppress checks}
28336 The drawback of dynamic checks is that they generate a
28337 significant overhead at run time, both in space and time. If you
28338 are absolutely sure that your program cannot raise any elaboration
28339 exceptions, and you still want to use the dynamic elaboration model,
28340 then you can use the configuration pragma
28341 @cite{Suppress (Elaboration_Check)} to suppress all such checks. For
28342 example this pragma could be placed in the @code{gnat.adc} file.
28344 @item 
28345 @emph{Suppress checks selectively}
28347 When you know that certain calls or instantiations in elaboration code cannot
28348 possibly lead to an elaboration error, and the binder nevertheless complains
28349 about implicit @cite{Elaborate} and @cite{Elaborate_All} pragmas that lead to
28350 elaboration circularities, it is possible to remove those warnings locally and
28351 obtain a program that will bind. Clearly this can be unsafe, and it is the
28352 responsibility of the programmer to make sure that the resulting program has no
28353 elaboration anomalies. The pragma @cite{Suppress (Elaboration_Check)} can be
28354 used with different granularity to suppress warnings and break elaboration
28355 circularities:
28358 @itemize *
28360 @item 
28361 Place the pragma that names the called subprogram in the declarative part
28362 that contains the call.
28364 @item 
28365 Place the pragma in the declarative part, without naming an entity. This
28366 disables warnings on all calls in the corresponding  declarative region.
28368 @item 
28369 Place the pragma in the package spec that declares the called subprogram,
28370 and name the subprogram. This disables warnings on all elaboration calls to
28371 that subprogram.
28373 @item 
28374 Place the pragma in the package spec that declares the called subprogram,
28375 without naming any entity. This disables warnings on all elaboration calls to
28376 all subprograms declared in this spec.
28378 @item 
28379 Use Pragma Elaborate.
28381 As previously described in section @ref{23d,,Treatment of Pragma Elaborate},
28382 GNAT in static mode assumes that a @cite{pragma} Elaborate indicates correctly
28383 that no elaboration checks are required on calls to the designated unit.
28384 There may be cases in which the caller knows that no transitive calls
28385 can occur, so that a @cite{pragma Elaborate} will be sufficient in a
28386 case where @cite{pragma Elaborate_All} would cause a circularity.
28387 @end itemize
28389 These five cases are listed in order of decreasing safety, and therefore
28390 require increasing programmer care in their application. Consider the
28391 following program:
28393 @example
28394 package Pack1 is
28395   function F1 return Integer;
28396   X1 : Integer;
28397 end Pack1;
28399 package Pack2 is
28400   function F2 return Integer;
28401   function Pure (x : integer) return integer;
28402   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
28403   --  pragma Suppress (Elaboration_Check);              -- (4)
28404 end Pack2;
28406 with Pack2;
28407 package body Pack1 is
28408   function F1 return Integer is
28409   begin
28410     return 100;
28411   end F1;
28412   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
28413 begin
28414   declare
28415     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
28416     --  pragma Suppress(Elaboration_Check);             -- (2)
28417   begin
28418     X1 := Pack2.F2 + 1;                --  Elab. call (2)
28419   end;
28420 end Pack1;
28422 with Pack1;
28423 package body Pack2 is
28424   function F2 return Integer is
28425   begin
28426      return Pack1.F1;
28427   end F2;
28428   function Pure (x : integer) return integer is
28429   begin
28430      return x ** 3 - 3 * x;
28431   end;
28432 end Pack2;
28434 with Pack1, Ada.Text_IO;
28435 procedure Proc3 is
28436 begin
28437   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
28438 end Proc3;
28439 @end example
28441 In the absence of any pragmas, an attempt to bind this program produces
28442 the following diagnostics:
28444 @example
28445 error: elaboration circularity detected
28446 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
28447 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
28448 info:       recompile "pack1 (body)" with -gnatel for full details
28449 info:          "pack1 (body)"
28450 info:             must be elaborated along with its spec:
28451 info:          "pack1 (spec)"
28452 info:             which is withed by:
28453 info:          "pack2 (body)"
28454 info:             which must be elaborated along with its spec:
28455 info:          "pack2 (spec)"
28456 info:             which is withed by:
28457 info:          "pack1 (body)"
28458 @end example
28460 The sources of the circularity are the two calls to @cite{Pack2.Pure} and
28461 @cite{Pack2.F2} in the body of @cite{Pack1}. We can see that the call to
28462 F2 is safe, even though F2 calls F1, because the call appears after the
28463 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
28464 remove the warning on the call. It is also possible to use pragma (2)
28465 because there are no other potentially unsafe calls in the block.
28467 The call to @cite{Pure} is safe because this function does not depend on the
28468 state of @cite{Pack2}. Therefore any call to this function is safe, and it
28469 is correct to place pragma (3) in the corresponding package spec.
28471 Finally, we could place pragma (4) in the spec of @cite{Pack2} to disable
28472 warnings on all calls to functions declared therein. Note that this is not
28473 necessarily safe, and requires more detailed examination of the subprogram
28474 bodies involved. In particular, a call to @cite{F2} requires that @cite{F1}
28475 be already elaborated.
28476 @end itemize
28478 It is hard to generalize on which of these four approaches should be
28479 taken. Obviously if it is possible to fix the program so that the default
28480 treatment works, this is preferable, but this may not always be practical.
28481 It is certainly simple enough to use @emph{-gnatE}
28482 but the danger in this case is that, even if the GNAT binder
28483 finds a correct elaboration order, it may not always do so,
28484 and certainly a binder from another Ada compiler might not. A
28485 combination of testing and analysis (for which the
28486 information messages generated with the @emph{-gnatel}
28487 switch can be useful) must be used to ensure that the program is free
28488 of errors. One switch that is useful in this testing is the
28489 @emph{-p (pessimistic elaboration order)} switch for @cite{gnatbind}.
28490 Normally the binder tries to find an order that has the best chance
28491 of avoiding elaboration problems. However, if this switch is used, the binder
28492 plays a devil's advocate role, and tries to choose the order that
28493 has the best chance of failing. If your program works even with this
28494 switch, then it has a better chance of being error free, but this is still
28495 not a guarantee.
28497 For an example of this approach in action, consider the C-tests (executable
28498 tests) from the ACATS suite. If these are compiled and run with the default
28499 treatment, then all but one of them succeed without generating any error
28500 diagnostics from the binder. However, there is one test that fails, and
28501 this is not surprising, because the whole point of this test is to ensure
28502 that the compiler can handle cases where it is impossible to determine
28503 a correct order statically, and it checks that an exception is indeed
28504 raised at run time.
28506 This one test must be compiled and run using the @emph{-gnatE}
28507 switch, and then it passes. Alternatively, the entire suite can
28508 be run using this switch. It is never wrong to run with the dynamic
28509 elaboration switch if your code is correct, and we assume that the
28510 C-tests are indeed correct (it is less efficient, but efficiency is
28511 not a factor in running the ACATS tests.)
28513 @node Elaboration for Indirect Calls,Summary of Procedures for Elaboration Control,What to Do If the Default Elaboration Behavior Fails,Elaboration Order Handling in GNAT
28514 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id12}@anchor{244}@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-for-indirect-calls}@anchor{245}
28515 @section Elaboration for Indirect Calls
28518 @geindex Dispatching calls
28520 @geindex Indirect calls
28522 In rare cases, the static elaboration model fails to prevent
28523 dispatching calls to not-yet-elaborated subprograms. In such cases, we
28524 fall back to run-time checks; premature calls to any primitive
28525 operation of a tagged type before the body of the operation has been
28526 elaborated will raise @cite{Program_Error}.
28528 Access-to-subprogram types, however, are handled conservatively in many
28529 cases. This was not true in earlier versions of the compiler; you can use
28530 the @emph{-gnatd.U} debug switch to revert to the old behavior if the new
28531 conservative behavior causes elaboration cycles. Here, 'conservative' means
28532 that if you do @cite{P'Access} during elaboration, the compiler will normally
28533 assume that you might call @cite{P} indirectly during elaboration, so it adds an
28534 implicit @cite{pragma Elaborate_All} on the library unit containing @cite{P}. The
28535 @emph{-gnatd.U} switch is safe if you know there are no such calls. If the
28536 program worked before, it will continue to work with @emph{-gnatd.U}. But beware
28537 that code modifications such as adding an indirect call can cause erroneous
28538 behavior in the presence of @emph{-gnatd.U}.
28540 These implicit Elaborate_All pragmas are not added in all cases, because
28541 they cause elaboration cycles in certain common code patterns. If you want
28542 even more conservative handling of P'Access, you can use the @emph{-gnatd.o}
28543 switch.
28545 See @cite{debug.adb} for documentation on the @emph{-gnatd...} debug switches.
28547 @node Summary of Procedures for Elaboration Control,Other Elaboration Order Considerations,Elaboration for Indirect Calls,Elaboration Order Handling in GNAT
28548 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id13}@anchor{246}@anchor{gnat_ugn/elaboration_order_handling_in_gnat summary-of-procedures-for-elaboration-control}@anchor{247}
28549 @section Summary of Procedures for Elaboration Control
28552 @geindex Elaboration control
28554 First, compile your program with the default options, using none of
28555 the special elaboration-control switches. If the binder successfully
28556 binds your program, then you can be confident that, apart from issues
28557 raised by the use of access-to-subprogram types and dynamic dispatching,
28558 the program is free of elaboration errors. If it is important that the
28559 program be portable to other compilers than GNAT, then use the
28560 @emph{-gnatel}
28561 switch to generate messages about missing @cite{Elaborate} or
28562 @cite{Elaborate_All} pragmas, and supply the missing pragmas.
28564 If the program fails to bind using the default static elaboration
28565 handling, then you can fix the program to eliminate the binder
28566 message, or recompile the entire program with the
28567 @emph{-gnatE} switch to generate dynamic elaboration checks,
28568 and, if you are sure there really are no elaboration problems,
28569 use a global pragma @cite{Suppress (Elaboration_Check)}.
28571 @node Other Elaboration Order Considerations,Determining the Chosen Elaboration Order,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
28572 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id14}@anchor{248}@anchor{gnat_ugn/elaboration_order_handling_in_gnat other-elaboration-order-considerations}@anchor{249}
28573 @section Other Elaboration Order Considerations
28576 This section has been entirely concerned with the issue of finding a valid
28577 elaboration order, as defined by the Ada Reference Manual. In a case
28578 where several elaboration orders are valid, the task is to find one
28579 of the possible valid elaboration orders (and the static model in GNAT
28580 will ensure that this is achieved).
28582 The purpose of the elaboration rules in the Ada Reference Manual is to
28583 make sure that no entity is accessed before it has been elaborated. For
28584 a subprogram, this means that the spec and body must have been elaborated
28585 before the subprogram is called. For an object, this means that the object
28586 must have been elaborated before its value is read or written. A violation
28587 of either of these two requirements is an access before elaboration order,
28588 and this section has been all about avoiding such errors.
28590 In the case where more than one order of elaboration is possible, in the
28591 sense that access before elaboration errors are avoided, then any one of
28592 the orders is 'correct' in the sense that it meets the requirements of
28593 the Ada Reference Manual, and no such error occurs.
28595 However, it may be the case for a given program, that there are
28596 constraints on the order of elaboration that come not from consideration
28597 of avoiding elaboration errors, but rather from extra-lingual logic
28598 requirements. Consider this example:
28600 @example
28601 with Init_Constants;
28602 package Constants is
28603    X : Integer := 0;
28604    Y : Integer := 0;
28605 end Constants;
28607 package Init_Constants is
28608    procedure P; --* require a body*
28609 end Init_Constants;
28611 with Constants;
28612 package body Init_Constants is
28613    procedure P is begin null; end;
28614 begin
28615    Constants.X := 3;
28616    Constants.Y := 4;
28617 end Init_Constants;
28619 with Constants;
28620 package Calc is
28621    Z : Integer := Constants.X + Constants.Y;
28622 end Calc;
28624 with Calc;
28625 with Text_IO; use Text_IO;
28626 procedure Main is
28627 begin
28628    Put_Line (Calc.Z'Img);
28629 end Main;
28630 @end example
28632 In this example, there is more than one valid order of elaboration. For
28633 example both the following are correct orders:
28635 @example
28636 Init_Constants spec
28637 Constants spec
28638 Calc spec
28639 Init_Constants body
28640 Main body
28641 @end example
28645 @example
28646 Init_Constants spec
28647 Init_Constants body
28648 Constants spec
28649 Calc spec
28650 Main body
28651 @end example
28653 There is no language rule to prefer one or the other, both are correct
28654 from an order of elaboration point of view. But the programmatic effects
28655 of the two orders are very different. In the first, the elaboration routine
28656 of @cite{Calc} initializes @cite{Z} to zero, and then the main program
28657 runs with this value of zero. But in the second order, the elaboration
28658 routine of @cite{Calc} runs after the body of Init_Constants has set
28659 @cite{X} and @cite{Y} and thus @cite{Z} is set to 7 before @cite{Main} runs.
28661 One could perhaps by applying pretty clever non-artificial intelligence
28662 to the situation guess that it is more likely that the second order of
28663 elaboration is the one desired, but there is no formal linguistic reason
28664 to prefer one over the other. In fact in this particular case, GNAT will
28665 prefer the second order, because of the rule that bodies are elaborated
28666 as soon as possible, but it's just luck that this is what was wanted
28667 (if indeed the second order was preferred).
28669 If the program cares about the order of elaboration routines in a case like
28670 this, it is important to specify the order required. In this particular
28671 case, that could have been achieved by adding to the spec of Calc:
28673 @example
28674 pragma Elaborate_All (Constants);
28675 @end example
28677 which requires that the body (if any) and spec of @cite{Constants},
28678 as well as the body and spec of any unit @emph{with}ed by
28679 @cite{Constants} be elaborated before @cite{Calc} is elaborated.
28681 Clearly no automatic method can always guess which alternative you require,
28682 and if you are working with legacy code that had constraints of this kind
28683 which were not properly specified by adding @cite{Elaborate} or
28684 @cite{Elaborate_All} pragmas, then indeed it is possible that two different
28685 compilers can choose different orders.
28687 However, GNAT does attempt to diagnose the common situation where there
28688 are uninitialized variables in the visible part of a package spec, and the
28689 corresponding package body has an elaboration block that directly or
28690 indirectly initialized one or more of these variables. This is the situation
28691 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
28692 a warning that suggests this addition if it detects this situation.
28694 The @cite{gnatbind} @emph{-p} switch may be useful in smoking
28695 out problems. This switch causes bodies to be elaborated as late as possible
28696 instead of as early as possible. In the example above, it would have forced
28697 the choice of the first elaboration order. If you get different results
28698 when using this switch, and particularly if one set of results is right,
28699 and one is wrong as far as you are concerned, it shows that you have some
28700 missing @cite{Elaborate} pragmas. For the example above, we have the
28701 following output:
28703 @example
28704 $ gnatmake -f -q main
28705 $ main
28707 $ gnatmake -f -q main -bargs -p
28708 $ main
28710 @end example
28712 It is of course quite unlikely that both these results are correct, so
28713 it is up to you in a case like this to investigate the source of the
28714 difference, by looking at the two elaboration orders that are chosen,
28715 and figuring out which is correct, and then adding the necessary
28716 @cite{Elaborate} or @cite{Elaborate_All} pragmas to ensure the desired order.
28718 @node Determining the Chosen Elaboration Order,,Other Elaboration Order Considerations,Elaboration Order Handling in GNAT
28719 @anchor{gnat_ugn/elaboration_order_handling_in_gnat determining-the-chosen-elaboration-order}@anchor{24a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id15}@anchor{24b}
28720 @section Determining the Chosen Elaboration Order
28723 To see the elaboration order that the binder chooses, you can look at
28724 the last part of the file:@cite{b~xxx.adb} binder output file. Here is an example:
28726 @example
28727 System.Soft_Links'Elab_Body;
28728 E14 := True;
28729 System.Secondary_Stack'Elab_Body;
28730 E18 := True;
28731 System.Exception_Table'Elab_Body;
28732 E24 := True;
28733 Ada.Io_Exceptions'Elab_Spec;
28734 E67 := True;
28735 Ada.Tags'Elab_Spec;
28736 Ada.Streams'Elab_Spec;
28737 E43 := True;
28738 Interfaces.C'Elab_Spec;
28739 E69 := True;
28740 System.Finalization_Root'Elab_Spec;
28741 E60 := True;
28742 System.Os_Lib'Elab_Body;
28743 E71 := True;
28744 System.Finalization_Implementation'Elab_Spec;
28745 System.Finalization_Implementation'Elab_Body;
28746 E62 := True;
28747 Ada.Finalization'Elab_Spec;
28748 E58 := True;
28749 Ada.Finalization.List_Controller'Elab_Spec;
28750 E76 := True;
28751 System.File_Control_Block'Elab_Spec;
28752 E74 := True;
28753 System.File_Io'Elab_Body;
28754 E56 := True;
28755 Ada.Tags'Elab_Body;
28756 E45 := True;
28757 Ada.Text_Io'Elab_Spec;
28758 Ada.Text_Io'Elab_Body;
28759 E07 := True;
28760 @end example
28762 Here Elab_Spec elaborates the spec
28763 and Elab_Body elaborates the body. The assignments to the @code{E@emph{xx}} flags
28764 flag that the corresponding body is now elaborated.
28766 You can also ask the binder to generate a more
28767 readable list of the elaboration order using the
28768 @cite{-l} switch when invoking the binder. Here is
28769 an example of the output generated by this switch:
28771 @example
28772 ada (spec)
28773 interfaces (spec)
28774 system (spec)
28775 system.case_util (spec)
28776 system.case_util (body)
28777 system.concat_2 (spec)
28778 system.concat_2 (body)
28779 system.concat_3 (spec)
28780 system.concat_3 (body)
28781 system.htable (spec)
28782 system.parameters (spec)
28783 system.parameters (body)
28784 system.crtl (spec)
28785 interfaces.c_streams (spec)
28786 interfaces.c_streams (body)
28787 system.restrictions (spec)
28788 system.restrictions (body)
28789 system.standard_library (spec)
28790 system.exceptions (spec)
28791 system.exceptions (body)
28792 system.storage_elements (spec)
28793 system.storage_elements (body)
28794 system.secondary_stack (spec)
28795 system.stack_checking (spec)
28796 system.stack_checking (body)
28797 system.string_hash (spec)
28798 system.string_hash (body)
28799 system.htable (body)
28800 system.strings (spec)
28801 system.strings (body)
28802 system.traceback (spec)
28803 system.traceback (body)
28804 system.traceback_entries (spec)
28805 system.traceback_entries (body)
28806 ada.exceptions (spec)
28807 ada.exceptions.last_chance_handler (spec)
28808 system.soft_links (spec)
28809 system.soft_links (body)
28810 ada.exceptions.last_chance_handler (body)
28811 system.secondary_stack (body)
28812 system.exception_table (spec)
28813 system.exception_table (body)
28814 ada.io_exceptions (spec)
28815 ada.tags (spec)
28816 ada.streams (spec)
28817 interfaces.c (spec)
28818 interfaces.c (body)
28819 system.finalization_root (spec)
28820 system.finalization_root (body)
28821 system.memory (spec)
28822 system.memory (body)
28823 system.standard_library (body)
28824 system.os_lib (spec)
28825 system.os_lib (body)
28826 system.unsigned_types (spec)
28827 system.stream_attributes (spec)
28828 system.stream_attributes (body)
28829 system.finalization_implementation (spec)
28830 system.finalization_implementation (body)
28831 ada.finalization (spec)
28832 ada.finalization (body)
28833 ada.finalization.list_controller (spec)
28834 ada.finalization.list_controller (body)
28835 system.file_control_block (spec)
28836 system.file_io (spec)
28837 system.file_io (body)
28838 system.val_uns (spec)
28839 system.val_util (spec)
28840 system.val_util (body)
28841 system.val_uns (body)
28842 system.wch_con (spec)
28843 system.wch_con (body)
28844 system.wch_cnv (spec)
28845 system.wch_jis (spec)
28846 system.wch_jis (body)
28847 system.wch_cnv (body)
28848 system.wch_stw (spec)
28849 system.wch_stw (body)
28850 ada.tags (body)
28851 ada.exceptions (body)
28852 ada.text_io (spec)
28853 ada.text_io (body)
28854 text_io (spec)
28855 gdbstr (body)
28856 @end example
28858 @node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
28859 @anchor{gnat_ugn/inline_assembler inline-assembler}@anchor{10}@anchor{gnat_ugn/inline_assembler doc}@anchor{24c}@anchor{gnat_ugn/inline_assembler id1}@anchor{24d}
28860 @chapter Inline Assembler
28863 @geindex Inline Assembler
28865 If you need to write low-level software that interacts directly
28866 with the hardware, Ada provides two ways to incorporate assembly
28867 language code into your program.  First, you can import and invoke
28868 external routines written in assembly language, an Ada feature fully
28869 supported by GNAT.  However, for small sections of code it may be simpler
28870 or more efficient to include assembly language statements directly
28871 in your Ada source program, using the facilities of the implementation-defined
28872 package @cite{System.Machine_Code}, which incorporates the gcc
28873 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
28874 including the following:
28877 @itemize *
28879 @item 
28880 No need to use non-Ada tools
28882 @item 
28883 Consistent interface over different targets
28885 @item 
28886 Automatic usage of the proper calling conventions
28888 @item 
28889 Access to Ada constants and variables
28891 @item 
28892 Definition of intrinsic routines
28894 @item 
28895 Possibility of inlining a subprogram comprising assembler code
28897 @item 
28898 Code optimizer can take Inline Assembler code into account
28899 @end itemize
28901 This appendix presents a series of examples to show you how to use
28902 the Inline Assembler.  Although it focuses on the Intel x86,
28903 the general approach applies also to other processors.
28904 It is assumed that you are familiar with Ada
28905 and with assembly language programming.
28907 @menu
28908 * Basic Assembler Syntax:: 
28909 * A Simple Example of Inline Assembler:: 
28910 * Output Variables in Inline Assembler:: 
28911 * Input Variables in Inline Assembler:: 
28912 * Inlining Inline Assembler Code:: 
28913 * Other Asm Functionality:: 
28915 @end menu
28917 @node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
28918 @anchor{gnat_ugn/inline_assembler id2}@anchor{24e}@anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{24f}
28919 @section Basic Assembler Syntax
28922 The assembler used by GNAT and gcc is based not on the Intel assembly
28923 language, but rather on a language that descends from the AT&T Unix
28924 assembler @emph{as} (and which is often referred to as 'AT&T syntax').
28925 The following table summarizes the main features of @emph{as} syntax
28926 and points out the differences from the Intel conventions.
28927 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
28928 pre-processor) documentation for further information.
28931 @display
28932 @emph{Register names}@w{ }
28933 @display
28934 gcc / @emph{as}: Prefix with '%'; for example @cite{%eax}@w{ }
28935 Intel: No extra punctuation; for example @cite{eax}@w{ }
28936 @end display
28937 @end display
28942 @display
28943 @emph{Immediate operand}@w{ }
28944 @display
28945 gcc / @emph{as}: Prefix with '$'; for example @cite{$4}@w{ }
28946 Intel: No extra punctuation; for example @cite{4}@w{ }
28947 @end display
28948 @end display
28953 @display
28954 @emph{Address}@w{ }
28955 @display
28956 gcc / @emph{as}: Prefix with '$'; for example @cite{$loc}@w{ }
28957 Intel: No extra punctuation; for example @cite{loc}@w{ }
28958 @end display
28959 @end display
28964 @display
28965 @emph{Memory contents}@w{ }
28966 @display
28967 gcc / @emph{as}: No extra punctuation; for example @cite{loc}@w{ }
28968 Intel: Square brackets; for example @cite{[loc]}@w{ }
28969 @end display
28970 @end display
28975 @display
28976 @emph{Register contents}@w{ }
28977 @display
28978 gcc / @emph{as}: Parentheses; for example @cite{(%eax)}@w{ }
28979 Intel: Square brackets; for example @cite{[eax]}@w{ }
28980 @end display
28981 @end display
28986 @display
28987 @emph{Hexadecimal numbers}@w{ }
28988 @display
28989 gcc / @emph{as}: Leading '0x' (C language syntax); for example @cite{0xA0}@w{ }
28990 Intel: Trailing 'h'; for example @cite{A0h}@w{ }
28991 @end display
28992 @end display
28997 @display
28998 @emph{Operand size}@w{ }
28999 @display
29000 gcc / @emph{as}: Explicit in op code; for example @cite{movw} to move a 16-bit word@w{ }
29001 Intel: Implicit, deduced by assembler; for example @cite{mov}@w{ }
29002 @end display
29003 @end display
29008 @display
29009 @emph{Instruction repetition}@w{ }
29010 @display
29011 gcc / @emph{as}: Split into two lines; for example@w{ }
29012 @display
29013 @cite{rep}@w{ }
29014 @cite{stosl}@w{ }
29015 @end display
29016 Intel: Keep on one line; for example @cite{rep stosl}@w{ }
29017 @end display
29018 @end display
29023 @display
29024 @emph{Order of operands}@w{ }
29025 @display
29026 gcc / @emph{as}: Source first; for example @cite{movw $4@comma{} %eax}@w{ }
29027 Intel: Destination first; for example @cite{mov eax@comma{} 4}@w{ }
29028 @end display
29029 @end display
29033 @node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
29034 @anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{250}@anchor{gnat_ugn/inline_assembler id3}@anchor{251}
29035 @section A Simple Example of Inline Assembler
29038 The following example will generate a single assembly language statement,
29039 @cite{nop}, which does nothing.  Despite its lack of run-time effect,
29040 the example will be useful in illustrating the basics of
29041 the Inline Assembler facility.
29043 @quotation
29045 @example
29046 with System.Machine_Code; use System.Machine_Code;
29047 procedure Nothing is
29048 begin
29049    Asm ("nop");
29050 end Nothing;
29051 @end example
29052 @end quotation
29054 @cite{Asm} is a procedure declared in package @cite{System.Machine_Code};
29055 here it takes one parameter, a @emph{template string} that must be a static
29056 expression and that will form the generated instruction.
29057 @cite{Asm} may be regarded as a compile-time procedure that parses
29058 the template string and additional parameters (none here),
29059 from which it generates a sequence of assembly language instructions.
29061 The examples in this chapter will illustrate several of the forms
29062 for invoking @cite{Asm}; a complete specification of the syntax
29063 is found in the @cite{Machine_Code_Insertions} section of the
29064 @cite{GNAT Reference Manual}.
29066 Under the standard GNAT conventions, the @cite{Nothing} procedure
29067 should be in a file named @code{nothing.adb}.
29068 You can build the executable in the usual way:
29070 @quotation
29072 @example
29073 $ gnatmake nothing
29074 @end example
29075 @end quotation
29077 However, the interesting aspect of this example is not its run-time behavior
29078 but rather the generated assembly code.
29079 To see this output, invoke the compiler as follows:
29081 @quotation
29083 @example
29084 $  gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
29085 @end example
29086 @end quotation
29088 where the options are:
29091 @itemize *
29093 @item 
29095 @table @asis
29097 @item @code{-c}
29099 compile only (no bind or link)
29100 @end table
29102 @item 
29104 @table @asis
29106 @item @code{-S}
29108 generate assembler listing
29109 @end table
29111 @item 
29113 @table @asis
29115 @item @code{-fomit-frame-pointer}
29117 do not set up separate stack frames
29118 @end table
29120 @item 
29122 @table @asis
29124 @item @code{-gnatp}
29126 do not add runtime checks
29127 @end table
29128 @end itemize
29130 This gives a human-readable assembler version of the code. The resulting
29131 file will have the same name as the Ada source file, but with a @cite{.s}
29132 extension. In our example, the file @code{nothing.s} has the following
29133 contents:
29135 @quotation
29137 @example
29138 .file "nothing.adb"
29139 gcc2_compiled.:
29140 ___gnu_compiled_ada:
29141 .text
29142    .align 4
29143 .globl __ada_nothing
29144 __ada_nothing:
29145 #APP
29146    nop
29147 #NO_APP
29148    jmp L1
29149    .align 2,0x90
29151    ret
29152 @end example
29153 @end quotation
29155 The assembly code you included is clearly indicated by
29156 the compiler, between the @cite{#APP} and @cite{#NO_APP}
29157 delimiters. The character before the 'APP' and 'NOAPP'
29158 can differ on different targets. For example, GNU/Linux uses '#APP' while
29159 on NT you will see '/APP'.
29161 If you make a mistake in your assembler code (such as using the
29162 wrong size modifier, or using a wrong operand for the instruction) GNAT
29163 will report this error in a temporary file, which will be deleted when
29164 the compilation is finished.  Generating an assembler file will help
29165 in such cases, since you can assemble this file separately using the
29166 @emph{as} assembler that comes with gcc.
29168 Assembling the file using the command
29170 @quotation
29172 @example
29173 $ as nothing.s
29174 @end example
29175 @end quotation
29177 will give you error messages whose lines correspond to the assembler
29178 input file, so you can easily find and correct any mistakes you made.
29179 If there are no errors, @emph{as} will generate an object file
29180 @code{nothing.out}.
29182 @node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
29183 @anchor{gnat_ugn/inline_assembler id4}@anchor{252}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{253}
29184 @section Output Variables in Inline Assembler
29187 The examples in this section, showing how to access the processor flags,
29188 illustrate how to specify the destination operands for assembly language
29189 statements.
29191 @quotation
29193 @example
29194 with Interfaces; use Interfaces;
29195 with Ada.Text_IO; use Ada.Text_IO;
29196 with System.Machine_Code; use System.Machine_Code;
29197 procedure Get_Flags is
29198    Flags : Unsigned_32;
29199    use ASCII;
29200 begin
29201    Asm ("pushfl"          & LF & HT & -- push flags on stack
29202         "popl %%eax"      & LF & HT & -- load eax with flags
29203         "movl %%eax, %0",             -- store flags in variable
29204         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29205    Put_Line ("Flags register:" & Flags'Img);
29206 end Get_Flags;
29207 @end example
29208 @end quotation
29210 In order to have a nicely aligned assembly listing, we have separated
29211 multiple assembler statements in the Asm template string with linefeed
29212 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
29213 The resulting section of the assembly output file is:
29215 @quotation
29217 @example
29218 #APP
29219    pushfl
29220    popl %eax
29221    movl %eax, -40(%ebp)
29222 #NO_APP
29223 @end example
29224 @end quotation
29226 It would have been legal to write the Asm invocation as:
29228 @quotation
29230 @example
29231 Asm ("pushfl popl %%eax movl %%eax, %0")
29232 @end example
29233 @end quotation
29235 but in the generated assembler file, this would come out as:
29237 @quotation
29239 @example
29240 #APP
29241    pushfl popl %eax movl %eax, -40(%ebp)
29242 #NO_APP
29243 @end example
29244 @end quotation
29246 which is not so convenient for the human reader.
29248 We use Ada comments
29249 at the end of each line to explain what the assembler instructions
29250 actually do.  This is a useful convention.
29252 When writing Inline Assembler instructions, you need to precede each register
29253 and variable name with a percent sign.  Since the assembler already requires
29254 a percent sign at the beginning of a register name, you need two consecutive
29255 percent signs for such names in the Asm template string, thus @cite{%%eax}.
29256 In the generated assembly code, one of the percent signs will be stripped off.
29258 Names such as @cite{%0}, @cite{%1}, @cite{%2}, etc., denote input or output
29259 variables: operands you later define using @cite{Input} or @cite{Output}
29260 parameters to @cite{Asm}.
29261 An output variable is illustrated in
29262 the third statement in the Asm template string:
29264 @quotation
29266 @example
29267 movl %%eax, %0
29268 @end example
29269 @end quotation
29271 The intent is to store the contents of the eax register in a variable that can
29272 be accessed in Ada.  Simply writing @cite{movl %%eax@comma{} Flags} would not
29273 necessarily work, since the compiler might optimize by using a register
29274 to hold Flags, and the expansion of the @cite{movl} instruction would not be
29275 aware of this optimization.  The solution is not to store the result directly
29276 but rather to advise the compiler to choose the correct operand form;
29277 that is the purpose of the @cite{%0} output variable.
29279 Information about the output variable is supplied in the @cite{Outputs}
29280 parameter to @cite{Asm}:
29282 @quotation
29284 @example
29285 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29286 @end example
29287 @end quotation
29289 The output is defined by the @cite{Asm_Output} attribute of the target type;
29290 the general format is
29292 @quotation
29294 @example
29295 Type'Asm_Output (constraint_string, variable_name)
29296 @end example
29297 @end quotation
29299 The constraint string directs the compiler how
29300 to store/access the associated variable.  In the example
29302 @quotation
29304 @example
29305 Unsigned_32'Asm_Output ("=m", Flags);
29306 @end example
29307 @end quotation
29309 the @cite{"m"} (memory) constraint tells the compiler that the variable
29310 @cite{Flags} should be stored in a memory variable, thus preventing
29311 the optimizer from keeping it in a register.  In contrast,
29313 @quotation
29315 @example
29316 Unsigned_32'Asm_Output ("=r", Flags);
29317 @end example
29318 @end quotation
29320 uses the @cite{"r"} (register) constraint, telling the compiler to
29321 store the variable in a register.
29323 If the constraint is preceded by the equal character '=', it tells
29324 the compiler that the variable will be used to store data into it.
29326 In the @cite{Get_Flags} example, we used the @cite{"g"} (global) constraint,
29327 allowing the optimizer to choose whatever it deems best.
29329 There are a fairly large number of constraints, but the ones that are
29330 most useful (for the Intel x86 processor) are the following:
29332 @quotation
29335 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
29336 @item
29338 @emph{=}
29340 @tab
29342 output constraint
29344 @item
29346 @emph{g}
29348 @tab
29350 global (i.e., can be stored anywhere)
29352 @item
29354 @emph{m}
29356 @tab
29358 in memory
29360 @item
29362 @emph{I}
29364 @tab
29366 a constant
29368 @item
29370 @emph{a}
29372 @tab
29374 use eax
29376 @item
29378 @emph{b}
29380 @tab
29382 use ebx
29384 @item
29386 @emph{c}
29388 @tab
29390 use ecx
29392 @item
29394 @emph{d}
29396 @tab
29398 use edx
29400 @item
29402 @emph{S}
29404 @tab
29406 use esi
29408 @item
29410 @emph{D}
29412 @tab
29414 use edi
29416 @item
29418 @emph{r}
29420 @tab
29422 use one of eax, ebx, ecx or edx
29424 @item
29426 @emph{q}
29428 @tab
29430 use one of eax, ebx, ecx, edx, esi or edi
29432 @end multitable
29434 @end quotation
29436 The full set of constraints is described in the gcc and @emph{as}
29437 documentation; note that it is possible to combine certain constraints
29438 in one constraint string.
29440 You specify the association of an output variable with an assembler operand
29441 through the @code{%@emph{n}} notation, where @emph{n} is a non-negative
29442 integer.  Thus in
29444 @quotation
29446 @example
29447 Asm ("pushfl"          & LF & HT & -- push flags on stack
29448      "popl %%eax"      & LF & HT & -- load eax with flags
29449      "movl %%eax, %0",             -- store flags in variable
29450      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29451 @end example
29452 @end quotation
29454 @cite{%0} will be replaced in the expanded code by the appropriate operand,
29455 whatever
29456 the compiler decided for the @cite{Flags} variable.
29458 In general, you may have any number of output variables:
29461 @itemize *
29463 @item 
29464 Count the operands starting at 0; thus @cite{%0}, @cite{%1}, etc.
29466 @item 
29467 Specify the @cite{Outputs} parameter as a parenthesized comma-separated list
29468 of @cite{Asm_Output} attributes
29469 @end itemize
29471 For example:
29473 @quotation
29475 @example
29476 Asm ("movl %%eax, %0" & LF & HT &
29477      "movl %%ebx, %1" & LF & HT &
29478      "movl %%ecx, %2",
29479      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
29480                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
29481                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
29482 @end example
29483 @end quotation
29485 where @cite{Var_A}, @cite{Var_B}, and @cite{Var_C} are variables
29486 in the Ada program.
29488 As a variation on the @cite{Get_Flags} example, we can use the constraints
29489 string to direct the compiler to store the eax register into the @cite{Flags}
29490 variable, instead of including the store instruction explicitly in the
29491 @cite{Asm} template string:
29493 @quotation
29495 @example
29496 with Interfaces; use Interfaces;
29497 with Ada.Text_IO; use Ada.Text_IO;
29498 with System.Machine_Code; use System.Machine_Code;
29499 procedure Get_Flags_2 is
29500    Flags : Unsigned_32;
29501    use ASCII;
29502 begin
29503    Asm ("pushfl"      & LF & HT & -- push flags on stack
29504         "popl %%eax",             -- save flags in eax
29505         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
29506    Put_Line ("Flags register:" & Flags'Img);
29507 end Get_Flags_2;
29508 @end example
29509 @end quotation
29511 The @cite{"a"} constraint tells the compiler that the @cite{Flags}
29512 variable will come from the eax register. Here is the resulting code:
29514 @quotation
29516 @example
29517 #APP
29518    pushfl
29519    popl %eax
29520 #NO_APP
29521    movl %eax,-40(%ebp)
29522 @end example
29523 @end quotation
29525 The compiler generated the store of eax into Flags after
29526 expanding the assembler code.
29528 Actually, there was no need to pop the flags into the eax register;
29529 more simply, we could just pop the flags directly into the program variable:
29531 @quotation
29533 @example
29534 with Interfaces; use Interfaces;
29535 with Ada.Text_IO; use Ada.Text_IO;
29536 with System.Machine_Code; use System.Machine_Code;
29537 procedure Get_Flags_3 is
29538    Flags : Unsigned_32;
29539    use ASCII;
29540 begin
29541    Asm ("pushfl"  & LF & HT & -- push flags on stack
29542         "pop %0",             -- save flags in Flags
29543         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29544    Put_Line ("Flags register:" & Flags'Img);
29545 end Get_Flags_3;
29546 @end example
29547 @end quotation
29549 @node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
29550 @anchor{gnat_ugn/inline_assembler id5}@anchor{254}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{255}
29551 @section Input Variables in Inline Assembler
29554 The example in this section illustrates how to specify the source operands
29555 for assembly language statements.
29556 The program simply increments its input value by 1:
29558 @quotation
29560 @example
29561 with Interfaces; use Interfaces;
29562 with Ada.Text_IO; use Ada.Text_IO;
29563 with System.Machine_Code; use System.Machine_Code;
29564 procedure Increment is
29566    function Incr (Value : Unsigned_32) return Unsigned_32 is
29567       Result : Unsigned_32;
29568    begin
29569       Asm ("incl %0",
29570            Outputs => Unsigned_32'Asm_Output ("=a", Result),
29571            Inputs  => Unsigned_32'Asm_Input ("a", Value));
29572       return Result;
29573    end Incr;
29575    Value : Unsigned_32;
29577 begin
29578    Value := 5;
29579    Put_Line ("Value before is" & Value'Img);
29580    Value := Incr (Value);
29581   Put_Line ("Value after is" & Value'Img);
29582 end Increment;
29583 @end example
29584 @end quotation
29586 The @cite{Outputs} parameter to @cite{Asm} specifies
29587 that the result will be in the eax register and that it is to be stored
29588 in the @cite{Result} variable.
29590 The @cite{Inputs} parameter looks much like the @cite{Outputs} parameter,
29591 but with an @cite{Asm_Input} attribute.
29592 The @cite{"="} constraint, indicating an output value, is not present.
29594 You can have multiple input variables, in the same way that you can have more
29595 than one output variable.
29597 The parameter count (%0, %1) etc, still starts at the first output statement,
29598 and continues with the input statements.
29600 Just as the @cite{Outputs} parameter causes the register to be stored into the
29601 target variable after execution of the assembler statements, so does the
29602 @cite{Inputs} parameter cause its variable to be loaded into the register
29603 before execution of the assembler statements.
29605 Thus the effect of the @cite{Asm} invocation is:
29608 @itemize *
29610 @item 
29611 load the 32-bit value of @cite{Value} into eax
29613 @item 
29614 execute the @cite{incl %eax} instruction
29616 @item 
29617 store the contents of eax into the @cite{Result} variable
29618 @end itemize
29620 The resulting assembler file (with @emph{-O2} optimization) contains:
29622 @quotation
29624 @example
29625 _increment__incr.1:
29626    subl $4,%esp
29627    movl 8(%esp),%eax
29628 #APP
29629    incl %eax
29630 #NO_APP
29631    movl %eax,%edx
29632    movl %ecx,(%esp)
29633    addl $4,%esp
29634    ret
29635 @end example
29636 @end quotation
29638 @node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
29639 @anchor{gnat_ugn/inline_assembler id6}@anchor{256}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{257}
29640 @section Inlining Inline Assembler Code
29643 For a short subprogram such as the @cite{Incr} function in the previous
29644 section, the overhead of the call and return (creating / deleting the stack
29645 frame) can be significant, compared to the amount of code in the subprogram
29646 body.  A solution is to apply Ada's @cite{Inline} pragma to the subprogram,
29647 which directs the compiler to expand invocations of the subprogram at the
29648 point(s) of call, instead of setting up a stack frame for out-of-line calls.
29649 Here is the resulting program:
29651 @quotation
29653 @example
29654 with Interfaces; use Interfaces;
29655 with Ada.Text_IO; use Ada.Text_IO;
29656 with System.Machine_Code; use System.Machine_Code;
29657 procedure Increment_2 is
29659    function Incr (Value : Unsigned_32) return Unsigned_32 is
29660       Result : Unsigned_32;
29661    begin
29662       Asm ("incl %0",
29663            Outputs => Unsigned_32'Asm_Output ("=a", Result),
29664            Inputs  => Unsigned_32'Asm_Input ("a", Value));
29665       return Result;
29666    end Incr;
29667    pragma Inline (Increment);
29669    Value : Unsigned_32;
29671 begin
29672    Value := 5;
29673    Put_Line ("Value before is" & Value'Img);
29674    Value := Increment (Value);
29675    Put_Line ("Value after is" & Value'Img);
29676 end Increment_2;
29677 @end example
29678 @end quotation
29680 Compile the program with both optimization (@emph{-O2}) and inlining
29681 (@emph{-gnatn}) enabled.
29683 The @cite{Incr} function is still compiled as usual, but at the
29684 point in @cite{Increment} where our function used to be called:
29686 @quotation
29688 @example
29689 pushl %edi
29690 call _increment__incr.1
29691 @end example
29692 @end quotation
29694 the code for the function body directly appears:
29696 @quotation
29698 @example
29699 movl %esi,%eax
29700 #APP
29701    incl %eax
29702 #NO_APP
29703    movl %eax,%edx
29704 @end example
29705 @end quotation
29707 thus saving the overhead of stack frame setup and an out-of-line call.
29709 @node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
29710 @anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{258}@anchor{gnat_ugn/inline_assembler id7}@anchor{259}
29711 @section Other @cite{Asm} Functionality
29714 This section describes two important parameters to the @cite{Asm}
29715 procedure: @cite{Clobber}, which identifies register usage;
29716 and @cite{Volatile}, which inhibits unwanted optimizations.
29718 @menu
29719 * The Clobber Parameter:: 
29720 * The Volatile Parameter:: 
29722 @end menu
29724 @node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
29725 @anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{25a}@anchor{gnat_ugn/inline_assembler id8}@anchor{25b}
29726 @subsection The @cite{Clobber} Parameter
29729 One of the dangers of intermixing assembly language and a compiled language
29730 such as Ada is that the compiler needs to be aware of which registers are
29731 being used by the assembly code.  In some cases, such as the earlier examples,
29732 the constraint string is sufficient to indicate register usage (e.g.,
29733 @cite{"a"} for
29734 the eax register).  But more generally, the compiler needs an explicit
29735 identification of the registers that are used by the Inline Assembly
29736 statements.
29738 Using a register that the compiler doesn't know about
29739 could be a side effect of an instruction (like @cite{mull}
29740 storing its result in both eax and edx).
29741 It can also arise from explicit register usage in your
29742 assembly code; for example:
29744 @quotation
29746 @example
29747 Asm ("movl %0, %%ebx" & LF & HT &
29748      "movl %%ebx, %1",
29749      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29750      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
29751 @end example
29752 @end quotation
29754 where the compiler (since it does not analyze the @cite{Asm} template string)
29755 does not know you are using the ebx register.
29757 In such cases you need to supply the @cite{Clobber} parameter to @cite{Asm},
29758 to identify the registers that will be used by your assembly code:
29760 @quotation
29762 @example
29763 Asm ("movl %0, %%ebx" & LF & HT &
29764      "movl %%ebx, %1",
29765      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29766      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
29767      Clobber => "ebx");
29768 @end example
29769 @end quotation
29771 The Clobber parameter is a static string expression specifying the
29772 register(s) you are using.  Note that register names are @emph{not} prefixed
29773 by a percent sign. Also, if more than one register is used then their names
29774 are separated by commas; e.g., @cite{"eax@comma{} ebx"}
29776 The @cite{Clobber} parameter has several additional uses:
29779 @itemize *
29781 @item 
29782 Use 'register' name @cite{cc} to indicate that flags might have changed
29784 @item 
29785 Use 'register' name @cite{memory} if you changed a memory location
29786 @end itemize
29788 @node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
29789 @anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{25c}@anchor{gnat_ugn/inline_assembler id9}@anchor{25d}
29790 @subsection The @cite{Volatile} Parameter
29793 @geindex Volatile parameter
29795 Compiler optimizations in the presence of Inline Assembler may sometimes have
29796 unwanted effects.  For example, when an @cite{Asm} invocation with an input
29797 variable is inside a loop, the compiler might move the loading of the input
29798 variable outside the loop, regarding it as a one-time initialization.
29800 If this effect is not desired, you can disable such optimizations by setting
29801 the @cite{Volatile} parameter to @cite{True}; for example:
29803 @quotation
29805 @example
29806 Asm ("movl %0, %%ebx" & LF & HT &
29807      "movl %%ebx, %1",
29808      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
29809      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
29810      Clobber  => "ebx",
29811      Volatile => True);
29812 @end example
29813 @end quotation
29815 By default, @cite{Volatile} is set to @cite{False} unless there is no
29816 @cite{Outputs} parameter.
29818 Although setting @cite{Volatile} to @cite{True} prevents unwanted
29819 optimizations, it will also disable other optimizations that might be
29820 important for efficiency. In general, you should set @cite{Volatile}
29821 to @cite{True} only if the compiler's optimizations have created
29822 problems.
29824 @node GNU Free Documentation License,Index,Inline Assembler,Top
29825 @anchor{share/gnu_free_documentation_license gnu-fdl}@anchor{1}@anchor{share/gnu_free_documentation_license doc}@anchor{25e}@anchor{share/gnu_free_documentation_license gnu-free-documentation-license}@anchor{25f}
29826 @chapter GNU Free Documentation License
29829 Version 1.3, 3 November 2008
29831 Copyright  2000, 2001, 2002, 2007, 2008  Free Software Foundation, Inc
29832 @indicateurl{http://fsf.org/}
29834 Everyone is permitted to copy and distribute verbatim copies of this
29835 license document, but changing it is not allowed.
29837 @strong{Preamble}
29839 The purpose of this License is to make a manual, textbook, or other
29840 functional and useful document "free" in the sense of freedom: to
29841 assure everyone the effective freedom to copy and redistribute it,
29842 with or without modifying it, either commercially or noncommercially.
29843 Secondarily, this License preserves for the author and publisher a way
29844 to get credit for their work, while not being considered responsible
29845 for modifications made by others.
29847 This License is a kind of "copyleft", which means that derivative
29848 works of the document must themselves be free in the same sense.  It
29849 complements the GNU General Public License, which is a copyleft
29850 license designed for free software.
29852 We have designed this License in order to use it for manuals for free
29853 software, because free software needs free documentation: a free
29854 program should come with manuals providing the same freedoms that the
29855 software does.  But this License is not limited to software manuals;
29856 it can be used for any textual work, regardless of subject matter or
29857 whether it is published as a printed book.  We recommend this License
29858 principally for works whose purpose is instruction or reference.
29860 @strong{1. APPLICABILITY AND DEFINITIONS}
29862 This License applies to any manual or other work, in any medium, that
29863 contains a notice placed by the copyright holder saying it can be
29864 distributed under the terms of this License.  Such a notice grants a
29865 world-wide, royalty-free license, unlimited in duration, to use that
29866 work under the conditions stated herein.  The @strong{Document}, below,
29867 refers to any such manual or work.  Any member of the public is a
29868 licensee, and is addressed as "@strong{you}".  You accept the license if you
29869 copy, modify or distribute the work in a way requiring permission
29870 under copyright law.
29872 A "@strong{Modified Version}" of the Document means any work containing the
29873 Document or a portion of it, either copied verbatim, or with
29874 modifications and/or translated into another language.
29876 A "@strong{Secondary Section}" is a named appendix or a front-matter section of
29877 the Document that deals exclusively with the relationship of the
29878 publishers or authors of the Document to the Document's overall subject
29879 (or to related matters) and contains nothing that could fall directly
29880 within that overall subject.  (Thus, if the Document is in part a
29881 textbook of mathematics, a Secondary Section may not explain any
29882 mathematics.)  The relationship could be a matter of historical
29883 connection with the subject or with related matters, or of legal,
29884 commercial, philosophical, ethical or political position regarding
29885 them.
29887 The "@strong{Invariant Sections}" are certain Secondary Sections whose titles
29888 are designated, as being those of Invariant Sections, in the notice
29889 that says that the Document is released under this License.  If a
29890 section does not fit the above definition of Secondary then it is not
29891 allowed to be designated as Invariant.  The Document may contain zero
29892 Invariant Sections.  If the Document does not identify any Invariant
29893 Sections then there are none.
29895 The "@strong{Cover Texts}" are certain short passages of text that are listed,
29896 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
29897 the Document is released under this License.  A Front-Cover Text may
29898 be at most 5 words, and a Back-Cover Text may be at most 25 words.
29900 A "@strong{Transparent}" copy of the Document means a machine-readable copy,
29901 represented in a format whose specification is available to the
29902 general public, that is suitable for revising the document
29903 straightforwardly with generic text editors or (for images composed of
29904 pixels) generic paint programs or (for drawings) some widely available
29905 drawing editor, and that is suitable for input to text formatters or
29906 for automatic translation to a variety of formats suitable for input
29907 to text formatters.  A copy made in an otherwise Transparent file
29908 format whose markup, or absence of markup, has been arranged to thwart
29909 or discourage subsequent modification by readers is not Transparent.
29910 An image format is not Transparent if used for any substantial amount
29911 of text.  A copy that is not "Transparent" is called @strong{Opaque}.
29913 Examples of suitable formats for Transparent copies include plain
29914 ASCII without markup, Texinfo input format, LaTeX input format, SGML
29915 or XML using a publicly available DTD, and standard-conforming simple
29916 HTML, PostScript or PDF designed for human modification.  Examples of
29917 transparent image formats include PNG, XCF and JPG.  Opaque formats
29918 include proprietary formats that can be read and edited only by
29919 proprietary word processors, SGML or XML for which the DTD and/or
29920 processing tools are not generally available, and the
29921 machine-generated HTML, PostScript or PDF produced by some word
29922 processors for output purposes only.
29924 The "@strong{Title Page}" means, for a printed book, the title page itself,
29925 plus such following pages as are needed to hold, legibly, the material
29926 this License requires to appear in the title page.  For works in
29927 formats which do not have any title page as such, "Title Page" means
29928 the text near the most prominent appearance of the work's title,
29929 preceding the beginning of the body of the text.
29931 The "@strong{publisher}" means any person or entity that distributes
29932 copies of the Document to the public.
29934 A section "@strong{Entitled XYZ}" means a named subunit of the Document whose
29935 title either is precisely XYZ or contains XYZ in parentheses following
29936 text that translates XYZ in another language.  (Here XYZ stands for a
29937 specific section name mentioned below, such as "@strong{Acknowledgements}",
29938 "@strong{Dedications}", "@strong{Endorsements}", or "@strong{History}".)
29939 To "@strong{Preserve the Title}"
29940 of such a section when you modify the Document means that it remains a
29941 section "Entitled XYZ" according to this definition.
29943 The Document may include Warranty Disclaimers next to the notice which
29944 states that this License applies to the Document.  These Warranty
29945 Disclaimers are considered to be included by reference in this
29946 License, but only as regards disclaiming warranties: any other
29947 implication that these Warranty Disclaimers may have is void and has
29948 no effect on the meaning of this License.
29950 @strong{2. VERBATIM COPYING}
29952 You may copy and distribute the Document in any medium, either
29953 commercially or noncommercially, provided that this License, the
29954 copyright notices, and the license notice saying this License applies
29955 to the Document are reproduced in all copies, and that you add no other
29956 conditions whatsoever to those of this License.  You may not use
29957 technical measures to obstruct or control the reading or further
29958 copying of the copies you make or distribute.  However, you may accept
29959 compensation in exchange for copies.  If you distribute a large enough
29960 number of copies you must also follow the conditions in section 3.
29962 You may also lend copies, under the same conditions stated above, and
29963 you may publicly display copies.
29965 @strong{3. COPYING IN QUANTITY}
29967 If you publish printed copies (or copies in media that commonly have
29968 printed covers) of the Document, numbering more than 100, and the
29969 Document's license notice requires Cover Texts, you must enclose the
29970 copies in covers that carry, clearly and legibly, all these Cover
29971 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
29972 the back cover.  Both covers must also clearly and legibly identify
29973 you as the publisher of these copies.  The front cover must present
29974 the full title with all words of the title equally prominent and
29975 visible.  You may add other material on the covers in addition.
29976 Copying with changes limited to the covers, as long as they preserve
29977 the title of the Document and satisfy these conditions, can be treated
29978 as verbatim copying in other respects.
29980 If the required texts for either cover are too voluminous to fit
29981 legibly, you should put the first ones listed (as many as fit
29982 reasonably) on the actual cover, and continue the rest onto adjacent
29983 pages.
29985 If you publish or distribute Opaque copies of the Document numbering
29986 more than 100, you must either include a machine-readable Transparent
29987 copy along with each Opaque copy, or state in or with each Opaque copy
29988 a computer-network location from which the general network-using
29989 public has access to download using public-standard network protocols
29990 a complete Transparent copy of the Document, free of added material.
29991 If you use the latter option, you must take reasonably prudent steps,
29992 when you begin distribution of Opaque copies in quantity, to ensure
29993 that this Transparent copy will remain thus accessible at the stated
29994 location until at least one year after the last time you distribute an
29995 Opaque copy (directly or through your agents or retailers) of that
29996 edition to the public.
29998 It is requested, but not required, that you contact the authors of the
29999 Document well before redistributing any large number of copies, to give
30000 them a chance to provide you with an updated version of the Document.
30002 @strong{4. MODIFICATIONS}
30004 You may copy and distribute a Modified Version of the Document under
30005 the conditions of sections 2 and 3 above, provided that you release
30006 the Modified Version under precisely this License, with the Modified
30007 Version filling the role of the Document, thus licensing distribution
30008 and modification of the Modified Version to whoever possesses a copy
30009 of it.  In addition, you must do these things in the Modified Version:
30012 @enumerate A
30014 @item 
30015 Use in the Title Page (and on the covers, if any) a title distinct
30016 from that of the Document, and from those of previous versions
30017 (which should, if there were any, be listed in the History section
30018 of the Document).  You may use the same title as a previous version
30019 if the original publisher of that version gives permission.
30021 @item 
30022 List on the Title Page, as authors, one or more persons or entities
30023 responsible for authorship of the modifications in the Modified
30024 Version, together with at least five of the principal authors of the
30025 Document (all of its principal authors, if it has fewer than five),
30026 unless they release you from this requirement.
30028 @item 
30029 State on the Title page the name of the publisher of the
30030 Modified Version, as the publisher.
30032 @item 
30033 Preserve all the copyright notices of the Document.
30035 @item 
30036 Add an appropriate copyright notice for your modifications
30037 adjacent to the other copyright notices.
30039 @item 
30040 Include, immediately after the copyright notices, a license notice
30041 giving the public permission to use the Modified Version under the
30042 terms of this License, in the form shown in the Addendum below.
30044 @item 
30045 Preserve in that license notice the full lists of Invariant Sections
30046 and required Cover Texts given in the Document's license notice.
30048 @item 
30049 Include an unaltered copy of this License.
30051 @item 
30052 Preserve the section Entitled "History", Preserve its Title, and add
30053 to it an item stating at least the title, year, new authors, and
30054 publisher of the Modified Version as given on the Title Page.  If
30055 there is no section Entitled "History" in the Document, create one
30056 stating the title, year, authors, and publisher of the Document as
30057 given on its Title Page, then add an item describing the Modified
30058 Version as stated in the previous sentence.
30060 @item 
30061 Preserve the network location, if any, given in the Document for
30062 public access to a Transparent copy of the Document, and likewise
30063 the network locations given in the Document for previous versions
30064 it was based on.  These may be placed in the "History" section.
30065 You may omit a network location for a work that was published at
30066 least four years before the Document itself, or if the original
30067 publisher of the version it refers to gives permission.
30069 @item 
30070 For any section Entitled "Acknowledgements" or "Dedications",
30071 Preserve the Title of the section, and preserve in the section all
30072 the substance and tone of each of the contributor acknowledgements
30073 and/or dedications given therein.
30075 @item 
30076 Preserve all the Invariant Sections of the Document,
30077 unaltered in their text and in their titles.  Section numbers
30078 or the equivalent are not considered part of the section titles.
30080 @item 
30081 Delete any section Entitled "Endorsements".  Such a section
30082 may not be included in the Modified Version.
30084 @item 
30085 Do not retitle any existing section to be Entitled "Endorsements"
30086 or to conflict in title with any Invariant Section.
30088 @item 
30089 Preserve any Warranty Disclaimers.
30090 @end enumerate
30092 If the Modified Version includes new front-matter sections or
30093 appendices that qualify as Secondary Sections and contain no material
30094 copied from the Document, you may at your option designate some or all
30095 of these sections as invariant.  To do this, add their titles to the
30096 list of Invariant Sections in the Modified Version's license notice.
30097 These titles must be distinct from any other section titles.
30099 You may add a section Entitled "Endorsements", provided it contains
30100 nothing but endorsements of your Modified Version by various
30101 parties---for example, statements of peer review or that the text has
30102 been approved by an organization as the authoritative definition of a
30103 standard.
30105 You may add a passage of up to five words as a Front-Cover Text, and a
30106 passage of up to 25 words as a Back-Cover Text, to the end of the list
30107 of Cover Texts in the Modified Version.  Only one passage of
30108 Front-Cover Text and one of Back-Cover Text may be added by (or
30109 through arrangements made by) any one entity.  If the Document already
30110 includes a cover text for the same cover, previously added by you or
30111 by arrangement made by the same entity you are acting on behalf of,
30112 you may not add another; but you may replace the old one, on explicit
30113 permission from the previous publisher that added the old one.
30115 The author(s) and publisher(s) of the Document do not by this License
30116 give permission to use their names for publicity for or to assert or
30117 imply endorsement of any Modified Version.
30119 @strong{5. COMBINING DOCUMENTS}
30121 You may combine the Document with other documents released under this
30122 License, under the terms defined in section 4 above for modified
30123 versions, provided that you include in the combination all of the
30124 Invariant Sections of all of the original documents, unmodified, and
30125 list them all as Invariant Sections of your combined work in its
30126 license notice, and that you preserve all their Warranty Disclaimers.
30128 The combined work need only contain one copy of this License, and
30129 multiple identical Invariant Sections may be replaced with a single
30130 copy.  If there are multiple Invariant Sections with the same name but
30131 different contents, make the title of each such section unique by
30132 adding at the end of it, in parentheses, the name of the original
30133 author or publisher of that section if known, or else a unique number.
30134 Make the same adjustment to the section titles in the list of
30135 Invariant Sections in the license notice of the combined work.
30137 In the combination, you must combine any sections Entitled "History"
30138 in the various original documents, forming one section Entitled
30139 "History"; likewise combine any sections Entitled "Acknowledgements",
30140 and any sections Entitled "Dedications".  You must delete all sections
30141 Entitled "Endorsements".
30143 @strong{6. COLLECTIONS OF DOCUMENTS}
30145 You may make a collection consisting of the Document and other documents
30146 released under this License, and replace the individual copies of this
30147 License in the various documents with a single copy that is included in
30148 the collection, provided that you follow the rules of this License for
30149 verbatim copying of each of the documents in all other respects.
30151 You may extract a single document from such a collection, and distribute
30152 it individually under this License, provided you insert a copy of this
30153 License into the extracted document, and follow this License in all
30154 other respects regarding verbatim copying of that document.
30156 @strong{7. AGGREGATION WITH INDEPENDENT WORKS}
30158 A compilation of the Document or its derivatives with other separate
30159 and independent documents or works, in or on a volume of a storage or
30160 distribution medium, is called an "aggregate" if the copyright
30161 resulting from the compilation is not used to limit the legal rights
30162 of the compilation's users beyond what the individual works permit.
30163 When the Document is included in an aggregate, this License does not
30164 apply to the other works in the aggregate which are not themselves
30165 derivative works of the Document.
30167 If the Cover Text requirement of section 3 is applicable to these
30168 copies of the Document, then if the Document is less than one half of
30169 the entire aggregate, the Document's Cover Texts may be placed on
30170 covers that bracket the Document within the aggregate, or the
30171 electronic equivalent of covers if the Document is in electronic form.
30172 Otherwise they must appear on printed covers that bracket the whole
30173 aggregate.
30175 @strong{8. TRANSLATION}
30177 Translation is considered a kind of modification, so you may
30178 distribute translations of the Document under the terms of section 4.
30179 Replacing Invariant Sections with translations requires special
30180 permission from their copyright holders, but you may include
30181 translations of some or all Invariant Sections in addition to the
30182 original versions of these Invariant Sections.  You may include a
30183 translation of this License, and all the license notices in the
30184 Document, and any Warranty Disclaimers, provided that you also include
30185 the original English version of this License and the original versions
30186 of those notices and disclaimers.  In case of a disagreement between
30187 the translation and the original version of this License or a notice
30188 or disclaimer, the original version will prevail.
30190 If a section in the Document is Entitled "Acknowledgements",
30191 "Dedications", or "History", the requirement (section 4) to Preserve
30192 its Title (section 1) will typically require changing the actual
30193 title.
30195 @strong{9. TERMINATION}
30197 You may not copy, modify, sublicense, or distribute the Document
30198 except as expressly provided under this License.  Any attempt
30199 otherwise to copy, modify, sublicense, or distribute it is void, and
30200 will automatically terminate your rights under this License.
30202 However, if you cease all violation of this License, then your license
30203 from a particular copyright holder is reinstated (a) provisionally,
30204 unless and until the copyright holder explicitly and finally
30205 terminates your license, and (b) permanently, if the copyright holder
30206 fails to notify you of the violation by some reasonable means prior to
30207 60 days after the cessation.
30209 Moreover, your license from a particular copyright holder is
30210 reinstated permanently if the copyright holder notifies you of the
30211 violation by some reasonable means, this is the first time you have
30212 received notice of violation of this License (for any work) from that
30213 copyright holder, and you cure the violation prior to 30 days after
30214 your receipt of the notice.
30216 Termination of your rights under this section does not terminate the
30217 licenses of parties who have received copies or rights from you under
30218 this License.  If your rights have been terminated and not permanently
30219 reinstated, receipt of a copy of some or all of the same material does
30220 not give you any rights to use it.
30222 @strong{10. FUTURE REVISIONS OF THIS LICENSE}
30224 The Free Software Foundation may publish new, revised versions
30225 of the GNU Free Documentation License from time to time.  Such new
30226 versions will be similar in spirit to the present version, but may
30227 differ in detail to address new problems or concerns.  See
30228 @indicateurl{http://www.gnu.org/copyleft/}.
30230 Each version of the License is given a distinguishing version number.
30231 If the Document specifies that a particular numbered version of this
30232 License "or any later version" applies to it, you have the option of
30233 following the terms and conditions either of that specified version or
30234 of any later version that has been published (not as a draft) by the
30235 Free Software Foundation.  If the Document does not specify a version
30236 number of this License, you may choose any version ever published (not
30237 as a draft) by the Free Software Foundation.  If the Document
30238 specifies that a proxy can decide which future versions of this
30239 License can be used, that proxy's public statement of acceptance of a
30240 version permanently authorizes you to choose that version for the
30241 Document.
30243 @strong{11. RELICENSING}
30245 "Massive Multiauthor Collaboration Site" (or "MMC Site") means any
30246 World Wide Web server that publishes copyrightable works and also
30247 provides prominent facilities for anybody to edit those works.  A
30248 public wiki that anybody can edit is an example of such a server.  A
30249 "Massive Multiauthor Collaboration" (or "MMC") contained in the
30250 site means any set of copyrightable works thus published on the MMC
30251 site.
30253 "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0
30254 license published by Creative Commons Corporation, a not-for-profit
30255 corporation with a principal place of business in San Francisco,
30256 California, as well as future copyleft versions of that license
30257 published by that same organization.
30259 "Incorporate" means to publish or republish a Document, in whole or
30260 in part, as part of another Document.
30262 An MMC is "eligible for relicensing" if it is licensed under this
30263 License, and if all works that were first published under this License
30264 somewhere other than this MMC, and subsequently incorporated in whole
30265 or in part into the MMC, (1) had no cover texts or invariant sections,
30266 and (2) were thus incorporated prior to November 1, 2008.
30268 The operator of an MMC Site may republish an MMC contained in the site
30269 under CC-BY-SA on the same site at any time before August 1, 2009,
30270 provided the MMC is eligible for relicensing.
30272 @strong{ADDENDUM: How to use this License for your documents}
30274 To use this License in a document you have written, include a copy of
30275 the License in the document and put the following copyright and
30276 license notices just after the title page:
30278 @quotation
30280 Copyright © YEAR  YOUR NAME.
30281 Permission is granted to copy, distribute and/or modify this document
30282 under the terms of the GNU Free Documentation License, Version 1.3
30283 or any later version published by the Free Software Foundation;
30284 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
30285 A copy of the license is included in the section entitled "GNU
30286 Free Documentation License".
30287 @end quotation
30289 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
30290 replace the "with ... Texts." line with this:
30292 @quotation
30294 with the Invariant Sections being LIST THEIR TITLES, with the
30295 Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
30296 @end quotation
30298 If you have Invariant Sections without Cover Texts, or some other
30299 combination of the three, merge those two alternatives to suit the
30300 situation.
30302 If your document contains nontrivial examples of program code, we
30303 recommend releasing these examples in parallel under your choice of
30304 free software license, such as the GNU General Public License,
30305 to permit their use in free software.
30307 @node Index,,GNU Free Documentation License,Top
30308 @unnumbered Index
30311 @printindex ge
30313 @anchor{de}@w{                              }
30314 @anchor{gnat_ugn/gnat_utility_programs switches-related-to-project-files}@w{                              }
30316 @c %**end of body
30317 @bye