[gcc]
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blob2e1a78839cbb0ba6bc2036f5a4e2567546826dfc
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename gnat_ugn.info
4 @documentencoding UTF-8
5 @ifinfo
6 @*Generated by Sphinx 1.4.6.@*
7 @end ifinfo
8 @settitle GNAT User's Guide for Native Platforms
9 @defindex ge
10 @paragraphindent 0
11 @exampleindent 4
12 @finalout
13 @dircategory GNU Ada Tools 
14 @direntry
15 * gnat_ugn: (gnat_ugn.info). gnat_ugn
16 @end direntry
18 @definfoenclose strong,`,'
19 @definfoenclose emph,`,'
20 @c %**end of header
22 @copying
23 @quotation
24 GNAT User's Guide for Native Platforms , Apr 25, 2017
26 AdaCore
28 Copyright @copyright{} 2008-2017, Free Software Foundation
29 @end quotation
31 @end copying
33 @titlepage
34 @title GNAT User's Guide for Native Platforms
35 @insertcopying
36 @end titlepage
37 @contents
39 @c %** start of user preamble
41 @c %** end of user preamble
43 @ifnottex
44 @node Top
45 @top GNAT User's Guide for Native Platforms
46 @insertcopying
47 @end ifnottex
49 @c %**start of body
50 @anchor{gnat_ugn doc}@anchor{0}
51 @emph{GNAT, The GNU Ada Development Environment}
54 @include gcc-common.texi
55 GCC version @value{version-GCC}@*
56 AdaCore
58 Permission is granted to copy, distribute and/or modify this document
59 under the terms of the GNU Free Documentation License, Version 1.3 or
60 any later version published by the Free Software Foundation; with no
61 Invariant Sections, with the Front-Cover Texts being
62 "GNAT User's Guide for Native Platforms",
63 and with no Back-Cover Texts.  A copy of the license is
64 included in the section entitled @ref{1,,GNU Free Documentation License}.
66 @menu
67 * About This Guide:: 
68 * Getting Started with GNAT:: 
69 * The GNAT Compilation Model:: 
70 * Building Executable Programs with GNAT:: 
71 * GNAT Utility Programs:: 
72 * GNAT and Program Execution:: 
73 * Platform-Specific Information:: 
74 * Example of Binder Output File:: 
75 * Elaboration Order Handling in GNAT:: 
76 * Inline Assembler:: 
77 * GNU Free Documentation License:: 
78 * Index:: 
80 @detailmenu
81  --- The Detailed Node Listing ---
83 About This Guide
85 * What This Guide Contains:: 
86 * What You Should Know before Reading This Guide:: 
87 * Related Information:: 
88 * A Note to Readers of Previous Versions of the Manual:: 
89 * Conventions:: 
91 Getting Started with GNAT
93 * Running GNAT:: 
94 * Running a Simple Ada Program:: 
95 * Running a Program with Multiple Units:: 
96 * Using the gnatmake Utility:: 
98 The GNAT Compilation Model
100 * Source Representation:: 
101 * Foreign Language Representation:: 
102 * File Naming Topics and Utilities:: 
103 * Configuration Pragmas:: 
104 * Generating Object Files:: 
105 * Source Dependencies:: 
106 * The Ada Library Information Files:: 
107 * Binding an Ada Program:: 
108 * GNAT and Libraries:: 
109 * Conditional Compilation:: 
110 * Mixed Language Programming:: 
111 * GNAT and Other Compilation Models:: 
112 * Using GNAT Files with External Tools:: 
114 Foreign Language Representation
116 * Latin-1:: 
117 * Other 8-Bit Codes:: 
118 * Wide_Character Encodings:: 
119 * Wide_Wide_Character Encodings:: 
121 File Naming Topics and Utilities
123 * File Naming Rules:: 
124 * Using Other File Names:: 
125 * Alternative File Naming Schemes:: 
126 * Handling Arbitrary File Naming Conventions with gnatname:: 
127 * File Name Krunching with gnatkr:: 
128 * Renaming Files with gnatchop:: 
130 Handling Arbitrary File Naming Conventions with gnatname
132 * Arbitrary File Naming Conventions:: 
133 * Running gnatname:: 
134 * Switches for gnatname:: 
135 * Examples of gnatname Usage:: 
137 File Name Krunching with gnatkr
139 * About gnatkr:: 
140 * Using gnatkr:: 
141 * Krunching Method:: 
142 * Examples of gnatkr Usage:: 
144 Renaming Files with gnatchop
146 * Handling Files with Multiple Units:: 
147 * Operating gnatchop in Compilation Mode:: 
148 * Command Line for gnatchop:: 
149 * Switches for gnatchop:: 
150 * Examples of gnatchop Usage:: 
152 Configuration Pragmas
154 * Handling of Configuration Pragmas:: 
155 * The Configuration Pragmas Files:: 
157 GNAT and Libraries
159 * Introduction to Libraries in GNAT:: 
160 * General Ada Libraries:: 
161 * Stand-alone Ada Libraries:: 
162 * Rebuilding the GNAT Run-Time Library:: 
164 General Ada Libraries
166 * Building a library:: 
167 * Installing a library:: 
168 * Using a library:: 
170 Stand-alone Ada Libraries
172 * Introduction to Stand-alone Libraries:: 
173 * Building a Stand-alone Library:: 
174 * Creating a Stand-alone Library to be used in a non-Ada context:: 
175 * Restrictions in Stand-alone Libraries:: 
177 Conditional Compilation
179 * Modeling Conditional Compilation in Ada:: 
180 * Preprocessing with gnatprep:: 
181 * Integrated Preprocessing:: 
183 Modeling Conditional Compilation in Ada
185 * Use of Boolean Constants:: 
186 * Debugging - A Special Case:: 
187 * Conditionalizing Declarations:: 
188 * Use of Alternative Implementations:: 
189 * Preprocessing:: 
191 Preprocessing with gnatprep
193 * Preprocessing Symbols:: 
194 * Using gnatprep:: 
195 * Switches for gnatprep:: 
196 * Form of Definitions File:: 
197 * Form of Input Text for gnatprep:: 
199 Mixed Language Programming
201 * Interfacing to C:: 
202 * Calling Conventions:: 
203 * Building Mixed Ada and C++ Programs:: 
204 * Generating Ada Bindings for C and C++ headers:: 
205 * Generating C Headers for Ada Specifications:: 
207 Building Mixed Ada and C++ Programs
209 * Interfacing to C++:: 
210 * Linking a Mixed C++ & Ada Program:: 
211 * A Simple Example:: 
212 * Interfacing with C++ constructors:: 
213 * Interfacing with C++ at the Class Level:: 
215 Generating Ada Bindings for C and C++ headers
217 * Running the Binding Generator:: 
218 * Generating Bindings for C++ Headers:: 
219 * Switches:: 
221 Generating C Headers for Ada Specifications
223 * Running the C Header Generator:: 
225 GNAT and Other Compilation Models
227 * Comparison between GNAT and C/C++ Compilation Models:: 
228 * Comparison between GNAT and Conventional Ada Library Models:: 
230 Using GNAT Files with External Tools
232 * Using Other Utility Programs with GNAT:: 
233 * The External Symbol Naming Scheme of GNAT:: 
235 Building Executable Programs with GNAT
237 * Building with gnatmake:: 
238 * Compiling with gcc:: 
239 * Compiler Switches:: 
240 * Linker Switches:: 
241 * Binding with gnatbind:: 
242 * Linking with gnatlink:: 
243 * Using the GNU make Utility:: 
245 Building with gnatmake
247 * Running gnatmake:: 
248 * Switches for gnatmake:: 
249 * Mode Switches for gnatmake:: 
250 * Notes on the Command Line:: 
251 * How gnatmake Works:: 
252 * Examples of gnatmake Usage:: 
254 Compiling with gcc
256 * Compiling Programs:: 
257 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
258 * Order of Compilation Issues:: 
259 * Examples:: 
261 Compiler Switches
263 * Alphabetical List of All Switches:: 
264 * Output and Error Message Control:: 
265 * Warning Message Control:: 
266 * Debugging and Assertion Control:: 
267 * Validity Checking:: 
268 * Style Checking:: 
269 * Run-Time Checks:: 
270 * Using gcc for Syntax Checking:: 
271 * Using gcc for Semantic Checking:: 
272 * Compiling Different Versions of Ada:: 
273 * Character Set Control:: 
274 * File Naming Control:: 
275 * Subprogram Inlining Control:: 
276 * Auxiliary Output Control:: 
277 * Debugging Control:: 
278 * Exception Handling Control:: 
279 * Units to Sources Mapping Files:: 
280 * Code Generation Control:: 
282 Binding with gnatbind
284 * Running gnatbind:: 
285 * Switches for gnatbind:: 
286 * Command-Line Access:: 
287 * Search Paths for gnatbind:: 
288 * Examples of gnatbind Usage:: 
290 Switches for gnatbind
292 * Consistency-Checking Modes:: 
293 * Binder Error Message Control:: 
294 * Elaboration Control:: 
295 * Output Control:: 
296 * Dynamic Allocation Control:: 
297 * Binding with Non-Ada Main Programs:: 
298 * Binding Programs with No Main Subprogram:: 
300 Linking with gnatlink
302 * Running gnatlink:: 
303 * Switches for gnatlink:: 
305 Using the GNU make Utility
307 * Using gnatmake in a Makefile:: 
308 * Automatically Creating a List of Directories:: 
309 * Generating the Command Line Switches:: 
310 * Overcoming Command Line Length Limits:: 
312 GNAT Utility Programs
314 * The File Cleanup Utility gnatclean:: 
315 * The GNAT Library Browser gnatls:: 
316 * The Cross-Referencing Tools gnatxref and gnatfind:: 
317 * The Ada to HTML Converter gnathtml:: 
319 The File Cleanup Utility gnatclean
321 * Running gnatclean:: 
322 * Switches for gnatclean:: 
324 The GNAT Library Browser gnatls
326 * Running gnatls:: 
327 * Switches for gnatls:: 
328 * Example of gnatls Usage:: 
330 The Cross-Referencing Tools gnatxref and gnatfind
332 * gnatxref Switches:: 
333 * gnatfind Switches:: 
334 * Configuration Files for gnatxref and gnatfind:: 
335 * Regular Expressions in gnatfind and gnatxref:: 
336 * Examples of gnatxref Usage:: 
337 * Examples of gnatfind Usage:: 
339 Examples of gnatxref Usage
341 * General Usage:: 
342 * Using gnatxref with vi:: 
344 The Ada to HTML Converter gnathtml
346 * Invoking gnathtml:: 
347 * Installing gnathtml:: 
349 GNAT and Program Execution
351 * Running and Debugging Ada Programs:: 
352 * Code Coverage and Profiling:: 
353 * Improving Performance:: 
354 * Overflow Check Handling in GNAT:: 
355 * Performing Dimensionality Analysis in GNAT:: 
356 * Stack Related Facilities:: 
357 * Memory Management Issues:: 
359 Running and Debugging Ada Programs
361 * The GNAT Debugger GDB:: 
362 * Running GDB:: 
363 * Introduction to GDB Commands:: 
364 * Using Ada Expressions:: 
365 * Calling User-Defined Subprograms:: 
366 * Using the next Command in a Function:: 
367 * Stopping When Ada Exceptions Are Raised:: 
368 * Ada Tasks:: 
369 * Debugging Generic Units:: 
370 * Remote Debugging with gdbserver:: 
371 * GNAT Abnormal Termination or Failure to Terminate:: 
372 * Naming Conventions for GNAT Source Files:: 
373 * Getting Internal Debugging Information:: 
374 * Stack Traceback:: 
376 Stack Traceback
378 * Non-Symbolic Traceback:: 
379 * Symbolic Traceback:: 
381 Code Coverage and Profiling
383 * Code Coverage of Ada Programs with gcov:: 
384 * Profiling an Ada Program with gprof:: 
386 Code Coverage of Ada Programs with gcov
388 * Quick startup guide:: 
389 * GNAT specifics:: 
391 Profiling an Ada Program with gprof
393 * Compilation for profiling:: 
394 * Program execution:: 
395 * Running gprof:: 
396 * Interpretation of profiling results:: 
398 Improving Performance
400 * Performance Considerations:: 
401 * Text_IO Suggestions:: 
402 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
404 Performance Considerations
406 * Controlling Run-Time Checks:: 
407 * Use of Restrictions:: 
408 * Optimization Levels:: 
409 * Debugging Optimized Code:: 
410 * Inlining of Subprograms:: 
411 * Floating_Point_Operations:: 
412 * Vectorization of loops:: 
413 * Other Optimization Switches:: 
414 * Optimization and Strict Aliasing:: 
415 * Aliased Variables and Optimization:: 
416 * Atomic Variables and Optimization:: 
417 * Passive Task Optimization:: 
419 Reducing Size of Executables with Unused Subprogram/Data Elimination
421 * About unused subprogram/data elimination:: 
422 * Compilation options:: 
423 * Example of unused subprogram/data elimination:: 
425 Overflow Check Handling in GNAT
427 * Background:: 
428 * Management of Overflows in GNAT:: 
429 * Specifying the Desired Mode:: 
430 * Default Settings:: 
431 * Implementation Notes:: 
433 Stack Related Facilities
435 * Stack Overflow Checking:: 
436 * Static Stack Usage Analysis:: 
437 * Dynamic Stack Usage Analysis:: 
439 Memory Management Issues
441 * Some Useful Memory Pools:: 
442 * The GNAT Debug Pool Facility:: 
444 Platform-Specific Information
446 * Run-Time Libraries:: 
447 * Specifying a Run-Time Library:: 
448 * Microsoft Windows Topics:: 
449 * Mac OS Topics:: 
451 Run-Time Libraries
453 * Summary of Run-Time Configurations:: 
455 Specifying a Run-Time Library
457 * Choosing the Scheduling Policy:: 
458 * Solaris-Specific Considerations:: 
459 * Solaris Threads Issues:: 
460 * AIX-Specific Considerations:: 
462 Microsoft Windows Topics
464 * Using GNAT on Windows:: 
465 * Using a network installation of GNAT:: 
466 * CONSOLE and WINDOWS subsystems:: 
467 * Temporary Files:: 
468 * Disabling Command Line Argument Expansion:: 
469 * Mixed-Language Programming on Windows:: 
470 * Windows Specific Add-Ons:: 
472 Mixed-Language Programming on Windows
474 * Windows Calling Conventions:: 
475 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
476 * Using DLLs with GNAT:: 
477 * Building DLLs with GNAT Project files:: 
478 * Building DLLs with GNAT:: 
479 * Building DLLs with gnatdll:: 
480 * Ada DLLs and Finalization:: 
481 * Creating a Spec for Ada DLLs:: 
482 * GNAT and Windows Resources:: 
483 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
484 * Debugging a DLL:: 
485 * Setting Stack Size from gnatlink:: 
486 * Setting Heap Size from gnatlink:: 
488 Windows Calling Conventions
490 * C Calling Convention:: 
491 * Stdcall Calling Convention:: 
492 * Win32 Calling Convention:: 
493 * DLL Calling Convention:: 
495 Using DLLs with GNAT
497 * Creating an Ada Spec for the DLL Services:: 
498 * Creating an Import Library:: 
500 Building DLLs with gnatdll
502 * Limitations When Using Ada DLLs from Ada:: 
503 * Exporting Ada Entities:: 
504 * Ada DLLs and Elaboration:: 
506 Creating a Spec for Ada DLLs
508 * Creating the Definition File:: 
509 * Using gnatdll:: 
511 GNAT and Windows Resources
513 * Building Resources:: 
514 * Compiling Resources:: 
515 * Using Resources:: 
517 Debugging a DLL
519 * Program and DLL Both Built with GCC/GNAT:: 
520 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
522 Windows Specific Add-Ons
524 * Win32Ada:: 
525 * wPOSIX:: 
527 Mac OS Topics
529 * Codesigning the Debugger:: 
531 Elaboration Order Handling in GNAT
533 * Elaboration Code:: 
534 * Checking the Elaboration Order:: 
535 * Controlling the Elaboration Order:: 
536 * Controlling Elaboration in GNAT - Internal Calls:: 
537 * Controlling Elaboration in GNAT - External Calls:: 
538 * Default Behavior in GNAT - Ensuring Safety:: 
539 * Treatment of Pragma Elaborate:: 
540 * Elaboration Issues for Library Tasks:: 
541 * Mixing Elaboration Models:: 
542 * What to Do If the Default Elaboration Behavior Fails:: 
543 * Elaboration for Indirect Calls:: 
544 * Summary of Procedures for Elaboration Control:: 
545 * Other Elaboration Order Considerations:: 
546 * Determining the Chosen Elaboration Order:: 
548 Inline Assembler
550 * Basic Assembler Syntax:: 
551 * A Simple Example of Inline Assembler:: 
552 * Output Variables in Inline Assembler:: 
553 * Input Variables in Inline Assembler:: 
554 * Inlining Inline Assembler Code:: 
555 * Other Asm Functionality:: 
557 Other Asm Functionality
559 * The Clobber Parameter:: 
560 * The Volatile Parameter:: 
562 @end detailmenu
563 @end menu
565 @node About This Guide,Getting Started with GNAT,Top,Top
566 @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}
567 @chapter About This Guide
571 This guide describes the use of GNAT,
572 a compiler and software development
573 toolset for the full Ada programming language.
574 It documents the features of the compiler and tools, and explains
575 how to use them to build Ada applications.
577 GNAT implements Ada 95, Ada 2005 and Ada 2012, and it may also be
578 invoked in Ada 83 compatibility mode.
579 By default, GNAT assumes Ada 2012, but you can override with a
580 compiler switch (@ref{6,,Compiling Different Versions of Ada})
581 to explicitly specify the language version.
582 Throughout this manual, references to 'Ada' without a year suffix
583 apply to all Ada 95/2005/2012 versions of the language.
585 @menu
586 * What This Guide Contains:: 
587 * What You Should Know before Reading This Guide:: 
588 * Related Information:: 
589 * A Note to Readers of Previous Versions of the Manual:: 
590 * Conventions:: 
592 @end menu
594 @node What This Guide Contains,What You Should Know before Reading This Guide,,About This Guide
595 @anchor{gnat_ugn/about_this_guide what-this-guide-contains}@anchor{7}
596 @section What This Guide Contains
599 This guide contains the following chapters:
602 @itemize *
604 @item 
605 @ref{8,,Getting Started with GNAT} describes how to get started compiling
606 and running Ada programs with the GNAT Ada programming environment.
608 @item 
609 @ref{9,,The GNAT Compilation Model} describes the compilation model used
610 by GNAT.
612 @item 
613 @ref{a,,Building Executable Programs with GNAT} describes how to use the
614 main GNAT tools to build executable programs, and it also gives examples of
615 using the GNU make utility with GNAT.
617 @item 
618 @ref{b,,GNAT Utility Programs} explains the various utility programs that
619 are included in the GNAT environment
621 @item 
622 @ref{c,,GNAT and Program Execution} covers a number of topics related to
623 running, debugging, and tuning the performace of programs developed
624 with GNAT
625 @end itemize
627 Appendices cover several additional topics:
630 @itemize *
632 @item 
633 @ref{d,,Platform-Specific Information} describes the different run-time
634 library implementations and also presents information on how to use
635 GNAT on several specific platforms
637 @item 
638 @ref{e,,Example of Binder Output File} shows the source code for the binder
639 output file for a sample program.
641 @item 
642 @ref{f,,Elaboration Order Handling in GNAT} describes how GNAT helps
643 you deal with elaboration order issues.
645 @item 
646 @ref{10,,Inline Assembler} shows how to use the inline assembly facility
647 in an Ada program.
648 @end itemize
650 @node What You Should Know before Reading This Guide,Related Information,What This Guide Contains,About This Guide
651 @anchor{gnat_ugn/about_this_guide what-you-should-know-before-reading-this-guide}@anchor{11}
652 @section What You Should Know before Reading This Guide
655 @geindex Ada 95 Language Reference Manual
657 @geindex Ada 2005 Language Reference Manual
659 This guide assumes a basic familiarity with the Ada 95 language, as
660 described in the International Standard ANSI/ISO/IEC-8652:1995, January
661 1995.
662 It does not require knowledge of the features introduced by Ada 2005
663 or Ada 2012.
664 Reference manuals for Ada 95, Ada 2005, and Ada 2012 are included in
665 the GNAT documentation package.
667 @node Related Information,A Note to Readers of Previous Versions of the Manual,What You Should Know before Reading This Guide,About This Guide
668 @anchor{gnat_ugn/about_this_guide related-information}@anchor{12}
669 @section Related Information
672 For further information about Ada and related tools, please refer to the
673 following documents:
676 @itemize *
678 @item 
679 @cite{Ada 95 Reference Manual}, @cite{Ada 2005 Reference Manual}, and
680 @cite{Ada 2012 Reference Manual}, which contain reference
681 material for the several revisions of the Ada language standard.
683 @item 
684 @cite{GNAT Reference_Manual}, which contains all reference material for the GNAT
685 implementation of Ada.
687 @item 
688 @cite{Using the GNAT Programming Studio}, which describes the GPS
689 Integrated Development Environment.
691 @item 
692 @cite{GNAT Programming Studio Tutorial}, which introduces the
693 main GPS features through examples.
695 @item 
696 @cite{Debugging with GDB},
697 for all details on the use of the GNU source-level debugger.
699 @item 
700 @cite{GNU Emacs Manual},
701 for full information on the extensible editor and programming
702 environment Emacs.
703 @end itemize
705 @node A Note to Readers of Previous Versions of the Manual,Conventions,Related Information,About This Guide
706 @anchor{gnat_ugn/about_this_guide a-note-to-readers-of-previous-versions-of-the-manual}@anchor{13}
707 @section A Note to Readers of Previous Versions of the Manual
710 In early 2015 the GNAT manuals were transitioned to the
711 reStructuredText (rst) / Sphinx documentation generator technology.
712 During that process the @cite{GNAT User's Guide} was reorganized
713 so that related topics would be described together in the same chapter
714 or appendix.  Here's a summary of the major changes realized in
715 the new document structure.
718 @itemize *
720 @item 
721 @ref{9,,The GNAT Compilation Model} has been extended so that it now covers
722 the following material:
725 @itemize -
727 @item 
728 The @cite{gnatname}, @cite{gnatkr}, and @cite{gnatchop} tools
730 @item 
731 @ref{14,,Configuration Pragmas}
733 @item 
734 @ref{15,,GNAT and Libraries}
736 @item 
737 @ref{16,,Conditional Compilation} including @ref{17,,Preprocessing with gnatprep}
738 and @ref{18,,Integrated Preprocessing}
740 @item 
741 @ref{19,,Generating Ada Bindings for C and C++ headers}
743 @item 
744 @ref{1a,,Using GNAT Files with External Tools}
745 @end itemize
747 @item 
748 @ref{a,,Building Executable Programs with GNAT} is a new chapter consolidating
749 the following content:
752 @itemize -
754 @item 
755 @ref{1b,,Building with gnatmake}
757 @item 
758 @ref{1c,,Compiling with gcc}
760 @item 
761 @ref{1d,,Binding with gnatbind}
763 @item 
764 @ref{1e,,Linking with gnatlink}
766 @item 
767 @ref{1f,,Using the GNU make Utility}
768 @end itemize
770 @item 
771 @ref{b,,GNAT Utility Programs} is a new chapter consolidating the information about several
772 GNAT tools:
776 @itemize -
778 @item 
779 @ref{20,,The File Cleanup Utility gnatclean}
781 @item 
782 @ref{21,,The GNAT Library Browser gnatls}
784 @item 
785 @ref{22,,The Cross-Referencing Tools gnatxref and gnatfind}
787 @item 
788 @ref{23,,The Ada to HTML Converter gnathtml}
789 @end itemize
791 @item 
792 @ref{c,,GNAT and Program Execution} is a new chapter consolidating the following:
795 @itemize -
797 @item 
798 @ref{24,,Running and Debugging Ada Programs}
800 @item 
801 @ref{25,,Code Coverage and Profiling}
803 @item 
804 @ref{26,,Improving Performance}
806 @item 
807 @ref{27,,Overflow Check Handling in GNAT}
809 @item 
810 @ref{28,,Performing Dimensionality Analysis in GNAT}
812 @item 
813 @ref{29,,Stack Related Facilities}
815 @item 
816 @ref{2a,,Memory Management Issues}
817 @end itemize
819 @item 
820 @ref{d,,Platform-Specific Information} is a new appendix consolidating the following:
823 @itemize -
825 @item 
826 @ref{2b,,Run-Time Libraries}
828 @item 
829 @ref{2c,,Microsoft Windows Topics}
831 @item 
832 @ref{2d,,Mac OS Topics}
833 @end itemize
835 @item 
836 The @cite{Compatibility and Porting Guide} appendix has been moved to the
837 @cite{GNAT Reference Manual}. It now includes a section
838 @cite{Writing Portable Fixed-Point Declarations} which was previously
839 a separate chapter in the @cite{GNAT User's Guide}.
840 @end itemize
842 @node Conventions,,A Note to Readers of Previous Versions of the Manual,About This Guide
843 @anchor{gnat_ugn/about_this_guide conventions}@anchor{2e}
844 @section Conventions
847 @geindex Conventions
848 @geindex typographical
850 @geindex Typographical conventions
852 Following are examples of the typographical and graphic conventions used
853 in this guide:
856 @itemize *
858 @item 
859 @cite{Functions}, @cite{utility program names}, @cite{standard names},
860 and @cite{classes}.
862 @item 
863 @cite{Option flags}
865 @item 
866 @code{File names}
868 @item 
869 @cite{Variables}
871 @item 
872 @emph{Emphasis}
874 @item 
875 [optional information or parameters]
877 @item 
878 Examples are described by text
880 @example
881 and then shown this way.
882 @end example
884 @item 
885 Commands that are entered by the user are shown as preceded by a prompt string
886 comprising the @code{$} character followed by a space.
888 @item 
889 Full file names are shown with the '/' character
890 as the directory separator; e.g., @code{parent-dir/subdir/myfile.adb}.
891 If you are using GNAT on a Windows platform, please note that
892 the '\' character should be used instead.
893 @end itemize
895 @node Getting Started with GNAT,The GNAT Compilation Model,About This Guide,Top
896 @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}
897 @chapter Getting Started with GNAT
900 This chapter describes how to use GNAT's command line interface to build
901 executable Ada programs.
902 On most platforms a visually oriented Integrated Development Environment
903 is also available, the GNAT Programming Studio (GPS).
904 GPS offers a graphical "look and feel", support for development in
905 other programming languages, comprehensive browsing features, and
906 many other capabilities.
907 For information on GPS please refer to
908 @cite{Using the GNAT Programming Studio}.
910 @menu
911 * Running GNAT:: 
912 * Running a Simple Ada Program:: 
913 * Running a Program with Multiple Units:: 
914 * Using the gnatmake Utility:: 
916 @end menu
918 @node Running GNAT,Running a Simple Ada Program,,Getting Started with GNAT
919 @anchor{gnat_ugn/getting_started_with_gnat running-gnat}@anchor{31}@anchor{gnat_ugn/getting_started_with_gnat id2}@anchor{32}
920 @section Running GNAT
923 Three steps are needed to create an executable file from an Ada source
924 file:
927 @itemize *
929 @item 
930 The source file(s) must be compiled.
932 @item 
933 The file(s) must be bound using the GNAT binder.
935 @item 
936 All appropriate object files must be linked to produce an executable.
937 @end itemize
939 All three steps are most commonly handled by using the @emph{gnatmake}
940 utility program that, given the name of the main program, automatically
941 performs the necessary compilation, binding and linking steps.
943 @node Running a Simple Ada Program,Running a Program with Multiple Units,Running GNAT,Getting Started with GNAT
944 @anchor{gnat_ugn/getting_started_with_gnat running-a-simple-ada-program}@anchor{33}@anchor{gnat_ugn/getting_started_with_gnat id3}@anchor{34}
945 @section Running a Simple Ada Program
948 Any text editor may be used to prepare an Ada program.
949 (If Emacs is used, the optional Ada mode may be helpful in laying out the
950 program.)
951 The program text is a normal text file. We will assume in our initial
952 example that you have used your editor to prepare the following
953 standard format text file:
955 @example
956 with Ada.Text_IO; use Ada.Text_IO;
957 procedure Hello is
958 begin
959    Put_Line ("Hello WORLD!");
960 end Hello;
961 @end example
963 This file should be named @code{hello.adb}.
964 With the normal default file naming conventions, GNAT requires
965 that each file
966 contain a single compilation unit whose file name is the
967 unit name,
968 with periods replaced by hyphens; the
969 extension is @code{ads} for a
970 spec and @code{adb} for a body.
971 You can override this default file naming convention by use of the
972 special pragma @cite{Source_File_Name} (for further information please
973 see @ref{35,,Using Other File Names}).
974 Alternatively, if you want to rename your files according to this default
975 convention, which is probably more convenient if you will be using GNAT
976 for all your compilations, then the @cite{gnatchop} utility
977 can be used to generate correctly-named source files
978 (see @ref{36,,Renaming Files with gnatchop}).
980 You can compile the program using the following command (@cite{$} is used
981 as the command prompt in the examples in this document):
983 @example
984 $ gcc -c hello.adb
985 @end example
987 @emph{gcc} is the command used to run the compiler. This compiler is
988 capable of compiling programs in several languages, including Ada and
989 C. It assumes that you have given it an Ada program if the file extension is
990 either @code{.ads} or @code{.adb}, and it will then call
991 the GNAT compiler to compile the specified file.
993 The @code{-c} switch is required. It tells @emph{gcc} to only do a
994 compilation. (For C programs, @emph{gcc} can also do linking, but this
995 capability is not used directly for Ada programs, so the @code{-c}
996 switch must always be present.)
998 This compile command generates a file
999 @code{hello.o}, which is the object
1000 file corresponding to your Ada program. It also generates
1001 an 'Ada Library Information' file @code{hello.ali},
1002 which contains additional information used to check
1003 that an Ada program is consistent.
1004 To build an executable file,
1005 use @cite{gnatbind} to bind the program
1006 and @emph{gnatlink} to link it. The
1007 argument to both @cite{gnatbind} and @emph{gnatlink} is the name of the
1008 @code{ALI} file, but the default extension of @code{.ali} can
1009 be omitted. This means that in the most common case, the argument
1010 is simply the name of the main program:
1012 @example
1013 $ gnatbind hello
1014 $ gnatlink hello
1015 @end example
1017 A simpler method of carrying out these steps is to use @emph{gnatmake},
1018 a master program that invokes all the required
1019 compilation, binding and linking tools in the correct order. In particular,
1020 @emph{gnatmake} automatically recompiles any sources that have been
1021 modified since they were last compiled, or sources that depend
1022 on such modified sources, so that 'version skew' is avoided.
1024 @geindex Version skew (avoided by *gnatmake*)
1026 @example
1027 $ gnatmake hello.adb
1028 @end example
1030 The result is an executable program called @code{hello}, which can be
1031 run by entering:
1033 @example
1034 $ hello
1035 @end example
1037 assuming that the current directory is on the search path
1038 for executable programs.
1040 and, if all has gone well, you will see:
1042 @example
1043 Hello WORLD!
1044 @end example
1046 appear in response to this command.
1048 @node Running a Program with Multiple Units,Using the gnatmake Utility,Running a Simple Ada Program,Getting Started with GNAT
1049 @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}
1050 @section Running a Program with Multiple Units
1053 Consider a slightly more complicated example that has three files: a
1054 main program, and the spec and body of a package:
1056 @example
1057 package Greetings is
1058    procedure Hello;
1059    procedure Goodbye;
1060 end Greetings;
1062 with Ada.Text_IO; use Ada.Text_IO;
1063 package body Greetings is
1064    procedure Hello is
1065    begin
1066       Put_Line ("Hello WORLD!");
1067    end Hello;
1069    procedure Goodbye is
1070    begin
1071       Put_Line ("Goodbye WORLD!");
1072    end Goodbye;
1073 end Greetings;
1075 with Greetings;
1076 procedure Gmain is
1077 begin
1078    Greetings.Hello;
1079    Greetings.Goodbye;
1080 end Gmain;
1081 @end example
1083 Following the one-unit-per-file rule, place this program in the
1084 following three separate files:
1087 @table @asis
1089 @item @emph{greetings.ads}
1091 spec of package @cite{Greetings}
1093 @item @emph{greetings.adb}
1095 body of package @cite{Greetings}
1097 @item @emph{gmain.adb}
1099 body of main program
1100 @end table
1102 To build an executable version of
1103 this program, we could use four separate steps to compile, bind, and link
1104 the program, as follows:
1106 @example
1107 $ gcc -c gmain.adb
1108 $ gcc -c greetings.adb
1109 $ gnatbind gmain
1110 $ gnatlink gmain
1111 @end example
1113 Note that there is no required order of compilation when using GNAT.
1114 In particular it is perfectly fine to compile the main program first.
1115 Also, it is not necessary to compile package specs in the case where
1116 there is an accompanying body; you only need to compile the body. If you want
1117 to submit these files to the compiler for semantic checking and not code
1118 generation, then use the @code{-gnatc} switch:
1120 @example
1121 $ gcc -c greetings.ads -gnatc
1122 @end example
1124 Although the compilation can be done in separate steps as in the
1125 above example, in practice it is almost always more convenient
1126 to use the @emph{gnatmake} tool. All you need to know in this case
1127 is the name of the main program's source file. The effect of the above four
1128 commands can be achieved with a single one:
1130 @example
1131 $ gnatmake gmain.adb
1132 @end example
1134 In the next section we discuss the advantages of using @emph{gnatmake} in
1135 more detail.
1137 @node Using the gnatmake Utility,,Running a Program with Multiple Units,Getting Started with GNAT
1138 @anchor{gnat_ugn/getting_started_with_gnat using-the-gnatmake-utility}@anchor{39}@anchor{gnat_ugn/getting_started_with_gnat id5}@anchor{3a}
1139 @section Using the @emph{gnatmake} Utility
1142 If you work on a program by compiling single components at a time using
1143 @emph{gcc}, you typically keep track of the units you modify. In order to
1144 build a consistent system, you compile not only these units, but also any
1145 units that depend on the units you have modified.
1146 For example, in the preceding case,
1147 if you edit @code{gmain.adb}, you only need to recompile that file. But if
1148 you edit @code{greetings.ads}, you must recompile both
1149 @code{greetings.adb} and @code{gmain.adb}, because both files contain
1150 units that depend on @code{greetings.ads}.
1152 @emph{gnatbind} will warn you if you forget one of these compilation
1153 steps, so that it is impossible to generate an inconsistent program as a
1154 result of forgetting to do a compilation. Nevertheless it is tedious and
1155 error-prone to keep track of dependencies among units.
1156 One approach to handle the dependency-bookkeeping is to use a
1157 makefile. However, makefiles present maintenance problems of their own:
1158 if the dependencies change as you change the program, you must make
1159 sure that the makefile is kept up-to-date manually, which is also an
1160 error-prone process.
1162 The @emph{gnatmake} utility takes care of these details automatically.
1163 Invoke it using either one of the following forms:
1165 @example
1166 $ gnatmake gmain.adb
1167 $ gnatmake gmain
1168 @end example
1170 The argument is the name of the file containing the main program;
1171 you may omit the extension. @emph{gnatmake}
1172 examines the environment, automatically recompiles any files that need
1173 recompiling, and binds and links the resulting set of object files,
1174 generating the executable file, @code{gmain}.
1175 In a large program, it
1176 can be extremely helpful to use @emph{gnatmake}, because working out by hand
1177 what needs to be recompiled can be difficult.
1179 Note that @emph{gnatmake} takes into account all the Ada rules that
1180 establish dependencies among units. These include dependencies that result
1181 from inlining subprogram bodies, and from
1182 generic instantiation. Unlike some other
1183 Ada make tools, @emph{gnatmake} does not rely on the dependencies that were
1184 found by the compiler on a previous compilation, which may possibly
1185 be wrong when sources change. @emph{gnatmake} determines the exact set of
1186 dependencies from scratch each time it is run.
1188 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
1190 @node The GNAT Compilation Model,Building Executable Programs with GNAT,Getting Started with GNAT,Top
1191 @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}
1192 @chapter The GNAT Compilation Model
1195 @geindex GNAT compilation model
1197 @geindex Compilation model
1199 This chapter describes the compilation model used by GNAT. Although
1200 similar to that used by other languages such as C and C++, this model
1201 is substantially different from the traditional Ada compilation models,
1202 which are based on a centralized program library. The chapter covers
1203 the following material:
1206 @itemize *
1208 @item 
1209 Topics related to source file makeup and naming
1212 @itemize *
1214 @item 
1215 @ref{3d,,Source Representation}
1217 @item 
1218 @ref{3e,,Foreign Language Representation}
1220 @item 
1221 @ref{3f,,File Naming Topics and Utilities}
1222 @end itemize
1224 @item 
1225 @ref{14,,Configuration Pragmas}
1227 @item 
1228 @ref{40,,Generating Object Files}
1230 @item 
1231 @ref{41,,Source Dependencies}
1233 @item 
1234 @ref{42,,The Ada Library Information Files}
1236 @item 
1237 @ref{43,,Binding an Ada Program}
1239 @item 
1240 @ref{15,,GNAT and Libraries}
1242 @item 
1243 @ref{16,,Conditional Compilation}
1245 @item 
1246 @ref{44,,Mixed Language Programming}
1248 @item 
1249 @ref{45,,GNAT and Other Compilation Models}
1251 @item 
1252 @ref{1a,,Using GNAT Files with External Tools}
1253 @end itemize
1255 @menu
1256 * Source Representation:: 
1257 * Foreign Language Representation:: 
1258 * File Naming Topics and Utilities:: 
1259 * Configuration Pragmas:: 
1260 * Generating Object Files:: 
1261 * Source Dependencies:: 
1262 * The Ada Library Information Files:: 
1263 * Binding an Ada Program:: 
1264 * GNAT and Libraries:: 
1265 * Conditional Compilation:: 
1266 * Mixed Language Programming:: 
1267 * GNAT and Other Compilation Models:: 
1268 * Using GNAT Files with External Tools:: 
1270 @end menu
1272 @node Source Representation,Foreign Language Representation,,The GNAT Compilation Model
1273 @anchor{gnat_ugn/the_gnat_compilation_model source-representation}@anchor{3d}@anchor{gnat_ugn/the_gnat_compilation_model id2}@anchor{46}
1274 @section Source Representation
1277 @geindex Latin-1
1279 @geindex VT
1280 @geindex HT
1281 @geindex CR
1282 @geindex LF
1283 @geindex FF
1285 Ada source programs are represented in standard text files, using
1286 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1287 7-bit ASCII set, plus additional characters used for
1288 representing foreign languages (see @ref{3e,,Foreign Language Representation}
1289 for support of non-USA character sets). The format effector characters
1290 are represented using their standard ASCII encodings, as follows:
1292 @quotation
1295 @multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxx} 
1296 @item
1298 Character
1300 @tab
1302 Effect
1304 @tab
1306 Code
1308 @item
1310 @code{VT}
1312 @tab
1314 Vertical tab
1316 @tab
1318 @cite{16#0B#}
1320 @item
1322 @code{HT}
1324 @tab
1326 Horizontal tab
1328 @tab
1330 @cite{16#09#}
1332 @item
1334 @code{CR}
1336 @tab
1338 Carriage return
1340 @tab
1342 @cite{16#0D#}
1344 @item
1346 @code{LF}
1348 @tab
1350 Line feed
1352 @tab
1354 @cite{16#0A#}
1356 @item
1358 @code{FF}
1360 @tab
1362 Form feed
1364 @tab
1366 @cite{16#0C#}
1368 @end multitable
1370 @end quotation
1372 Source files are in standard text file format. In addition, GNAT will
1373 recognize a wide variety of stream formats, in which the end of
1374 physical lines is marked by any of the following sequences:
1375 @cite{LF}, @cite{CR}, @cite{CR-LF}, or @cite{LF-CR}. This is useful
1376 in accommodating files that are imported from other operating systems.
1378 @geindex End of source file; Source file@comma{} end
1380 @geindex SUB (control character)
1382 The end of a source file is normally represented by the physical end of
1383 file. However, the control character @cite{16#1A#} (@code{SUB}) is also
1384 recognized as signalling the end of the source file. Again, this is
1385 provided for compatibility with other operating systems where this
1386 code is used to represent the end of file.
1388 @geindex spec (definition)
1389 @geindex compilation (definition)
1391 Each file contains a single Ada compilation unit, including any pragmas
1392 associated with the unit. For example, this means you must place a
1393 package declaration (a package @cite{spec}) and the corresponding body in
1394 separate files. An Ada @cite{compilation} (which is a sequence of
1395 compilation units) is represented using a sequence of files. Similarly,
1396 you will place each subunit or child unit in a separate file.
1398 @node Foreign Language Representation,File Naming Topics and Utilities,Source Representation,The GNAT Compilation Model
1399 @anchor{gnat_ugn/the_gnat_compilation_model foreign-language-representation}@anchor{3e}@anchor{gnat_ugn/the_gnat_compilation_model id3}@anchor{47}
1400 @section Foreign Language Representation
1403 GNAT supports the standard character sets defined in Ada as well as
1404 several other non-standard character sets for use in localized versions
1405 of the compiler (@ref{48,,Character Set Control}).
1407 @menu
1408 * Latin-1:: 
1409 * Other 8-Bit Codes:: 
1410 * Wide_Character Encodings:: 
1411 * Wide_Wide_Character Encodings:: 
1413 @end menu
1415 @node Latin-1,Other 8-Bit Codes,,Foreign Language Representation
1416 @anchor{gnat_ugn/the_gnat_compilation_model id4}@anchor{49}@anchor{gnat_ugn/the_gnat_compilation_model latin-1}@anchor{4a}
1417 @subsection Latin-1
1420 @geindex Latin-1
1422 The basic character set is Latin-1. This character set is defined by ISO
1423 standard 8859, part 1. The lower half (character codes @cite{16#00#}
1424 ... @cite{16#7F#)} is identical to standard ASCII coding, but the upper
1425 half is used to represent additional characters. These include extended letters
1426 used by European languages, such as French accents, the vowels with umlauts
1427 used in German, and the extra letter A-ring used in Swedish.
1429 @geindex Ada.Characters.Latin_1
1431 For a complete list of Latin-1 codes and their encodings, see the source
1432 file of library unit @cite{Ada.Characters.Latin_1} in file
1433 @code{a-chlat1.ads}.
1434 You may use any of these extended characters freely in character or
1435 string literals. In addition, the extended characters that represent
1436 letters can be used in identifiers.
1438 @node Other 8-Bit Codes,Wide_Character Encodings,Latin-1,Foreign Language Representation
1439 @anchor{gnat_ugn/the_gnat_compilation_model other-8-bit-codes}@anchor{4b}@anchor{gnat_ugn/the_gnat_compilation_model id5}@anchor{4c}
1440 @subsection Other 8-Bit Codes
1443 GNAT also supports several other 8-bit coding schemes:
1445 @geindex Latin-2
1447 @geindex ISO 8859-2
1450 @table @asis
1452 @item @emph{ISO 8859-2 (Latin-2)}
1454 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1455 equivalence.
1456 @end table
1458 @geindex Latin-3
1460 @geindex ISO 8859-3
1463 @table @asis
1465 @item @emph{ISO 8859-3 (Latin-3)}
1467 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1468 equivalence.
1469 @end table
1471 @geindex Latin-4
1473 @geindex ISO 8859-4
1476 @table @asis
1478 @item @emph{ISO 8859-4 (Latin-4)}
1480 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1481 equivalence.
1482 @end table
1484 @geindex ISO 8859-5
1486 @geindex Cyrillic
1489 @table @asis
1491 @item @emph{ISO 8859-5 (Cyrillic)}
1493 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1494 lowercase equivalence.
1495 @end table
1497 @geindex ISO 8859-15
1499 @geindex Latin-9
1502 @table @asis
1504 @item @emph{ISO 8859-15 (Latin-9)}
1506 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1507 lowercase equivalence
1508 @end table
1510 @geindex code page 437 (IBM PC)
1513 @table @asis
1515 @item @emph{IBM PC (code page 437)}
1517 This code page is the normal default for PCs in the U.S. It corresponds
1518 to the original IBM PC character set. This set has some, but not all, of
1519 the extended Latin-1 letters, but these letters do not have the same
1520 encoding as Latin-1. In this mode, these letters are allowed in
1521 identifiers with uppercase and lowercase equivalence.
1522 @end table
1524 @geindex code page 850 (IBM PC)
1527 @table @asis
1529 @item @emph{IBM PC (code page 850)}
1531 This code page is a modification of 437 extended to include all the
1532 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1533 mode, all these letters are allowed in identifiers with uppercase and
1534 lowercase equivalence.
1536 @item @emph{Full Upper 8-bit}
1538 Any character in the range 80-FF allowed in identifiers, and all are
1539 considered distinct. In other words, there are no uppercase and lowercase
1540 equivalences in this range. This is useful in conjunction with
1541 certain encoding schemes used for some foreign character sets (e.g.,
1542 the typical method of representing Chinese characters on the PC).
1544 @item @emph{No Upper-Half}
1546 No upper-half characters in the range 80-FF are allowed in identifiers.
1547 This gives Ada 83 compatibility for identifier names.
1548 @end table
1550 For precise data on the encodings permitted, and the uppercase and lowercase
1551 equivalences that are recognized, see the file @code{csets.adb} in
1552 the GNAT compiler sources. You will need to obtain a full source release
1553 of GNAT to obtain this file.
1555 @node Wide_Character Encodings,Wide_Wide_Character Encodings,Other 8-Bit Codes,Foreign Language Representation
1556 @anchor{gnat_ugn/the_gnat_compilation_model id6}@anchor{4d}@anchor{gnat_ugn/the_gnat_compilation_model wide-character-encodings}@anchor{4e}
1557 @subsection Wide_Character Encodings
1560 GNAT allows wide character codes to appear in character and string
1561 literals, and also optionally in identifiers, by means of the following
1562 possible encoding schemes:
1565 @table @asis
1567 @item @emph{Hex Coding}
1569 In this encoding, a wide character is represented by the following five
1570 character sequence:
1572 @example
1573 ESC a b c d
1574 @end example
1576 where @cite{a}, @cite{b}, @cite{c}, @cite{d} are the four hexadecimal
1577 characters (using uppercase letters) of the wide character code. For
1578 example, ESC A345 is used to represent the wide character with code
1579 @cite{16#A345#}.
1580 This scheme is compatible with use of the full Wide_Character set.
1582 @item @emph{Upper-Half Coding}
1584 @geindex Upper-Half Coding
1586 The wide character with encoding @cite{16#abcd#} where the upper bit is on
1587 (in other words, 'a' is in the range 8-F) is represented as two bytes,
1588 @cite{16#ab#} and @cite{16#cd#}. The second byte cannot be a format control
1589 character, but is not required to be in the upper half. This method can
1590 be also used for shift-JIS or EUC, where the internal coding matches the
1591 external coding.
1593 @item @emph{Shift JIS Coding}
1595 @geindex Shift JIS Coding
1597 A wide character is represented by a two-character sequence,
1598 @cite{16#ab#} and
1599 @cite{16#cd#}, with the restrictions described for upper-half encoding as
1600 described above. The internal character code is the corresponding JIS
1601 character according to the standard algorithm for Shift-JIS
1602 conversion. Only characters defined in the JIS code set table can be
1603 used with this encoding method.
1605 @item @emph{EUC Coding}
1607 @geindex EUC Coding
1609 A wide character is represented by a two-character sequence
1610 @cite{16#ab#} and
1611 @cite{16#cd#}, with both characters being in the upper half. The internal
1612 character code is the corresponding JIS character according to the EUC
1613 encoding algorithm. Only characters defined in the JIS code set table
1614 can be used with this encoding method.
1616 @item @emph{UTF-8 Coding}
1618 A wide character is represented using
1619 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1620 10646-1/Am.2. Depending on the character value, the representation
1621 is a one, two, or three byte sequence:
1623 @example
1624 16#0000#-16#007f#: 2#0`xxxxxxx`#
1625 16#0080#-16#07ff#: 2#110`xxxxx`# 2#10`xxxxxx`#
1626 16#0800#-16#ffff#: 2#1110`xxxx`# 2#10`xxxxxx`# 2#10`xxxxxx`#
1627 @end example
1629 where the @cite{xxx} bits correspond to the left-padded bits of the
1630 16-bit character value. Note that all lower half ASCII characters
1631 are represented as ASCII bytes and all upper half characters and
1632 other wide characters are represented as sequences of upper-half
1633 (The full UTF-8 scheme allows for encoding 31-bit characters as
1634 6-byte sequences, and in the following section on wide wide
1635 characters, the use of these sequences is documented).
1637 @item @emph{Brackets Coding}
1639 In this encoding, a wide character is represented by the following eight
1640 character sequence:
1642 @example
1643 [ " a b c d " ]
1644 @end example
1646 where @cite{a}, @cite{b}, @cite{c}, @cite{d} are the four hexadecimal
1647 characters (using uppercase letters) of the wide character code. For
1648 example, ['A345'] is used to represent the wide character with code
1649 @cite{16#A345#}. It is also possible (though not required) to use the
1650 Brackets coding for upper half characters. For example, the code
1651 @cite{16#A3#} can be represented as @cite{['A3']}.
1653 This scheme is compatible with use of the full Wide_Character set,
1654 and is also the method used for wide character encoding in some standard
1655 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1656 @end table
1658 @cartouche
1659 @quotation Note 
1660 Some of these coding schemes do not permit the full use of the
1661 Ada character set. For example, neither Shift JIS nor EUC allow the
1662 use of the upper half of the Latin-1 set.
1663 @end quotation
1664 @end cartouche
1666 @node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1667 @anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{4f}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{50}
1668 @subsection Wide_Wide_Character Encodings
1671 GNAT allows wide wide character codes to appear in character and string
1672 literals, and also optionally in identifiers, by means of the following
1673 possible encoding schemes:
1676 @table @asis
1678 @item @emph{UTF-8 Coding}
1680 A wide character is represented using
1681 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1682 10646-1/Am.2. Depending on the character value, the representation
1683 of character codes with values greater than 16#FFFF# is a
1684 is a four, five, or six byte sequence:
1686 @example
1687 16#01_0000#-16#10_FFFF#:     11110xxx 10xxxxxx 10xxxxxx
1688                              10xxxxxx
1689 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1690                              10xxxxxx 10xxxxxx
1691 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1692                              10xxxxxx 10xxxxxx 10xxxxxx
1693 @end example
1695 where the @cite{xxx} bits correspond to the left-padded bits of the
1696 32-bit character value.
1698 @item @emph{Brackets Coding}
1700 In this encoding, a wide wide character is represented by the following ten or
1701 twelve byte character sequence:
1703 @example
1704 [ " a b c d e f " ]
1705 [ " a b c d e f g h " ]
1706 @end example
1708 where @cite{a-h} are the six or eight hexadecimal
1709 characters (using uppercase letters) of the wide wide character code. For
1710 example, ["1F4567"] is used to represent the wide wide character with code
1711 @cite{16#001F_4567#}.
1713 This scheme is compatible with use of the full Wide_Wide_Character set,
1714 and is also the method used for wide wide character encoding in some standard
1715 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1716 @end table
1718 @node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1719 @anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{3f}
1720 @section File Naming Topics and Utilities
1723 GNAT has a default file naming scheme and also provides the user with
1724 a high degree of control over how the names and extensions of the
1725 source files correspond to the Ada compilation units that they contain.
1727 @menu
1728 * File Naming Rules:: 
1729 * Using Other File Names:: 
1730 * Alternative File Naming Schemes:: 
1731 * Handling Arbitrary File Naming Conventions with gnatname:: 
1732 * File Name Krunching with gnatkr:: 
1733 * Renaming Files with gnatchop:: 
1735 @end menu
1737 @node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1738 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{52}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{53}
1739 @subsection File Naming Rules
1742 The default file name is determined by the name of the unit that the
1743 file contains. The name is formed by taking the full expanded name of
1744 the unit and replacing the separating dots with hyphens and using
1745 lowercase for all letters.
1747 An exception arises if the file name generated by the above rules starts
1748 with one of the characters
1749 @cite{a}, @cite{g}, @cite{i}, or @cite{s}, and the second character is a
1750 minus. In this case, the character tilde is used in place
1751 of the minus. The reason for this special rule is to avoid clashes with
1752 the standard names for child units of the packages System, Ada,
1753 Interfaces, and GNAT, which use the prefixes
1754 @cite{s-}, @cite{a-}, @cite{i-}, and @cite{g-},
1755 respectively.
1757 The file extension is @code{.ads} for a spec and
1758 @code{.adb} for a body. The following table shows some
1759 examples of these rules.
1761 @quotation
1764 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
1765 @item
1767 Source File
1769 @tab
1771 Ada Compilation Unit
1773 @item
1775 @code{main.ads}
1777 @tab
1779 Main (spec)
1781 @item
1783 @code{main.adb}
1785 @tab
1787 Main (body)
1789 @item
1791 @code{arith_functions.ads}
1793 @tab
1795 Arith_Functions (package spec)
1797 @item
1799 @code{arith_functions.adb}
1801 @tab
1803 Arith_Functions (package body)
1805 @item
1807 @code{func-spec.ads}
1809 @tab
1811 Func.Spec (child package spec)
1813 @item
1815 @code{func-spec.adb}
1817 @tab
1819 Func.Spec (child package body)
1821 @item
1823 @code{main-sub.adb}
1825 @tab
1827 Sub (subunit of Main)
1829 @item
1831 @code{a~bad.adb}
1833 @tab
1835 A.Bad (child package body)
1837 @end multitable
1839 @end quotation
1841 Following these rules can result in excessively long
1842 file names if corresponding
1843 unit names are long (for example, if child units or subunits are
1844 heavily nested). An option is available to shorten such long file names
1845 (called file name 'krunching'). This may be particularly useful when
1846 programs being developed with GNAT are to be used on operating systems
1847 with limited file name lengths. @ref{54,,Using gnatkr}.
1849 Of course, no file shortening algorithm can guarantee uniqueness over
1850 all possible unit names; if file name krunching is used, it is your
1851 responsibility to ensure no name clashes occur. Alternatively you
1852 can specify the exact file names that you want used, as described
1853 in the next section. Finally, if your Ada programs are migrating from a
1854 compiler with a different naming convention, you can use the gnatchop
1855 utility to produce source files that follow the GNAT naming conventions.
1856 (For details see @ref{36,,Renaming Files with gnatchop}.)
1858 Note: in the case of Windows or Mac OS operating systems, case is not
1859 significant. So for example on @cite{Windows} if the canonical name is
1860 @cite{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1861 However, case is significant for other operating systems, so for example,
1862 if you want to use other than canonically cased file names on a Unix system,
1863 you need to follow the procedures described in the next section.
1865 @node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1866 @anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{55}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{35}
1867 @subsection Using Other File Names
1870 @geindex File names
1872 In the previous section, we have described the default rules used by
1873 GNAT to determine the file name in which a given unit resides. It is
1874 often convenient to follow these default rules, and if you follow them,
1875 the compiler knows without being explicitly told where to find all
1876 the files it needs.
1878 @geindex Source_File_Name pragma
1880 However, in some cases, particularly when a program is imported from
1881 another Ada compiler environment, it may be more convenient for the
1882 programmer to specify which file names contain which units. GNAT allows
1883 arbitrary file names to be used by means of the Source_File_Name pragma.
1884 The form of this pragma is as shown in the following examples:
1886 @example
1887 pragma Source_File_Name (My_Utilities.Stacks,
1888   Spec_File_Name => "myutilst_a.ada");
1889 pragma Source_File_name (My_Utilities.Stacks,
1890   Body_File_Name => "myutilst.ada");
1891 @end example
1893 As shown in this example, the first argument for the pragma is the unit
1894 name (in this example a child unit). The second argument has the form
1895 of a named association. The identifier
1896 indicates whether the file name is for a spec or a body;
1897 the file name itself is given by a string literal.
1899 The source file name pragma is a configuration pragma, which means that
1900 normally it will be placed in the @code{gnat.adc}
1901 file used to hold configuration
1902 pragmas that apply to a complete compilation environment.
1903 For more details on how the @code{gnat.adc} file is created and used
1904 see @ref{56,,Handling of Configuration Pragmas}.
1906 @geindex gnat.adc
1908 GNAT allows completely arbitrary file names to be specified using the
1909 source file name pragma. However, if the file name specified has an
1910 extension other than @code{.ads} or @code{.adb} it is necessary to use
1911 a special syntax when compiling the file. The name in this case must be
1912 preceded by the special sequence @emph{-x} followed by a space and the name
1913 of the language, here @cite{ada}, as in:
1915 @example
1916 $ gcc -c -x ada peculiar_file_name.sim
1917 @end example
1919 @cite{gnatmake} handles non-standard file names in the usual manner (the
1920 non-standard file name for the main program is simply used as the
1921 argument to gnatmake). Note that if the extension is also non-standard,
1922 then it must be included in the @cite{gnatmake} command, it may not
1923 be omitted.
1925 @node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
1926 @anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{57}@anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{58}
1927 @subsection Alternative File Naming Schemes
1930 @geindex File naming schemes
1931 @geindex alternative
1933 @geindex File names
1935 The previous section described the use of the @cite{Source_File_Name}
1936 pragma to allow arbitrary names to be assigned to individual source files.
1937 However, this approach requires one pragma for each file, and especially in
1938 large systems can result in very long @code{gnat.adc} files, and also create
1939 a maintenance problem.
1941 @geindex Source_File_Name pragma
1943 GNAT also provides a facility for specifying systematic file naming schemes
1944 other than the standard default naming scheme previously described. An
1945 alternative scheme for naming is specified by the use of
1946 @cite{Source_File_Name} pragmas having the following format:
1948 @example
1949 pragma Source_File_Name (
1950    Spec_File_Name  => FILE_NAME_PATTERN
1951  [ , Casing          => CASING_SPEC]
1952  [ , Dot_Replacement => STRING_LITERAL ] );
1954 pragma Source_File_Name (
1955    Body_File_Name  => FILE_NAME_PATTERN
1956  [ , Casing          => CASING_SPEC ]
1957  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1959 pragma Source_File_Name (
1960    Subunit_File_Name  => FILE_NAME_PATTERN
1961  [ , Casing          => CASING_SPEC ]
1962  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1964 FILE_NAME_PATTERN ::= STRING_LITERAL
1965 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1966 @end example
1968 The @cite{FILE_NAME_PATTERN} string shows how the file name is constructed.
1969 It contains a single asterisk character, and the unit name is substituted
1970 systematically for this asterisk. The optional parameter
1971 @cite{Casing} indicates
1972 whether the unit name is to be all upper-case letters, all lower-case letters,
1973 or mixed-case. If no
1974 @cite{Casing} parameter is used, then the default is all
1975 lower-case.
1977 The optional @cite{Dot_Replacement} string is used to replace any periods
1978 that occur in subunit or child unit names. If no @cite{Dot_Replacement}
1979 argument is used then separating dots appear unchanged in the resulting
1980 file name.
1981 Although the above syntax indicates that the
1982 @cite{Casing} argument must appear
1983 before the @cite{Dot_Replacement} argument, but it
1984 is also permissible to write these arguments in the opposite order.
1986 As indicated, it is possible to specify different naming schemes for
1987 bodies, specs, and subunits. Quite often the rule for subunits is the
1988 same as the rule for bodies, in which case, there is no need to give
1989 a separate @cite{Subunit_File_Name} rule, and in this case the
1990 @cite{Body_File_name} rule is used for subunits as well.
1992 The separate rule for subunits can also be used to implement the rather
1993 unusual case of a compilation environment (e.g., a single directory) which
1994 contains a subunit and a child unit with the same unit name. Although
1995 both units cannot appear in the same partition, the Ada Reference Manual
1996 allows (but does not require) the possibility of the two units coexisting
1997 in the same environment.
1999 The file name translation works in the following steps:
2002 @itemize *
2004 @item 
2005 If there is a specific @cite{Source_File_Name} pragma for the given unit,
2006 then this is always used, and any general pattern rules are ignored.
2008 @item 
2009 If there is a pattern type @cite{Source_File_Name} pragma that applies to
2010 the unit, then the resulting file name will be used if the file exists. If
2011 more than one pattern matches, the latest one will be tried first, and the
2012 first attempt resulting in a reference to a file that exists will be used.
2014 @item 
2015 If no pattern type @cite{Source_File_Name} pragma that applies to the unit
2016 for which the corresponding file exists, then the standard GNAT default
2017 naming rules are used.
2018 @end itemize
2020 As an example of the use of this mechanism, consider a commonly used scheme
2021 in which file names are all lower case, with separating periods copied
2022 unchanged to the resulting file name, and specs end with @code{.1.ada}, and
2023 bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
2024 two pragmas appear:
2026 @example
2027 pragma Source_File_Name
2028   (Spec_File_Name => ".1.ada");
2029 pragma Source_File_Name
2030   (Body_File_Name => ".2.ada");
2031 @end example
2033 The default GNAT scheme is actually implemented by providing the following
2034 default pragmas internally:
2036 @example
2037 pragma Source_File_Name
2038   (Spec_File_Name => ".ads", Dot_Replacement => "-");
2039 pragma Source_File_Name
2040   (Body_File_Name => ".adb", Dot_Replacement => "-");
2041 @end example
2043 Our final example implements a scheme typically used with one of the
2044 Ada 83 compilers, where the separator character for subunits was '__'
2045 (two underscores), specs were identified by adding @code{_.ADA}, bodies
2046 by adding @code{.ADA}, and subunits by
2047 adding @code{.SEP}. All file names were
2048 upper case. Child units were not present of course since this was an
2049 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2050 the same double underscore separator for child units.
2052 @example
2053 pragma Source_File_Name
2054   (Spec_File_Name => "_.ADA",
2055    Dot_Replacement => "__",
2056    Casing = Uppercase);
2057 pragma Source_File_Name
2058   (Body_File_Name => ".ADA",
2059    Dot_Replacement => "__",
2060    Casing = Uppercase);
2061 pragma Source_File_Name
2062   (Subunit_File_Name => ".SEP",
2063    Dot_Replacement => "__",
2064    Casing = Uppercase);
2065 @end example
2067 @geindex gnatname
2069 @node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
2070 @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}
2071 @subsection Handling Arbitrary File Naming Conventions with @cite{gnatname}
2074 @geindex File Naming Conventions
2076 @menu
2077 * Arbitrary File Naming Conventions:: 
2078 * Running gnatname:: 
2079 * Switches for gnatname:: 
2080 * Examples of gnatname Usage:: 
2082 @end menu
2084 @node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
2085 @anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{5b}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{5c}
2086 @subsubsection Arbitrary File Naming Conventions
2089 The GNAT compiler must be able to know the source file name of a compilation
2090 unit.  When using the standard GNAT default file naming conventions
2091 (@cite{.ads} for specs, @cite{.adb} for bodies), the GNAT compiler
2092 does not need additional information.
2094 When the source file names do not follow the standard GNAT default file naming
2095 conventions, the GNAT compiler must be given additional information through
2096 a configuration pragmas file (@ref{14,,Configuration Pragmas})
2097 or a project file.
2098 When the non-standard file naming conventions are well-defined,
2099 a small number of pragmas @cite{Source_File_Name} specifying a naming pattern
2100 (@ref{58,,Alternative File Naming Schemes}) may be sufficient. However,
2101 if the file naming conventions are irregular or arbitrary, a number
2102 of pragma @cite{Source_File_Name} for individual compilation units
2103 must be defined.
2104 To help maintain the correspondence between compilation unit names and
2105 source file names within the compiler,
2106 GNAT provides a tool @cite{gnatname} to generate the required pragmas for a
2107 set of files.
2109 @node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
2110 @anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{5d}@anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{5e}
2111 @subsubsection Running @cite{gnatname}
2114 The usual form of the @cite{gnatname} command is:
2116 @example
2117 $ gnatname [`switches`] `naming_pattern` [`naming_patterns`]
2118     [--and [`switches`] `naming_pattern` [`naming_patterns`]]
2119 @end example
2121 All of the arguments are optional. If invoked without any argument,
2122 @cite{gnatname} will display its usage.
2124 When used with at least one naming pattern, @cite{gnatname} will attempt to
2125 find all the compilation units in files that follow at least one of the
2126 naming patterns. To find these compilation units,
2127 @cite{gnatname} will use the GNAT compiler in syntax-check-only mode on all
2128 regular files.
2130 One or several Naming Patterns may be given as arguments to @cite{gnatname}.
2131 Each Naming Pattern is enclosed between double quotes (or single
2132 quotes on Windows).
2133 A Naming Pattern is a regular expression similar to the wildcard patterns
2134 used in file names by the Unix shells or the DOS prompt.
2136 @cite{gnatname} may be called with several sections of directories/patterns.
2137 Sections are separated by switch @cite{--and}. In each section, there must be
2138 at least one pattern. If no directory is specified in a section, the current
2139 directory (or the project directory is @cite{-P} is used) is implied.
2140 The options other that the directory switches and the patterns apply globally
2141 even if they are in different sections.
2143 Examples of Naming Patterns are:
2145 @example
2146 "*.[12].ada"
2147 "*.ad[sb]*"
2148 "body_*"    "spec_*"
2149 @end example
2151 For a more complete description of the syntax of Naming Patterns,
2152 see the second kind of regular expressions described in @code{g-regexp.ads}
2153 (the 'Glob' regular expressions).
2155 When invoked with no switch @cite{-P}, @cite{gnatname} will create a
2156 configuration pragmas file @code{gnat.adc} in the current working directory,
2157 with pragmas @cite{Source_File_Name} for each file that contains a valid Ada
2158 unit.
2160 @node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
2161 @anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{5f}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{60}
2162 @subsubsection Switches for @cite{gnatname}
2165 Switches for @cite{gnatname} must precede any specified Naming Pattern.
2167 You may specify any of the following switches to @cite{gnatname}:
2169 @geindex --version (gnatname)
2172 @table @asis
2174 @item @code{--version}
2176 Display Copyright and version, then exit disregarding all other options.
2177 @end table
2179 @geindex --help (gnatname)
2182 @table @asis
2184 @item @code{--help}
2186 If @emph{--version} was not used, display usage, then exit disregarding
2187 all other options.
2189 @item @code{--subdirs=@emph{dir}}
2191 Real object, library or exec directories are subdirectories <dir> of the
2192 specified ones.
2194 @item @code{--no-backup}
2196 Do not create a backup copy of an existing project file.
2198 @item @code{--and}
2200 Start another section of directories/patterns.
2201 @end table
2203 @geindex -c (gnatname)
2206 @table @asis
2208 @item @code{-c@emph{filename}}
2210 Create a configuration pragmas file @code{filename} (instead of the default
2211 @code{gnat.adc}).
2212 There may be zero, one or more space between @emph{-c} and
2213 @code{filename}.
2214 @code{filename} may include directory information. @code{filename} must be
2215 writable. There may be only one switch @emph{-c}.
2216 When a switch @emph{-c} is
2217 specified, no switch @emph{-P} may be specified (see below).
2218 @end table
2220 @geindex -d (gnatname)
2223 @table @asis
2225 @item @code{-d@emph{dir}}
2227 Look for source files in directory @code{dir}. There may be zero, one or more
2228 spaces between @emph{-d} and @code{dir}.
2229 @code{dir} may end with @cite{/**}, that is it may be of the form
2230 @cite{root_dir/**}. In this case, the directory @cite{root_dir} and all of its
2231 subdirectories, recursively, have to be searched for sources.
2232 When a switch @emph{-d}
2233 is specified, the current working directory will not be searched for source
2234 files, unless it is explicitly specified with a @emph{-d}
2235 or @emph{-D} switch.
2236 Several switches @emph{-d} may be specified.
2237 If @code{dir} is a relative path, it is relative to the directory of
2238 the configuration pragmas file specified with switch
2239 @emph{-c},
2240 or to the directory of the project file specified with switch
2241 @emph{-P} or,
2242 if neither switch @emph{-c}
2243 nor switch @emph{-P} are specified, it is relative to the
2244 current working directory. The directory
2245 specified with switch @emph{-d} must exist and be readable.
2246 @end table
2248 @geindex -D (gnatname)
2251 @table @asis
2253 @item @code{-D@emph{filename}}
2255 Look for source files in all directories listed in text file @code{filename}.
2256 There may be zero, one or more spaces between @emph{-D}
2257 and @code{filename}.
2258 @code{filename} must be an existing, readable text file.
2259 Each nonempty line in @code{filename} must be a directory.
2260 Specifying switch @emph{-D} is equivalent to specifying as many
2261 switches @emph{-d} as there are nonempty lines in
2262 @code{file}.
2264 @item @code{-eL}
2266 Follow symbolic links when processing project files.
2268 @geindex -f (gnatname)
2270 @item @code{-f@emph{pattern}}
2272 Foreign patterns. Using this switch, it is possible to add sources of languages
2273 other than Ada to the list of sources of a project file.
2274 It is only useful if a -P switch is used.
2275 For example,
2277 @example
2278 gnatname -Pprj -f"*.c" "*.ada"
2279 @end example
2281 will look for Ada units in all files with the @code{.ada} extension,
2282 and will add to the list of file for project @code{prj.gpr} the C files
2283 with extension @code{.c}.
2285 @geindex -h (gnatname)
2287 @item @code{-h}
2289 Output usage (help) information. The output is written to @code{stdout}.
2291 @geindex -P (gnatname)
2293 @item @code{-P@emph{proj}}
2295 Create or update project file @code{proj}. There may be zero, one or more space
2296 between @emph{-P} and @code{proj}. @code{proj} may include directory
2297 information. @code{proj} must be writable.
2298 There may be only one switch @emph{-P}.
2299 When a switch @emph{-P} is specified,
2300 no switch @emph{-c} may be specified.
2301 On all platforms, except on VMS, when @cite{gnatname} is invoked for an
2302 existing project file <proj>.gpr, a backup copy of the project file is created
2303 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
2304 non negative number that makes this backup copy a new file.
2306 @geindex -v (gnatname)
2308 @item @code{-v}
2310 Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2311 This includes name of the file written, the name of the directories to search
2312 and, for each file in those directories whose name matches at least one of
2313 the Naming Patterns, an indication of whether the file contains a unit,
2314 and if so the name of the unit.
2315 @end table
2317 @geindex -v -v (gnatname)
2320 @table @asis
2322 @item @code{-v -v}
2324 Very Verbose mode. In addition to the output produced in verbose mode,
2325 for each file in the searched directories whose name matches none of
2326 the Naming Patterns, an indication is given that there is no match.
2328 @geindex -x (gnatname)
2330 @item @code{-x@emph{pattern}}
2332 Excluded patterns. Using this switch, it is possible to exclude some files
2333 that would match the name patterns. For example,
2335 @example
2336 gnatname -x "*_nt.ada" "*.ada"
2337 @end example
2339 will look for Ada units in all files with the @code{.ada} extension,
2340 except those whose names end with @code{_nt.ada}.
2341 @end table
2343 @node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2344 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{61}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{62}
2345 @subsubsection Examples of @cite{gnatname} Usage
2348 @example
2349 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2350 @end example
2352 In this example, the directory @code{/home/me} must already exist
2353 and be writable. In addition, the directory
2354 @code{/home/me/sources} (specified by
2355 @emph{-d sources}) must exist and be readable.
2357 Note the optional spaces after @emph{-c} and @emph{-d}.
2359 @example
2360 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
2361 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2362 @end example
2364 Note that several switches @emph{-d} may be used,
2365 even in conjunction with one or several switches
2366 @emph{-D}. Several Naming Patterns and one excluded pattern
2367 are used in this example.
2369 @node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2370 @anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{63}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{64}
2371 @subsection File Name Krunching with @cite{gnatkr}
2374 @geindex gnatkr
2376 This section discusses the method used by the compiler to shorten
2377 the default file names chosen for Ada units so that they do not
2378 exceed the maximum length permitted. It also describes the
2379 @cite{gnatkr} utility that can be used to determine the result of
2380 applying this shortening.
2382 @menu
2383 * About gnatkr:: 
2384 * Using gnatkr:: 
2385 * Krunching Method:: 
2386 * Examples of gnatkr Usage:: 
2388 @end menu
2390 @node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2391 @anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{66}
2392 @subsubsection About @cite{gnatkr}
2395 The default file naming rule in GNAT
2396 is that the file name must be derived from
2397 the unit name. The exact default rule is as follows:
2400 @itemize *
2402 @item 
2403 Take the unit name and replace all dots by hyphens.
2405 @item 
2406 If such a replacement occurs in the
2407 second character position of a name, and the first character is
2408 @code{a}, @code{g}, @code{s}, or @code{i},
2409 then replace the dot by the character
2410 @code{~} (tilde)
2411 instead of a minus.
2413 The reason for this exception is to avoid clashes
2414 with the standard names for children of System, Ada, Interfaces,
2415 and GNAT, which use the prefixes
2416 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
2417 respectively.
2418 @end itemize
2420 The @code{-gnatk@emph{nn}}
2421 switch of the compiler activates a 'krunching'
2422 circuit that limits file names to nn characters (where nn is a decimal
2423 integer).
2425 The @cite{gnatkr} utility can be used to determine the krunched name for
2426 a given file, when krunched to a specified maximum length.
2428 @node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2429 @anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{67}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{54}
2430 @subsubsection Using @cite{gnatkr}
2433 The @cite{gnatkr} command has the form:
2435 @example
2436 $ gnatkr `name` [`length`]
2437 @end example
2439 @cite{name} is the uncrunched file name, derived from the name of the unit
2440 in the standard manner described in the previous section (i.e., in particular
2441 all dots are replaced by hyphens). The file name may or may not have an
2442 extension (defined as a suffix of the form period followed by arbitrary
2443 characters other than period). If an extension is present then it will
2444 be preserved in the output. For example, when krunching @code{hellofile.ads}
2445 to eight characters, the result will be hellofil.ads.
2447 Note: for compatibility with previous versions of @cite{gnatkr} dots may
2448 appear in the name instead of hyphens, but the last dot will always be
2449 taken as the start of an extension. So if @cite{gnatkr} is given an argument
2450 such as @code{Hello.World.adb} it will be treated exactly as if the first
2451 period had been a hyphen, and for example krunching to eight characters
2452 gives the result @code{hellworl.adb}.
2454 Note that the result is always all lower case.
2455 Characters of the other case are folded as required.
2457 @cite{length} represents the length of the krunched name. The default
2458 when no argument is given is 8 characters. A length of zero stands for
2459 unlimited, in other words do not chop except for system files where the
2460 implied crunching length is always eight characters.
2462 The output is the krunched name. The output has an extension only if the
2463 original argument was a file name with an extension.
2465 @node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2466 @anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{68}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{69}
2467 @subsubsection Krunching Method
2470 The initial file name is determined by the name of the unit that the file
2471 contains. The name is formed by taking the full expanded name of the
2472 unit and replacing the separating dots with hyphens and
2473 using lowercase
2474 for all letters, except that a hyphen in the second character position is
2475 replaced by a tilde if the first character is
2476 @code{a}, @code{i}, @code{g}, or @code{s}.
2477 The extension is @cite{.ads} for a
2478 spec and @cite{.adb} for a body.
2479 Krunching does not affect the extension, but the file name is shortened to
2480 the specified length by following these rules:
2483 @itemize *
2485 @item 
2486 The name is divided into segments separated by hyphens, tildes or
2487 underscores and all hyphens, tildes, and underscores are
2488 eliminated. If this leaves the name short enough, we are done.
2490 @item 
2491 If the name is too long, the longest segment is located (left-most
2492 if there are two of equal length), and shortened by dropping
2493 its last character. This is repeated until the name is short enough.
2495 As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2496 to fit the name into 8 characters as required by some operating systems:
2498 @example
2499 our-strings-wide_fixed 22
2500 our strings wide fixed 19
2501 our string  wide fixed 18
2502 our strin   wide fixed 17
2503 our stri    wide fixed 16
2504 our stri    wide fixe  15
2505 our str     wide fixe  14
2506 our str     wid  fixe  13
2507 our str     wid  fix   12
2508 ou  str     wid  fix   11
2509 ou  st      wid  fix   10
2510 ou  st      wi   fix   9
2511 ou  st      wi   fi    8
2512 Final file name: oustwifi.adb
2513 @end example
2515 @item 
2516 The file names for all predefined units are always krunched to eight
2517 characters. The krunching of these predefined units uses the following
2518 special prefix replacements:
2521 @multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} 
2522 @item
2524 Prefix
2526 @tab
2528 Replacement
2530 @item
2532 @code{ada-}
2534 @tab
2536 @code{a-}
2538 @item
2540 @code{gnat-}
2542 @tab
2544 @code{g-}
2546 @item
2548 @code{interfac es-}
2550 @tab
2552 @code{i-}
2554 @item
2556 @code{system-}
2558 @tab
2560 @code{s-}
2562 @end multitable
2565 These system files have a hyphen in the second character position. That
2566 is why normal user files replace such a character with a
2567 tilde, to avoid confusion with system file names.
2569 As an example of this special rule, consider
2570 @code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2572 @example
2573 ada-strings-wide_fixed 22
2574 a-  strings wide fixed 18
2575 a-  string  wide fixed 17
2576 a-  strin   wide fixed 16
2577 a-  stri    wide fixed 15
2578 a-  stri    wide fixe  14
2579 a-  str     wide fixe  13
2580 a-  str     wid  fixe  12
2581 a-  str     wid  fix   11
2582 a-  st      wid  fix   10
2583 a-  st      wi   fix   9
2584 a-  st      wi   fi    8
2585 Final file name: a-stwifi.adb
2586 @end example
2587 @end itemize
2589 Of course no file shortening algorithm can guarantee uniqueness over all
2590 possible unit names, and if file name krunching is used then it is your
2591 responsibility to ensure that no name clashes occur. The utility
2592 program @cite{gnatkr} is supplied for conveniently determining the
2593 krunched name of a file.
2595 @node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2596 @anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{6a}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{6b}
2597 @subsubsection Examples of @cite{gnatkr} Usage
2600 @example
2601 $ gnatkr very_long_unit_name.ads      --> velounna.ads
2602 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
2603 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2604 $ gnatkr grandparent-parent-child     --> grparchi
2605 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2606 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2607 @end example
2609 @node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2610 @anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{36}
2611 @subsection Renaming Files with @cite{gnatchop}
2614 @geindex gnatchop
2616 This section discusses how to handle files with multiple units by using
2617 the @cite{gnatchop} utility. This utility is also useful in renaming
2618 files to meet the standard GNAT default file naming conventions.
2620 @menu
2621 * Handling Files with Multiple Units:: 
2622 * Operating gnatchop in Compilation Mode:: 
2623 * Command Line for gnatchop:: 
2624 * Switches for gnatchop:: 
2625 * Examples of gnatchop Usage:: 
2627 @end menu
2629 @node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2630 @anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{6d}@anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{6e}
2631 @subsubsection Handling Files with Multiple Units
2634 The basic compilation model of GNAT requires that a file submitted to the
2635 compiler have only one unit and there be a strict correspondence
2636 between the file name and the unit name.
2638 The @cite{gnatchop} utility allows both of these rules to be relaxed,
2639 allowing GNAT to process files which contain multiple compilation units
2640 and files with arbitrary file names. @cite{gnatchop}
2641 reads the specified file and generates one or more output files,
2642 containing one unit per file. The unit and the file name correspond,
2643 as required by GNAT.
2645 If you want to permanently restructure a set of 'foreign' files so that
2646 they match the GNAT rules, and do the remaining development using the
2647 GNAT structure, you can simply use @emph{gnatchop} once, generate the
2648 new set of files and work with them from that point on.
2650 Alternatively, if you want to keep your files in the 'foreign' format,
2651 perhaps to maintain compatibility with some other Ada compilation
2652 system, you can set up a procedure where you use @emph{gnatchop} each
2653 time you compile, regarding the source files that it writes as temporary
2654 files that you throw away.
2656 Note that if your file containing multiple units starts with a byte order
2657 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2658 will each start with a copy of this BOM, meaning that they can be compiled
2659 automatically in UTF-8 mode without needing to specify an explicit encoding.
2661 @node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2662 @anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{6f}@anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{70}
2663 @subsubsection Operating gnatchop in Compilation Mode
2666 The basic function of @cite{gnatchop} is to take a file with multiple units
2667 and split it into separate files. The boundary between files is reasonably
2668 clear, except for the issue of comments and pragmas. In default mode, the
2669 rule is that any pragmas between units belong to the previous unit, except
2670 that configuration pragmas always belong to the following unit. Any comments
2671 belong to the following unit. These rules
2672 almost always result in the right choice of
2673 the split point without needing to mark it explicitly and most users will
2674 find this default to be what they want. In this default mode it is incorrect to
2675 submit a file containing only configuration pragmas, or one that ends in
2676 configuration pragmas, to @cite{gnatchop}.
2678 However, using a special option to activate 'compilation mode',
2679 @cite{gnatchop}
2680 can perform another function, which is to provide exactly the semantics
2681 required by the RM for handling of configuration pragmas in a compilation.
2682 In the absence of configuration pragmas (at the main file level), this
2683 option has no effect, but it causes such configuration pragmas to be handled
2684 in a quite different manner.
2686 First, in compilation mode, if @cite{gnatchop} is given a file that consists of
2687 only configuration pragmas, then this file is appended to the
2688 @code{gnat.adc} file in the current directory. This behavior provides
2689 the required behavior described in the RM for the actions to be taken
2690 on submitting such a file to the compiler, namely that these pragmas
2691 should apply to all subsequent compilations in the same compilation
2692 environment. Using GNAT, the current directory, possibly containing a
2693 @code{gnat.adc} file is the representation
2694 of a compilation environment. For more information on the
2695 @code{gnat.adc} file, see @ref{56,,Handling of Configuration Pragmas}.
2697 Second, in compilation mode, if @cite{gnatchop}
2698 is given a file that starts with
2699 configuration pragmas, and contains one or more units, then these
2700 configuration pragmas are prepended to each of the chopped files. This
2701 behavior provides the required behavior described in the RM for the
2702 actions to be taken on compiling such a file, namely that the pragmas
2703 apply to all units in the compilation, but not to subsequently compiled
2704 units.
2706 Finally, if configuration pragmas appear between units, they are appended
2707 to the previous unit. This results in the previous unit being illegal,
2708 since the compiler does not accept configuration pragmas that follow
2709 a unit. This provides the required RM behavior that forbids configuration
2710 pragmas other than those preceding the first compilation unit of a
2711 compilation.
2713 For most purposes, @cite{gnatchop} will be used in default mode. The
2714 compilation mode described above is used only if you need exactly
2715 accurate behavior with respect to compilations, and you have files
2716 that contain multiple units and configuration pragmas. In this
2717 circumstance the use of @cite{gnatchop} with the compilation mode
2718 switch provides the required behavior, and is for example the mode
2719 in which GNAT processes the ACVC tests.
2721 @node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2722 @anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{72}
2723 @subsubsection Command Line for @cite{gnatchop}
2726 The @cite{gnatchop} command has the form:
2728 @example
2729 $ gnatchop switches file_name [file_name ...]
2730       [directory]
2731 @end example
2733 The only required argument is the file name of the file to be chopped.
2734 There are no restrictions on the form of this file name. The file itself
2735 contains one or more Ada units, in normal GNAT format, concatenated
2736 together. As shown, more than one file may be presented to be chopped.
2738 When run in default mode, @cite{gnatchop} generates one output file in
2739 the current directory for each unit in each of the files.
2741 @cite{directory}, if specified, gives the name of the directory to which
2742 the output files will be written. If it is not specified, all files are
2743 written to the current directory.
2745 For example, given a
2746 file called @code{hellofiles} containing
2748 @example
2749 procedure Hello;
2751 with Ada.Text_IO; use Ada.Text_IO;
2752 procedure Hello is
2753 begin
2754    Put_Line ("Hello");
2755 end Hello;
2756 @end example
2758 the command
2760 @example
2761 $ gnatchop hellofiles
2762 @end example
2764 generates two files in the current directory, one called
2765 @code{hello.ads} containing the single line that is the procedure spec,
2766 and the other called @code{hello.adb} containing the remaining text. The
2767 original file is not affected. The generated files can be compiled in
2768 the normal manner.
2770 When gnatchop is invoked on a file that is empty or that contains only empty
2771 lines and/or comments, gnatchop will not fail, but will not produce any
2772 new sources.
2774 For example, given a
2775 file called @code{toto.txt} containing
2777 @example
2778 --  Just a comment
2779 @end example
2781 the command
2783 @example
2784 $ gnatchop toto.txt
2785 @end example
2787 will not produce any new file and will result in the following warnings:
2789 @example
2790 toto.txt:1:01: warning: empty file, contains no compilation units
2791 no compilation units found
2792 no source files written
2793 @end example
2795 @node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2796 @anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{73}@anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{74}
2797 @subsubsection Switches for @cite{gnatchop}
2800 @emph{gnatchop} recognizes the following switches:
2802 @geindex --version (gnatchop)
2805 @table @asis
2807 @item @code{--version}
2809 Display Copyright and version, then exit disregarding all other options.
2810 @end table
2812 @geindex --help (gnatchop)
2815 @table @asis
2817 @item @code{--help}
2819 If @emph{--version} was not used, display usage, then exit disregarding
2820 all other options.
2821 @end table
2823 @geindex -c (gnatchop)
2826 @table @asis
2828 @item @code{-c}
2830 Causes @cite{gnatchop} to operate in compilation mode, in which
2831 configuration pragmas are handled according to strict RM rules. See
2832 previous section for a full description of this mode.
2834 @item @code{-gnat@emph{xxx}}
2836 This passes the given @emph{-gnat`xxx*` switch to `gnat` which is
2837 used to parse the given file. Not all `xxx` options make sense,
2838 but for example, the use of *-gnati2} allows @cite{gnatchop} to
2839 process a source file that uses Latin-2 coding for identifiers.
2841 @item @code{-h}
2843 Causes @cite{gnatchop} to generate a brief help summary to the standard
2844 output file showing usage information.
2845 @end table
2847 @geindex -k (gnatchop)
2850 @table @asis
2852 @item @code{-k@emph{mm}}
2854 Limit generated file names to the specified number @cite{mm}
2855 of characters.
2856 This is useful if the
2857 resulting set of files is required to be interoperable with systems
2858 which limit the length of file names.
2859 No space is allowed between the @emph{-k} and the numeric value. The numeric
2860 value may be omitted in which case a default of @emph{-k8},
2861 suitable for use
2862 with DOS-like file systems, is used. If no @emph{-k} switch
2863 is present then
2864 there is no limit on the length of file names.
2865 @end table
2867 @geindex -p (gnatchop)
2870 @table @asis
2872 @item @code{-p}
2874 Causes the file modification time stamp of the input file to be
2875 preserved and used for the time stamp of the output file(s). This may be
2876 useful for preserving coherency of time stamps in an environment where
2877 @cite{gnatchop} is used as part of a standard build process.
2878 @end table
2880 @geindex -q (gnatchop)
2883 @table @asis
2885 @item @code{-q}
2887 Causes output of informational messages indicating the set of generated
2888 files to be suppressed. Warnings and error messages are unaffected.
2889 @end table
2891 @geindex -r (gnatchop)
2893 @geindex Source_Reference pragmas
2896 @table @asis
2898 @item @code{-r}
2900 Generate @cite{Source_Reference} pragmas. Use this switch if the output
2901 files are regarded as temporary and development is to be done in terms
2902 of the original unchopped file. This switch causes
2903 @cite{Source_Reference} pragmas to be inserted into each of the
2904 generated files to refers back to the original file name and line number.
2905 The result is that all error messages refer back to the original
2906 unchopped file.
2907 In addition, the debugging information placed into the object file (when
2908 the @emph{-g} switch of @emph{gcc} or @emph{gnatmake} is
2909 specified)
2910 also refers back to this original file so that tools like profilers and
2911 debuggers will give information in terms of the original unchopped file.
2913 If the original file to be chopped itself contains
2914 a @cite{Source_Reference}
2915 pragma referencing a third file, then gnatchop respects
2916 this pragma, and the generated @cite{Source_Reference} pragmas
2917 in the chopped file refer to the original file, with appropriate
2918 line numbers. This is particularly useful when @cite{gnatchop}
2919 is used in conjunction with @cite{gnatprep} to compile files that
2920 contain preprocessing statements and multiple units.
2921 @end table
2923 @geindex -v (gnatchop)
2926 @table @asis
2928 @item @code{-v}
2930 Causes @cite{gnatchop} to operate in verbose mode. The version
2931 number and copyright notice are output, as well as exact copies of
2932 the gnat1 commands spawned to obtain the chop control information.
2933 @end table
2935 @geindex -w (gnatchop)
2938 @table @asis
2940 @item @code{-w}
2942 Overwrite existing file names. Normally @cite{gnatchop} regards it as a
2943 fatal error if there is already a file with the same name as a
2944 file it would otherwise output, in other words if the files to be
2945 chopped contain duplicated units. This switch bypasses this
2946 check, and causes all but the last instance of such duplicated
2947 units to be skipped.
2948 @end table
2950 @geindex --GCC= (gnatchop)
2953 @table @asis
2955 @item @code{--GCC=@emph{xxxx}}
2957 Specify the path of the GNAT parser to be used. When this switch is used,
2958 no attempt is made to add the prefix to the GNAT parser executable.
2959 @end table
2961 @node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
2962 @anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{75}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{76}
2963 @subsubsection Examples of @cite{gnatchop} Usage
2966 @example
2967 $ gnatchop -w hello_s.ada prerelease/files
2968 @end example
2970 Chops the source file @code{hello_s.ada}. The output files will be
2971 placed in the directory @code{prerelease/files},
2972 overwriting any
2973 files with matching names in that directory (no files in the current
2974 directory are modified).
2976 @example
2977 $ gnatchop archive
2978 @end example
2980 Chops the source file @code{archive}
2981 into the current directory. One
2982 useful application of @cite{gnatchop} is in sending sets of sources
2983 around, for example in email messages. The required sources are simply
2984 concatenated (for example, using a Unix @cite{cat}
2985 command), and then
2986 @emph{gnatchop} is used at the other end to reconstitute the original
2987 file names.
2989 @example
2990 $ gnatchop file1 file2 file3 direc
2991 @end example
2993 Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
2994 the resulting files in the directory @code{direc}. Note that if any units
2995 occur more than once anywhere within this set of files, an error message
2996 is generated, and no files are written. To override this check, use the
2997 @emph{-w} switch,
2998 in which case the last occurrence in the last file will
2999 be the one that is output, and earlier duplicate occurrences for a given
3000 unit will be skipped.
3002 @node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
3003 @anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{14}
3004 @section Configuration Pragmas
3007 @geindex Configuration pragmas
3009 @geindex Pragmas
3010 @geindex configuration
3012 Configuration pragmas include those pragmas described as
3013 such in the Ada Reference Manual, as well as
3014 implementation-dependent pragmas that are configuration pragmas.
3015 See the @cite{Implementation_Defined_Pragmas} chapter in the
3016 @cite{GNAT_Reference_Manual} for details on these
3017 additional GNAT-specific configuration pragmas.
3018 Most notably, the pragma @cite{Source_File_Name}, which allows
3019 specifying non-default names for source files, is a configuration
3020 pragma. The following is a complete list of configuration pragmas
3021 recognized by GNAT:
3023 @example
3024 Ada_83
3025 Ada_95
3026 Ada_05
3027 Ada_2005
3028 Ada_12
3029 Ada_2012
3030 Allow_Integer_Address
3031 Annotate
3032 Assertion_Policy
3033 Assume_No_Invalid_Values
3034 C_Pass_By_Copy
3035 Check_Name
3036 Check_Policy
3037 Compile_Time_Error
3038 Compile_Time_Warning
3039 Compiler_Unit
3040 Component_Alignment
3041 Convention_Identifier
3042 Debug_Policy
3043 Detect_Blocking
3044 Default_Storage_Pool
3045 Discard_Names
3046 Elaboration_Checks
3047 Eliminate
3048 Extend_System
3049 Extensions_Allowed
3050 External_Name_Casing
3051 Fast_Math
3052 Favor_Top_Level
3053 Float_Representation
3054 Implicit_Packing
3055 Initialize_Scalars
3056 Interrupt_State
3057 License
3058 Locking_Policy
3059 Long_Float
3060 No_Run_Time
3061 No_Strict_Aliasing
3062 Normalize_Scalars
3063 Optimize_Alignment
3064 Persistent_BSS
3065 Polling
3066 Priority_Specific_Dispatching
3067 Profile
3068 Profile_Warnings
3069 Propagate_Exceptions
3070 Queuing_Policy
3071 Ravenscar
3072 Rename_Pragma
3073 Restricted_Run_Time
3074 Restrictions
3075 Restrictions_Warnings
3076 Reviewable
3077 Short_Circuit_And_Or
3078 Source_File_Name
3079 Source_File_Name_Project
3080 SPARK_Mode
3081 Style_Checks
3082 Suppress
3083 Suppress_Exception_Locations
3084 Task_Dispatching_Policy
3085 Universal_Data
3086 Unsuppress
3087 Use_VADS_Size
3088 Validity_Checks
3089 Warnings
3090 Wide_Character_Encoding
3091 @end example
3093 @menu
3094 * Handling of Configuration Pragmas:: 
3095 * The Configuration Pragmas Files:: 
3097 @end menu
3099 @node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
3100 @anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{78}@anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{56}
3101 @subsection Handling of Configuration Pragmas
3104 Configuration pragmas may either appear at the start of a compilation
3105 unit, or they can appear in a configuration pragma file to apply to
3106 all compilations performed in a given compilation environment.
3108 GNAT also provides the @cite{gnatchop} utility to provide an automatic
3109 way to handle configuration pragmas following the semantics for
3110 compilations (that is, files with multiple units), described in the RM.
3111 See @ref{6f,,Operating gnatchop in Compilation Mode} for details.
3112 However, for most purposes, it will be more convenient to edit the
3113 @code{gnat.adc} file that contains configuration pragmas directly,
3114 as described in the following section.
3116 In the case of @cite{Restrictions} pragmas appearing as configuration
3117 pragmas in individual compilation units, the exact handling depends on
3118 the type of restriction.
3120 Restrictions that require partition-wide consistency (like
3121 @cite{No_Tasking}) are
3122 recognized wherever they appear
3123 and can be freely inherited, e.g. from a @emph{with}ed unit to the @emph{with}ing
3124 unit. This makes sense since the binder will in any case insist on seeing
3125 consistent use, so any unit not conforming to any restrictions that are
3126 anywhere in the partition will be rejected, and you might as well find
3127 that out at compile time rather than at bind time.
3129 For restrictions that do not require partition-wide consistency, e.g.
3130 SPARK or No_Implementation_Attributes, in general the restriction applies
3131 only to the unit in which the pragma appears, and not to any other units.
3133 The exception is No_Elaboration_Code which always applies to the entire
3134 object file from a compilation, i.e. to the body, spec, and all subunits.
3135 This restriction can be specified in a configuration pragma file, or it
3136 can be on the body and/or the spec (in eithe case it applies to all the
3137 relevant units). It can appear on a subunit only if it has previously
3138 appeared in the body of spec.
3140 @node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
3141 @anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{79}@anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{7a}
3142 @subsection The Configuration Pragmas Files
3145 @geindex gnat.adc
3147 In GNAT a compilation environment is defined by the current
3148 directory at the time that a compile command is given. This current
3149 directory is searched for a file whose name is @code{gnat.adc}. If
3150 this file is present, it is expected to contain one or more
3151 configuration pragmas that will be applied to the current compilation.
3152 However, if the switch @emph{-gnatA} is used, @code{gnat.adc} is not
3153 considered. When taken into account, @code{gnat.adc} is added to the
3154 dependencies, so that if @code{gnat.adc} is modified later, an invocation of
3155 @emph{gnatmake} will recompile the source.
3157 Configuration pragmas may be entered into the @code{gnat.adc} file
3158 either by running @cite{gnatchop} on a source file that consists only of
3159 configuration pragmas, or more conveniently by direct editing of the
3160 @code{gnat.adc} file, which is a standard format source file.
3162 Besides @code{gnat.adc}, additional files containing configuration
3163 pragmas may be applied to the current compilation using the switch
3164 @code{-gnatec=@emph{path}} where @cite{path} must designate an existing file that
3165 contains only configuration pragmas. These configuration pragmas are
3166 in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
3167 is present and switch @emph{-gnatA} is not used).
3169 It is allowable to specify several switches @emph{-gnatec=}, all of which
3170 will be taken into account.
3172 Files containing configuration pragmas specified with switches
3173 @emph{-gnatec=} are added to the dependencies, unless they are
3174 temporary files. A file is considered temporary if its name ends in
3175 @code{.tmp} or @code{.TMP}. Certain tools follow this naming
3176 convention because they pass information to @emph{gcc} via
3177 temporary files that are immediately deleted; it doesn't make sense to
3178 depend on a file that no longer exists. Such tools include
3179 @emph{gprbuild}, @emph{gnatmake}, and @emph{gnatcheck}.
3181 If you are using project file, a separate mechanism is provided using
3182 project attributes.
3184 @c --Comment:
3185 @c See :ref:`Specifying_Configuration_Pragmas` for more details.
3187 @node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
3188 @anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{7b}
3189 @section Generating Object Files
3192 An Ada program consists of a set of source files, and the first step in
3193 compiling the program is to generate the corresponding object files.
3194 These are generated by compiling a subset of these source files.
3195 The files you need to compile are the following:
3198 @itemize *
3200 @item 
3201 If a package spec has no body, compile the package spec to produce the
3202 object file for the package.
3204 @item 
3205 If a package has both a spec and a body, compile the body to produce the
3206 object file for the package. The source file for the package spec need
3207 not be compiled in this case because there is only one object file, which
3208 contains the code for both the spec and body of the package.
3210 @item 
3211 For a subprogram, compile the subprogram body to produce the object file
3212 for the subprogram. The spec, if one is present, is as usual in a
3213 separate file, and need not be compiled.
3214 @end itemize
3216 @geindex Subunits
3219 @itemize *
3221 @item 
3222 In the case of subunits, only compile the parent unit. A single object
3223 file is generated for the entire subunit tree, which includes all the
3224 subunits.
3226 @item 
3227 Compile child units independently of their parent units
3228 (though, of course, the spec of all the ancestor unit must be present in order
3229 to compile a child unit).
3231 @geindex Generics
3233 @item 
3234 Compile generic units in the same manner as any other units. The object
3235 files in this case are small dummy files that contain at most the
3236 flag used for elaboration checking. This is because GNAT always handles generic
3237 instantiation by means of macro expansion. However, it is still necessary to
3238 compile generic units, for dependency checking and elaboration purposes.
3239 @end itemize
3241 The preceding rules describe the set of files that must be compiled to
3242 generate the object files for a program. Each object file has the same
3243 name as the corresponding source file, except that the extension is
3244 @code{.o} as usual.
3246 You may wish to compile other files for the purpose of checking their
3247 syntactic and semantic correctness. For example, in the case where a
3248 package has a separate spec and body, you would not normally compile the
3249 spec. However, it is convenient in practice to compile the spec to make
3250 sure it is error-free before compiling clients of this spec, because such
3251 compilations will fail if there is an error in the spec.
3253 GNAT provides an option for compiling such files purely for the
3254 purposes of checking correctness; such compilations are not required as
3255 part of the process of building a program. To compile a file in this
3256 checking mode, use the @emph{-gnatc} switch.
3258 @node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3259 @anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{7c}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{41}
3260 @section Source Dependencies
3263 A given object file clearly depends on the source file which is compiled
3264 to produce it. Here we are using "depends" in the sense of a typical
3265 @cite{make} utility; in other words, an object file depends on a source
3266 file if changes to the source file require the object file to be
3267 recompiled.
3268 In addition to this basic dependency, a given object may depend on
3269 additional source files as follows:
3272 @itemize *
3274 @item 
3275 If a file being compiled @emph{with}s a unit @cite{X}, the object file
3276 depends on the file containing the spec of unit @cite{X}. This includes
3277 files that are @emph{with}ed implicitly either because they are parents
3278 of @emph{with}ed child units or they are run-time units required by the
3279 language constructs used in a particular unit.
3281 @item 
3282 If a file being compiled instantiates a library level generic unit, the
3283 object file depends on both the spec and body files for this generic
3284 unit.
3286 @item 
3287 If a file being compiled instantiates a generic unit defined within a
3288 package, the object file depends on the body file for the package as
3289 well as the spec file.
3290 @end itemize
3292 @geindex Inline
3294 @geindex -gnatn switch
3297 @itemize *
3299 @item 
3300 If a file being compiled contains a call to a subprogram for which
3301 pragma @cite{Inline} applies and inlining is activated with the
3302 @emph{-gnatn} switch, the object file depends on the file containing the
3303 body of this subprogram as well as on the file containing the spec. Note
3304 that for inlining to actually occur as a result of the use of this switch,
3305 it is necessary to compile in optimizing mode.
3307 @geindex -gnatN switch
3309 The use of @emph{-gnatN} activates  inlining optimization
3310 that is performed by the front end of the compiler. This inlining does
3311 not require that the code generation be optimized. Like @emph{-gnatn},
3312 the use of this switch generates additional dependencies.
3314 When using a gcc-based back end (in practice this means using any version
3315 of GNAT other than for the JVM, .NET or GNAAMP platforms), then the use of
3316 @emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
3317 Historically front end inlining was more extensive than the gcc back end
3318 inlining, but that is no longer the case.
3320 @item 
3321 If an object file @code{O} depends on the proper body of a subunit through
3322 inlining or instantiation, it depends on the parent unit of the subunit.
3323 This means that any modification of the parent unit or one of its subunits
3324 affects the compilation of @code{O}.
3326 @item 
3327 The object file for a parent unit depends on all its subunit body files.
3329 @item 
3330 The previous two rules meant that for purposes of computing dependencies and
3331 recompilation, a body and all its subunits are treated as an indivisible whole.
3333 These rules are applied transitively: if unit @cite{A} @emph{with}s
3334 unit @cite{B}, whose elaboration calls an inlined procedure in package
3335 @cite{C}, the object file for unit @cite{A} will depend on the body of
3336 @cite{C}, in file @code{c.adb}.
3338 The set of dependent files described by these rules includes all the
3339 files on which the unit is semantically dependent, as dictated by the
3340 Ada language standard. However, it is a superset of what the
3341 standard describes, because it includes generic, inline, and subunit
3342 dependencies.
3344 An object file must be recreated by recompiling the corresponding source
3345 file if any of the source files on which it depends are modified. For
3346 example, if the @cite{make} utility is used to control compilation,
3347 the rule for an Ada object file must mention all the source files on
3348 which the object file depends, according to the above definition.
3349 The determination of the necessary
3350 recompilations is done automatically when one uses @emph{gnatmake}.
3351 @end itemize
3353 @node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3354 @anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{7d}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{42}
3355 @section The Ada Library Information Files
3358 @geindex Ada Library Information files
3360 @geindex ALI files
3362 Each compilation actually generates two output files. The first of these
3363 is the normal object file that has a @code{.o} extension. The second is a
3364 text file containing full dependency information. It has the same
3365 name as the source file, but an @code{.ali} extension.
3366 This file is known as the Ada Library Information (@code{ALI}) file.
3367 The following information is contained in the @code{ALI} file.
3370 @itemize *
3372 @item 
3373 Version information (indicates which version of GNAT was used to compile
3374 the unit(s) in question)
3376 @item 
3377 Main program information (including priority and time slice settings,
3378 as well as the wide character encoding used during compilation).
3380 @item 
3381 List of arguments used in the @emph{gcc} command for the compilation
3383 @item 
3384 Attributes of the unit, including configuration pragmas used, an indication
3385 of whether the compilation was successful, exception model used etc.
3387 @item 
3388 A list of relevant restrictions applying to the unit (used for consistency)
3389 checking.
3391 @item 
3392 Categorization information (e.g., use of pragma @cite{Pure}).
3394 @item 
3395 Information on all @emph{with}ed units, including presence of
3396 Elaborate` or @cite{Elaborate_All} pragmas.
3398 @item 
3399 Information from any @cite{Linker_Options} pragmas used in the unit
3401 @item 
3402 Information on the use of @cite{Body_Version} or @cite{Version}
3403 attributes in the unit.
3405 @item 
3406 Dependency information. This is a list of files, together with
3407 time stamp and checksum information. These are files on which
3408 the unit depends in the sense that recompilation is required
3409 if any of these units are modified.
3411 @item 
3412 Cross-reference data. Contains information on all entities referenced
3413 in the unit. Used by tools like @cite{gnatxref} and @cite{gnatfind} to
3414 provide cross-reference information.
3415 @end itemize
3417 For a full detailed description of the format of the @code{ALI} file,
3418 see the source of the body of unit @cite{Lib.Writ}, contained in file
3419 @code{lib-writ.adb} in the GNAT compiler sources.
3421 @node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3422 @anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{7e}@anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{43}
3423 @section Binding an Ada Program
3426 When using languages such as C and C++, once the source files have been
3427 compiled the only remaining step in building an executable program
3428 is linking the object modules together. This means that it is possible to
3429 link an inconsistent version of a program, in which two units have
3430 included different versions of the same header.
3432 The rules of Ada do not permit such an inconsistent program to be built.
3433 For example, if two clients have different versions of the same package,
3434 it is illegal to build a program containing these two clients.
3435 These rules are enforced by the GNAT binder, which also determines an
3436 elaboration order consistent with the Ada rules.
3438 The GNAT binder is run after all the object files for a program have
3439 been created. It is given the name of the main program unit, and from
3440 this it determines the set of units required by the program, by reading the
3441 corresponding ALI files. It generates error messages if the program is
3442 inconsistent or if no valid order of elaboration exists.
3444 If no errors are detected, the binder produces a main program, in Ada by
3445 default, that contains calls to the elaboration procedures of those
3446 compilation unit that require them, followed by
3447 a call to the main program. This Ada program is compiled to generate the
3448 object file for the main program. The name of
3449 the Ada file is @code{b~xxx}.adb` (with the corresponding spec
3450 @code{b~xxx}.ads`) where @cite{xxx} is the name of the
3451 main program unit.
3453 Finally, the linker is used to build the resulting executable program,
3454 using the object from the main program from the bind step as well as the
3455 object files for the Ada units of the program.
3457 @node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3458 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{15}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{7f}
3459 @section GNAT and Libraries
3462 @geindex Library building and using
3464 This section describes how to build and use libraries with GNAT, and also shows
3465 how to recompile the GNAT run-time library. You should be familiar with the
3466 Project Manager facility (see the @emph{GNAT_Project_Manager} chapter of the
3467 @emph{GPRbuild User's Guide}) before reading this chapter.
3469 @menu
3470 * Introduction to Libraries in GNAT:: 
3471 * General Ada Libraries:: 
3472 * Stand-alone Ada Libraries:: 
3473 * Rebuilding the GNAT Run-Time Library:: 
3475 @end menu
3477 @node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3478 @anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{80}@anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{81}
3479 @subsection Introduction to Libraries in GNAT
3482 A library is, conceptually, a collection of objects which does not have its
3483 own main thread of execution, but rather provides certain services to the
3484 applications that use it. A library can be either statically linked with the
3485 application, in which case its code is directly included in the application,
3486 or, on platforms that support it, be dynamically linked, in which case
3487 its code is shared by all applications making use of this library.
3489 GNAT supports both types of libraries.
3490 In the static case, the compiled code can be provided in different ways. The
3491 simplest approach is to provide directly the set of objects resulting from
3492 compilation of the library source files. Alternatively, you can group the
3493 objects into an archive using whatever commands are provided by the operating
3494 system. For the latter case, the objects are grouped into a shared library.
3496 In the GNAT environment, a library has three types of components:
3499 @itemize *
3501 @item 
3502 Source files,
3504 @item 
3505 @code{ALI} files (see @ref{42,,The Ada Library Information Files}), and
3507 @item 
3508 Object files, an archive or a shared library.
3509 @end itemize
3511 A GNAT library may expose all its source files, which is useful for
3512 documentation purposes. Alternatively, it may expose only the units needed by
3513 an external user to make use of the library. That is to say, the specs
3514 reflecting the library services along with all the units needed to compile
3515 those specs, which can include generic bodies or any body implementing an
3516 inlined routine. In the case of @emph{stand-alone libraries} those exposed
3517 units are called @emph{interface units} (@ref{82,,Stand-alone Ada Libraries}).
3519 All compilation units comprising an application, including those in a library,
3520 need to be elaborated in an order partially defined by Ada's semantics. GNAT
3521 computes the elaboration order from the @code{ALI} files and this is why they
3522 constitute a mandatory part of GNAT libraries.
3523 @emph{Stand-alone libraries} are the exception to this rule because a specific
3524 library elaboration routine is produced independently of the application(s)
3525 using the library.
3527 @node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3528 @anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{83}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{84}
3529 @subsection General Ada Libraries
3532 @menu
3533 * Building a library:: 
3534 * Installing a library:: 
3535 * Using a library:: 
3537 @end menu
3539 @node Building a library,Installing a library,,General Ada Libraries
3540 @anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{85}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{86}
3541 @subsubsection Building a library
3544 The easiest way to build a library is to use the Project Manager,
3545 which supports a special type of project called a @emph{Library Project}
3546 (see the @emph{Library Projects} section in the @emph{GNAT Project Manager}
3547 chapter of the @emph{GPRbuild User's Guide}).
3549 A project is considered a library project, when two project-level attributes
3550 are defined in it: @cite{Library_Name} and @cite{Library_Dir}. In order to
3551 control different aspects of library configuration, additional optional
3552 project-level attributes can be specified:
3555 @itemize *
3557 @item 
3559 @table @asis
3561 @item @emph{Library_Kind}
3563 This attribute controls whether the library is to be static or dynamic
3564 @end table
3566 @item 
3568 @table @asis
3570 @item @emph{Library_Version}
3572 This attribute specifies the library version; this value is used
3573 during dynamic linking of shared libraries to determine if the currently
3574 installed versions of the binaries are compatible.
3575 @end table
3577 @item 
3578 @emph{Library_Options}
3580 @item 
3582 @table @asis
3584 @item @emph{Library_GCC}
3586 These attributes specify additional low-level options to be used during
3587 library generation, and redefine the actual application used to generate
3588 library.
3589 @end table
3590 @end itemize
3592 The GNAT Project Manager takes full care of the library maintenance task,
3593 including recompilation of the source files for which objects do not exist
3594 or are not up to date, assembly of the library archive, and installation of
3595 the library (i.e., copying associated source, object and @code{ALI} files
3596 to the specified location).
3598 Here is a simple library project file:
3600 @example
3601 project My_Lib is
3602   for Source_Dirs use ("src1", "src2");
3603   for Object_Dir use "obj";
3604   for Library_Name use "mylib";
3605   for Library_Dir use "lib";
3606   for Library_Kind use "dynamic";
3607 end My_lib;
3608 @end example
3610 and the compilation command to build and install the library:
3612 @example
3613 $ gnatmake -Pmy_lib
3614 @end example
3616 It is not entirely trivial to perform manually all the steps required to
3617 produce a library. We recommend that you use the GNAT Project Manager
3618 for this task. In special cases where this is not desired, the necessary
3619 steps are discussed below.
3621 There are various possibilities for compiling the units that make up the
3622 library: for example with a Makefile (@ref{1f,,Using the GNU make Utility}) or
3623 with a conventional script. For simple libraries, it is also possible to create
3624 a dummy main program which depends upon all the packages that comprise the
3625 interface of the library. This dummy main program can then be given to
3626 @emph{gnatmake}, which will ensure that all necessary objects are built.
3628 After this task is accomplished, you should follow the standard procedure
3629 of the underlying operating system to produce the static or shared library.
3631 Here is an example of such a dummy program:
3633 @example
3634 with My_Lib.Service1;
3635 with My_Lib.Service2;
3636 with My_Lib.Service3;
3637 procedure My_Lib_Dummy is
3638 begin
3639    null;
3640 end;
3641 @end example
3643 Here are the generic commands that will build an archive or a shared library.
3645 @example
3646 # compiling the library
3647 $ gnatmake -c my_lib_dummy.adb
3649 # we don't need the dummy object itself
3650 $ rm my_lib_dummy.o my_lib_dummy.ali
3652 # create an archive with the remaining objects
3653 $ ar rc libmy_lib.a *.o
3654 # some systems may require "ranlib" to be run as well
3656 # or create a shared library
3657 $ gcc -shared -o libmy_lib.so *.o
3658 # some systems may require the code to have been compiled with -fPIC
3660 # remove the object files that are now in the library
3661 $ rm *.o
3663 # Make the ALI files read-only so that gnatmake will not try to
3664 # regenerate the objects that are in the library
3665 $ chmod -w *.ali
3666 @end example
3668 Please note that the library must have a name of the form @code{lib@emph{xxx}.a}
3669 or @code{lib@emph{xxx}.so} (or @code{lib@emph{xxx}.dll} on Windows) in order to
3670 be accessed by the directive @code{-l@emph{xxx}} at link time.
3672 @node Installing a library,Using a library,Building a library,General Ada Libraries
3673 @anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{87}@anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{88}
3674 @subsubsection Installing a library
3677 @geindex ADA_PROJECT_PATH
3679 @geindex GPR_PROJECT_PATH
3681 If you use project files, library installation is part of the library build
3682 process (see the @emph{Installing a Library with Project Files} section of the
3683 @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}).
3685 When project files are not an option, it is also possible, but not recommended,
3686 to install the library so that the sources needed to use the library are on the
3687 Ada source path and the ALI files & libraries be on the Ada Object path (see
3688 @ref{89,,Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
3689 administrator can place general-purpose libraries in the default compiler
3690 paths, by specifying the libraries' location in the configuration files
3691 @code{ada_source_path} and @code{ada_object_path}. These configuration files
3692 must be located in the GNAT installation tree at the same place as the gcc spec
3693 file. The location of the gcc spec file can be determined as follows:
3695 @example
3696 $ gcc -v
3697 @end example
3699 The configuration files mentioned above have a simple format: each line
3700 must contain one unique directory name.
3701 Those names are added to the corresponding path
3702 in their order of appearance in the file. The names can be either absolute
3703 or relative; in the latter case, they are relative to where theses files
3704 are located.
3706 The files @code{ada_source_path} and @code{ada_object_path} might not be
3707 present in a
3708 GNAT installation, in which case, GNAT will look for its run-time library in
3709 the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3710 objects and @code{ALI} files). When the files exist, the compiler does not
3711 look in @code{adainclude} and @code{adalib}, and thus the
3712 @code{ada_source_path} file
3713 must contain the location for the GNAT run-time sources (which can simply
3714 be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3715 contain the location for the GNAT run-time objects (which can simply
3716 be @code{adalib}).
3718 You can also specify a new default path to the run-time library at compilation
3719 time with the switch @emph{--RTS=rts-path}. You can thus choose / change
3720 the run-time library you want your program to be compiled with. This switch is
3721 recognized by @emph{gcc}, @emph{gnatmake}, @emph{gnatbind},
3722 @emph{gnatls}, @emph{gnatfind} and @emph{gnatxref}.
3724 It is possible to install a library before or after the standard GNAT
3725 library, by reordering the lines in the configuration files. In general, a
3726 library must be installed before the GNAT library if it redefines
3727 any part of it.
3729 @node Using a library,,Installing a library,General Ada Libraries
3730 @anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{8a}@anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{8b}
3731 @subsubsection Using a library
3734 Once again, the project facility greatly simplifies the use of
3735 libraries. In this context, using a library is just a matter of adding a
3736 @emph{with} clause in the user project. For instance, to make use of the
3737 library @cite{My_Lib} shown in examples in earlier sections, you can
3738 write:
3740 @example
3741 with "my_lib";
3742 project My_Proj is
3743   ...
3744 end My_Proj;
3745 @end example
3747 Even if you have a third-party, non-Ada library, you can still use GNAT's
3748 Project Manager facility to provide a wrapper for it. For example, the
3749 following project, when @emph{with}ed by your main project, will link with the
3750 third-party library @code{liba.a}:
3752 @example
3753 project Liba is
3754    for Externally_Built use "true";
3755    for Source_Files use ();
3756    for Library_Dir use "lib";
3757    for Library_Name use "a";
3758    for Library_Kind use "static";
3759 end Liba;
3760 @end example
3762 This is an alternative to the use of @cite{pragma Linker_Options}. It is
3763 especially interesting in the context of systems with several interdependent
3764 static libraries where finding a proper linker order is not easy and best be
3765 left to the tools having visibility over project dependence information.
3767 In order to use an Ada library manually, you need to make sure that this
3768 library is on both your source and object path
3769 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}
3770 and @ref{8c,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3771 in an archive or a shared library, you need to specify the desired
3772 library at link time.
3774 For example, you can use the library @code{mylib} installed in
3775 @code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3777 @example
3778 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3779   -largs -lmy_lib
3780 @end example
3782 This can be expressed more simply:
3784 @example
3785 $ gnatmake my_appl
3786 @end example
3788 when the following conditions are met:
3791 @itemize *
3793 @item 
3794 @code{/dir/my_lib_src} has been added by the user to the environment
3795 variable 
3796 @geindex ADA_INCLUDE_PATH
3797 @geindex environment variable; ADA_INCLUDE_PATH
3798 @code{ADA_INCLUDE_PATH}, or by the administrator to the file
3799 @code{ada_source_path}
3801 @item 
3802 @code{/dir/my_lib_obj} has been added by the user to the environment
3803 variable 
3804 @geindex ADA_OBJECTS_PATH
3805 @geindex environment variable; ADA_OBJECTS_PATH
3806 @code{ADA_OBJECTS_PATH}, or by the administrator to the file
3807 @code{ada_object_path}
3809 @item 
3810 a pragma @cite{Linker_Options} has been added to one of the sources.
3811 For example:
3813 @example
3814 pragma Linker_Options ("-lmy_lib");
3815 @end example
3816 @end itemize
3818 Note that you may also load a library dynamically at
3819 run time given its filename, as illustrated in the GNAT @code{plugins} example
3820 in the directory @code{share/examples/gnat/plugins} within the GNAT
3821 install area.
3823 @node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3824 @anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{82}@anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{8d}
3825 @subsection Stand-alone Ada Libraries
3828 @geindex Stand-alone libraries
3830 @menu
3831 * Introduction to Stand-alone Libraries:: 
3832 * Building a Stand-alone Library:: 
3833 * Creating a Stand-alone Library to be used in a non-Ada context:: 
3834 * Restrictions in Stand-alone Libraries:: 
3836 @end menu
3838 @node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3839 @anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{8e}@anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{8f}
3840 @subsubsection Introduction to Stand-alone Libraries
3843 A Stand-alone Library (abbreviated 'SAL') is a library that contains the
3844 necessary code to
3845 elaborate the Ada units that are included in the library. In contrast with
3846 an ordinary library, which consists of all sources, objects and @code{ALI}
3847 files of the
3848 library, a SAL may specify a restricted subset of compilation units
3849 to serve as a library interface. In this case, the fully
3850 self-sufficient set of files will normally consist of an objects
3851 archive, the sources of interface units' specs, and the @code{ALI}
3852 files of interface units.
3853 If an interface spec contains a generic unit or an inlined subprogram,
3854 the body's
3855 source must also be provided; if the units that must be provided in the source
3856 form depend on other units, the source and @code{ALI} files of those must
3857 also be provided.
3859 The main purpose of a SAL is to minimize the recompilation overhead of client
3860 applications when a new version of the library is installed. Specifically,
3861 if the interface sources have not changed, client applications do not need to
3862 be recompiled. If, furthermore, a SAL is provided in the shared form and its
3863 version, controlled by @cite{Library_Version} attribute, is not changed,
3864 then the clients do not need to be relinked.
3866 SALs also allow the library providers to minimize the amount of library source
3867 text exposed to the clients.  Such 'information hiding' might be useful or
3868 necessary for various reasons.
3870 Stand-alone libraries are also well suited to be used in an executable whose
3871 main routine is not written in Ada.
3873 @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
3874 @anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{90}@anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{91}
3875 @subsubsection Building a Stand-alone Library
3878 GNAT's Project facility provides a simple way of building and installing
3879 stand-alone libraries; see the @emph{Stand-alone Library Projects} section
3880 in the @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}.
3881 To be a Stand-alone Library Project, in addition to the two attributes
3882 that make a project a Library Project (@cite{Library_Name} and
3883 @cite{Library_Dir}; see the @emph{Library Projects} section in the
3884 @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}),
3885 the attribute @cite{Library_Interface} must be defined.  For example:
3887 @example
3888 for Library_Dir use "lib_dir";
3889 for Library_Name use "dummy";
3890 for Library_Interface use ("int1", "int1.child");
3891 @end example
3893 Attribute @cite{Library_Interface} has a non-empty string list value,
3894 each string in the list designating a unit contained in an immediate source
3895 of the project file.
3897 When a Stand-alone Library is built, first the binder is invoked to build
3898 a package whose name depends on the library name
3899 (@code{b~dummy.ads/b} in the example above).
3900 This binder-generated package includes initialization and
3901 finalization procedures whose
3902 names depend on the library name (@cite{dummyinit} and @cite{dummyfinal}
3903 in the example
3904 above). The object corresponding to this package is included in the library.
3906 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
3907 calling of these procedures if a static SAL is built, or if a shared SAL
3908 is built
3909 with the project-level attribute @cite{Library_Auto_Init} set to
3910 @cite{"false"}.
3912 For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
3913 (those that are listed in attribute @cite{Library_Interface}) are copied to
3914 the Library Directory. As a consequence, only the Interface Units may be
3915 imported from Ada units outside of the library. If other units are imported,
3916 the binding phase will fail.
3918 It is also possible to build an encapsulated library where not only
3919 the code to elaborate and finalize the library is embedded but also
3920 ensuring that the library is linked only against static
3921 libraries. So an encapsulated library only depends on system
3922 libraries, all other code, including the GNAT runtime, is embedded. To
3923 build an encapsulated library the attribute
3924 @cite{Library_Standalone} must be set to @cite{encapsulated}:
3926 @example
3927 for Library_Dir use "lib_dir";
3928 for Library_Name use "dummy";
3929 for Library_Kind use "dynamic";
3930 for Library_Interface use ("int1", "int1.child");
3931 for Library_Standalone use "encapsulated";
3932 @end example
3934 The default value for this attribute is @cite{standard} in which case
3935 a stand-alone library is built.
3937 The attribute @cite{Library_Src_Dir} may be specified for a
3938 Stand-Alone Library. @cite{Library_Src_Dir} is a simple attribute that has a
3939 single string value. Its value must be the path (absolute or relative to the
3940 project directory) of an existing directory. This directory cannot be the
3941 object directory or one of the source directories, but it can be the same as
3942 the library directory. The sources of the Interface
3943 Units of the library that are needed by an Ada client of the library will be
3944 copied to the designated directory, called the Interface Copy directory.
3945 These sources include the specs of the Interface Units, but they may also
3946 include bodies and subunits, when pragmas @cite{Inline} or @cite{Inline_Always}
3947 are used, or when there is a generic unit in the spec. Before the sources
3948 are copied to the Interface Copy directory, an attempt is made to delete all
3949 files in the Interface Copy directory.
3951 Building stand-alone libraries by hand is somewhat tedious, but for those
3952 occasions when it is necessary here are the steps that you need to perform:
3955 @itemize *
3957 @item 
3958 Compile all library sources.
3960 @item 
3961 Invoke the binder with the switch @emph{-n} (No Ada main program),
3962 with all the @code{ALI} files of the interfaces, and
3963 with the switch @emph{-L} to give specific names to the @cite{init}
3964 and @cite{final} procedures.  For example:
3966 @example
3967 $ gnatbind -n int1.ali int2.ali -Lsal1
3968 @end example
3970 @item 
3971 Compile the binder generated file:
3973 @example
3974 $ gcc -c b~int2.adb
3975 @end example
3977 @item 
3978 Link the dynamic library with all the necessary object files,
3979 indicating to the linker the names of the @cite{init} (and possibly
3980 @cite{final}) procedures for automatic initialization (and finalization).
3981 The built library should be placed in a directory different from
3982 the object directory.
3984 @item 
3985 Copy the @cite{ALI} files of the interface to the library directory,
3986 add in this copy an indication that it is an interface to a SAL
3987 (i.e., add a word @emph{SL} on the line in the @code{ALI} file that starts
3988 with letter 'P') and make the modified copy of the @code{ALI} file
3989 read-only.
3990 @end itemize
3992 Using SALs is not different from using other libraries
3993 (see @ref{8a,,Using a library}).
3995 @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
3996 @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}
3997 @subsubsection Creating a Stand-alone Library to be used in a non-Ada context
4000 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
4001 a non-Ada context.
4003 The only extra step required is to ensure that library interface subprograms
4004 are compatible with the main program, by means of @cite{pragma Export}
4005 or @cite{pragma Convention}.
4007 Here is an example of simple library interface for use with C main program:
4009 @example
4010 package My_Package is
4012    procedure Do_Something;
4013    pragma Export (C, Do_Something, "do_something");
4015    procedure Do_Something_Else;
4016    pragma Export (C, Do_Something_Else, "do_something_else");
4018 end My_Package;
4019 @end example
4021 On the foreign language side, you must provide a 'foreign' view of the
4022 library interface; remember that it should contain elaboration routines in
4023 addition to interface subprograms.
4025 The example below shows the content of @cite{mylib_interface.h} (note
4026 that there is no rule for the naming of this file, any name can be used)
4028 @example
4029 /* the library elaboration procedure */
4030 extern void mylibinit (void);
4032 /* the library finalization procedure */
4033 extern void mylibfinal (void);
4035 /* the interface exported by the library */
4036 extern void do_something (void);
4037 extern void do_something_else (void);
4038 @end example
4040 Libraries built as explained above can be used from any program, provided
4041 that the elaboration procedures (named @cite{mylibinit} in the previous
4042 example) are called before the library services are used. Any number of
4043 libraries can be used simultaneously, as long as the elaboration
4044 procedure of each library is called.
4046 Below is an example of a C program that uses the @cite{mylib} library.
4048 @example
4049 #include "mylib_interface.h"
4052 main (void)
4054    /* First, elaborate the library before using it */
4055    mylibinit ();
4057    /* Main program, using the library exported entities */
4058    do_something ();
4059    do_something_else ();
4061    /* Library finalization at the end of the program */
4062    mylibfinal ();
4063    return 0;
4065 @end example
4067 Note that invoking any library finalization procedure generated by
4068 @cite{gnatbind} shuts down the Ada run-time environment.
4069 Consequently, the
4070 finalization of all Ada libraries must be performed at the end of the program.
4071 No call to these libraries or to the Ada run-time library should be made
4072 after the finalization phase.
4074 Note also that special care must be taken with multi-tasks
4075 applications. The initialization and finalization routines are not
4076 protected against concurrent access. If such requirement is needed it
4077 must be ensured at the application level using a specific operating
4078 system services like a mutex or a critical-section.
4080 @node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
4081 @anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{94}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{95}
4082 @subsubsection Restrictions in Stand-alone Libraries
4085 The pragmas listed below should be used with caution inside libraries,
4086 as they can create incompatibilities with other Ada libraries:
4089 @itemize *
4091 @item 
4092 pragma @cite{Locking_Policy}
4094 @item 
4095 pragma @cite{Partition_Elaboration_Policy}
4097 @item 
4098 pragma @cite{Queuing_Policy}
4100 @item 
4101 pragma @cite{Task_Dispatching_Policy}
4103 @item 
4104 pragma @cite{Unreserve_All_Interrupts}
4105 @end itemize
4107 When using a library that contains such pragmas, the user must make sure
4108 that all libraries use the same pragmas with the same values. Otherwise,
4109 @cite{Program_Error} will
4110 be raised during the elaboration of the conflicting
4111 libraries. The usage of these pragmas and its consequences for the user
4112 should therefore be well documented.
4114 Similarly, the traceback in the exception occurrence mechanism should be
4115 enabled or disabled in a consistent manner across all libraries.
4116 Otherwise, Program_Error will be raised during the elaboration of the
4117 conflicting libraries.
4119 If the @cite{Version} or @cite{Body_Version}
4120 attributes are used inside a library, then you need to
4121 perform a @cite{gnatbind} step that specifies all @code{ALI} files in all
4122 libraries, so that version identifiers can be properly computed.
4123 In practice these attributes are rarely used, so this is unlikely
4124 to be a consideration.
4126 @node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
4127 @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}
4128 @subsection Rebuilding the GNAT Run-Time Library
4131 @geindex GNAT Run-Time Library
4132 @geindex rebuilding
4134 @geindex Building the GNAT Run-Time Library
4136 @geindex Rebuilding the GNAT Run-Time Library
4138 @geindex Run-Time Library
4139 @geindex rebuilding
4141 It may be useful to recompile the GNAT library in various contexts, the
4142 most important one being the use of partition-wide configuration pragmas
4143 such as @cite{Normalize_Scalars}. A special Makefile called
4144 @cite{Makefile.adalib} is provided to that effect and can be found in
4145 the directory containing the GNAT library. The location of this
4146 directory depends on the way the GNAT environment has been installed and can
4147 be determined by means of the command:
4149 @example
4150 $ gnatls -v
4151 @end example
4153 The last entry in the object search path usually contains the
4154 gnat library. This Makefile contains its own documentation and in
4155 particular the set of instructions needed to rebuild a new library and
4156 to use it.
4158 @geindex Conditional compilation
4160 @node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
4161 @anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{98}@anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{16}
4162 @section Conditional Compilation
4165 This section presents some guidelines for modeling conditional compilation in Ada and describes the
4166 gnatprep preprocessor utility.
4168 @geindex Conditional compilation
4170 @menu
4171 * Modeling Conditional Compilation in Ada:: 
4172 * Preprocessing with gnatprep:: 
4173 * Integrated Preprocessing:: 
4175 @end menu
4177 @node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
4178 @anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{99}@anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{9a}
4179 @subsection Modeling Conditional Compilation in Ada
4182 It is often necessary to arrange for a single source program
4183 to serve multiple purposes, where it is compiled in different
4184 ways to achieve these different goals. Some examples of the
4185 need for this feature are
4188 @itemize *
4190 @item 
4191 Adapting a program to a different hardware environment
4193 @item 
4194 Adapting a program to a different target architecture
4196 @item 
4197 Turning debugging features on and off
4199 @item 
4200 Arranging for a program to compile with different compilers
4201 @end itemize
4203 In C, or C++, the typical approach would be to use the preprocessor
4204 that is defined as part of the language. The Ada language does not
4205 contain such a feature. This is not an oversight, but rather a very
4206 deliberate design decision, based on the experience that overuse of
4207 the preprocessing features in C and C++ can result in programs that
4208 are extremely difficult to maintain. For example, if we have ten
4209 switches that can be on or off, this means that there are a thousand
4210 separate programs, any one of which might not even be syntactically
4211 correct, and even if syntactically correct, the resulting program
4212 might not work correctly. Testing all combinations can quickly become
4213 impossible.
4215 Nevertheless, the need to tailor programs certainly exists, and in
4216 this section we will discuss how this can
4217 be achieved using Ada in general, and GNAT in particular.
4219 @menu
4220 * Use of Boolean Constants:: 
4221 * Debugging - A Special Case:: 
4222 * Conditionalizing Declarations:: 
4223 * Use of Alternative Implementations:: 
4224 * Preprocessing:: 
4226 @end menu
4228 @node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4229 @anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{9b}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{9c}
4230 @subsubsection Use of Boolean Constants
4233 In the case where the difference is simply which code
4234 sequence is executed, the cleanest solution is to use Boolean
4235 constants to control which code is executed.
4237 @example
4238 FP_Initialize_Required : constant Boolean := True;
4240 if FP_Initialize_Required then
4242 end if;
4243 @end example
4245 Not only will the code inside the @cite{if} statement not be executed if
4246 the constant Boolean is @cite{False}, but it will also be completely
4247 deleted from the program.
4248 However, the code is only deleted after the @cite{if} statement
4249 has been checked for syntactic and semantic correctness.
4250 (In contrast, with preprocessors the code is deleted before the
4251 compiler ever gets to see it, so it is not checked until the switch
4252 is turned on.)
4254 @geindex Preprocessors (contrasted with conditional compilation)
4256 Typically the Boolean constants will be in a separate package,
4257 something like:
4259 @example
4260 package Config is
4261    FP_Initialize_Required : constant Boolean := True;
4262    Reset_Available        : constant Boolean := False;
4263    ...
4264 end Config;
4265 @end example
4267 The @cite{Config} package exists in multiple forms for the various targets,
4268 with an appropriate script selecting the version of @cite{Config} needed.
4269 Then any other unit requiring conditional compilation can do a @emph{with}
4270 of @cite{Config} to make the constants visible.
4272 @node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4273 @anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{9d}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{9e}
4274 @subsubsection Debugging - A Special Case
4277 A common use of conditional code is to execute statements (for example
4278 dynamic checks, or output of intermediate results) under control of a
4279 debug switch, so that the debugging behavior can be turned on and off.
4280 This can be done using a Boolean constant to control whether the code
4281 is active:
4283 @example
4284 if Debugging then
4285    Put_Line ("got to the first stage!");
4286 end if;
4287 @end example
4291 @example
4292 if Debugging and then Temperature > 999.0 then
4293    raise Temperature_Crazy;
4294 end if;
4295 @end example
4297 @geindex pragma Assert
4299 Since this is a common case, there are special features to deal with
4300 this in a convenient manner. For the case of tests, Ada 2005 has added
4301 a pragma @cite{Assert} that can be used for such tests. This pragma is modeled
4302 on the @cite{Assert} pragma that has always been available in GNAT, so this
4303 feature may be used with GNAT even if you are not using Ada 2005 features.
4304 The use of pragma @cite{Assert} is described in the
4305 @cite{GNAT_Reference_Manual}, but as an
4306 example, the last test could be written:
4308 @example
4309 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4310 @end example
4312 or simply
4314 @example
4315 pragma Assert (Temperature <= 999.0);
4316 @end example
4318 In both cases, if assertions are active and the temperature is excessive,
4319 the exception @cite{Assert_Failure} will be raised, with the given string in
4320 the first case or a string indicating the location of the pragma in the second
4321 case used as the exception message.
4323 @geindex pragma Assertion_Policy
4325 You can turn assertions on and off by using the @cite{Assertion_Policy}
4326 pragma.
4328 @geindex -gnata switch
4330 This is an Ada 2005 pragma which is implemented in all modes by
4331 GNAT. Alternatively, you can use the @emph{-gnata} switch
4332 to enable assertions from the command line, which applies to
4333 all versions of Ada.
4335 @geindex pragma Debug
4337 For the example above with the @cite{Put_Line}, the GNAT-specific pragma
4338 @cite{Debug} can be used:
4340 @example
4341 pragma Debug (Put_Line ("got to the first stage!"));
4342 @end example
4344 If debug pragmas are enabled, the argument, which must be of the form of
4345 a procedure call, is executed (in this case, @cite{Put_Line} will be called).
4346 Only one call can be present, but of course a special debugging procedure
4347 containing any code you like can be included in the program and then
4348 called in a pragma @cite{Debug} argument as needed.
4350 One advantage of pragma @cite{Debug} over the @cite{if Debugging then}
4351 construct is that pragma @cite{Debug} can appear in declarative contexts,
4352 such as at the very beginning of a procedure, before local declarations have
4353 been elaborated.
4355 @geindex pragma Debug_Policy
4357 Debug pragmas are enabled using either the @emph{-gnata} switch that also
4358 controls assertions, or with a separate Debug_Policy pragma.
4360 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4361 in Ada 95 and Ada 83 programs as well), and is analogous to
4362 pragma @cite{Assertion_Policy} to control assertions.
4364 @cite{Assertion_Policy} and @cite{Debug_Policy} are configuration pragmas,
4365 and thus they can appear in @code{gnat.adc} if you are not using a
4366 project file, or in the file designated to contain configuration pragmas
4367 in a project file.
4368 They then apply to all subsequent compilations. In practice the use of
4369 the @emph{-gnata} switch is often the most convenient method of controlling
4370 the status of these pragmas.
4372 Note that a pragma is not a statement, so in contexts where a statement
4373 sequence is required, you can't just write a pragma on its own. You have
4374 to add a @cite{null} statement.
4376 @example
4377 if ... then
4378    ... -- some statements
4379 else
4380    pragma Assert (Num_Cases < 10);
4381    null;
4382 end if;
4383 @end example
4385 @node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4386 @anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{9f}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{a0}
4387 @subsubsection Conditionalizing Declarations
4390 In some cases it may be necessary to conditionalize declarations to meet
4391 different requirements. For example we might want a bit string whose length
4392 is set to meet some hardware message requirement.
4394 This may be possible using declare blocks controlled
4395 by conditional constants:
4397 @example
4398 if Small_Machine then
4399    declare
4400       X : Bit_String (1 .. 10);
4401    begin
4402       ...
4403    end;
4404 else
4405    declare
4406       X : Large_Bit_String (1 .. 1000);
4407    begin
4408       ...
4409    end;
4410 end if;
4411 @end example
4413 Note that in this approach, both declarations are analyzed by the
4414 compiler so this can only be used where both declarations are legal,
4415 even though one of them will not be used.
4417 Another approach is to define integer constants, e.g., @cite{Bits_Per_Word},
4418 or Boolean constants, e.g., @cite{Little_Endian}, and then write declarations
4419 that are parameterized by these constants. For example
4421 @example
4422 for Rec use
4423   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4424 end record;
4425 @end example
4427 If @cite{Bits_Per_Word} is set to 32, this generates either
4429 @example
4430 for Rec use
4431   Field1 at 0 range 0 .. 32;
4432 end record;
4433 @end example
4435 for the big endian case, or
4437 @example
4438 for Rec use record
4439     Field1 at 0 range 10 .. 32;
4440 end record;
4441 @end example
4443 for the little endian case. Since a powerful subset of Ada expression
4444 notation is usable for creating static constants, clever use of this
4445 feature can often solve quite difficult problems in conditionalizing
4446 compilation (note incidentally that in Ada 95, the little endian
4447 constant was introduced as @cite{System.Default_Bit_Order}, so you do not
4448 need to define this one yourself).
4450 @node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4451 @anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{a2}
4452 @subsubsection Use of Alternative Implementations
4455 In some cases, none of the approaches described above are adequate. This
4456 can occur for example if the set of declarations required is radically
4457 different for two different configurations.
4459 In this situation, the official Ada way of dealing with conditionalizing
4460 such code is to write separate units for the different cases. As long as
4461 this does not result in excessive duplication of code, this can be done
4462 without creating maintenance problems. The approach is to share common
4463 code as far as possible, and then isolate the code and declarations
4464 that are different. Subunits are often a convenient method for breaking
4465 out a piece of a unit that is to be conditionalized, with separate files
4466 for different versions of the subunit for different targets, where the
4467 build script selects the right one to give to the compiler.
4469 @geindex Subunits (and conditional compilation)
4471 As an example, consider a situation where a new feature in Ada 2005
4472 allows something to be done in a really nice way. But your code must be able
4473 to compile with an Ada 95 compiler. Conceptually you want to say:
4475 @example
4476 if Ada_2005 then
4477    ... neat Ada 2005 code
4478 else
4479    ... not quite as neat Ada 95 code
4480 end if;
4481 @end example
4483 where @cite{Ada_2005} is a Boolean constant.
4485 But this won't work when @cite{Ada_2005} is set to @cite{False},
4486 since the @cite{then} clause will be illegal for an Ada 95 compiler.
4487 (Recall that although such unreachable code would eventually be deleted
4488 by the compiler, it still needs to be legal.  If it uses features
4489 introduced in Ada 2005, it will be illegal in Ada 95.)
4491 So instead we write
4493 @example
4494 procedure Insert is separate;
4495 @end example
4497 Then we have two files for the subunit @cite{Insert}, with the two sets of
4498 code.
4499 If the package containing this is called @cite{File_Queries}, then we might
4500 have two files
4503 @itemize *
4505 @item 
4506 @code{file_queries-insert-2005.adb}
4508 @item 
4509 @code{file_queries-insert-95.adb}
4510 @end itemize
4512 and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4514 This can also be done with project files' naming schemes. For example:
4516 @example
4517 for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4518 @end example
4520 Note also that with project files it is desirable to use a different extension
4521 than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4522 conflict may arise through another commonly used feature: to declare as part
4523 of the project a set of directories containing all the sources obeying the
4524 default naming scheme.
4526 The use of alternative units is certainly feasible in all situations,
4527 and for example the Ada part of the GNAT run-time is conditionalized
4528 based on the target architecture using this approach. As a specific example,
4529 consider the implementation of the AST feature in VMS. There is one
4530 spec: @code{s-asthan.ads} which is the same for all architectures, and three
4531 bodies:
4534 @itemize *
4536 @item 
4538 @table @asis
4540 @item @code{s-asthan.adb}
4542 used for all non-VMS operating systems
4543 @end table
4545 @item 
4547 @table @asis
4549 @item @code{s-asthan-vms-alpha.adb}
4551 used for VMS on the Alpha
4552 @end table
4554 @item 
4556 @table @asis
4558 @item @code{s-asthan-vms-ia64.adb}
4560 used for VMS on the ia64
4561 @end table
4562 @end itemize
4564 The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4565 this operating system feature is not available, and the two remaining
4566 versions interface with the corresponding versions of VMS to provide
4567 VMS-compatible AST handling. The GNAT build script knows the architecture
4568 and operating system, and automatically selects the right version,
4569 renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4571 Another style for arranging alternative implementations is through Ada's
4572 access-to-subprogram facility.
4573 In case some functionality is to be conditionally included,
4574 you can declare an access-to-procedure variable @cite{Ref} that is initialized
4575 to designate a 'do nothing' procedure, and then invoke @cite{Ref.all}
4576 when appropriate.
4577 In some library package, set @cite{Ref} to @cite{Proc'Access} for some
4578 procedure @cite{Proc} that performs the relevant processing.
4579 The initialization only occurs if the library package is included in the
4580 program.
4581 The same idea can also be implemented using tagged types and dispatching
4582 calls.
4584 @node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4585 @anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{a3}@anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{a4}
4586 @subsubsection Preprocessing
4589 @geindex Preprocessing
4591 Although it is quite possible to conditionalize code without the use of
4592 C-style preprocessing, as described earlier in this section, it is
4593 nevertheless convenient in some cases to use the C approach. Moreover,
4594 older Ada compilers have often provided some preprocessing capability,
4595 so legacy code may depend on this approach, even though it is not
4596 standard.
4598 To accommodate such use, GNAT provides a preprocessor (modeled to a large
4599 extent on the various preprocessors that have been used
4600 with legacy code on other compilers, to enable easier transition).
4602 @geindex gnatprep
4604 The preprocessor may be used in two separate modes. It can be used quite
4605 separately from the compiler, to generate a separate output source file
4606 that is then fed to the compiler as a separate step. This is the
4607 @cite{gnatprep} utility, whose use is fully described in
4608 @ref{17,,Preprocessing with gnatprep}.
4610 The preprocessing language allows such constructs as
4612 @example
4613 #if DEBUG or else (PRIORITY > 4) then
4614    sequence of declarations
4615 #else
4616    completely different sequence of declarations
4617 #end if;
4618 @end example
4620 The values of the symbols @cite{DEBUG} and @cite{PRIORITY} can be
4621 defined either on the command line or in a separate file.
4623 The other way of running the preprocessor is even closer to the C style and
4624 often more convenient. In this approach the preprocessing is integrated into
4625 the compilation process. The compiler is given the preprocessor input which
4626 includes @cite{#if} lines etc, and then the compiler carries out the
4627 preprocessing internally and processes the resulting output.
4628 For more details on this approach, see @ref{18,,Integrated Preprocessing}.
4630 @node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4631 @anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{17}
4632 @subsection Preprocessing with @cite{gnatprep}
4635 @geindex gnatprep
4637 @geindex Preprocessing (gnatprep)
4639 This section discusses how to use GNAT's @cite{gnatprep} utility for simple
4640 preprocessing.
4641 Although designed for use with GNAT, @cite{gnatprep} does not depend on any
4642 special GNAT features.
4643 For further discussion of conditional compilation in general, see
4644 @ref{16,,Conditional Compilation}.
4646 @menu
4647 * Preprocessing Symbols:: 
4648 * Using gnatprep:: 
4649 * Switches for gnatprep:: 
4650 * Form of Definitions File:: 
4651 * Form of Input Text for gnatprep:: 
4653 @end menu
4655 @node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4656 @anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{a6}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{a7}
4657 @subsubsection Preprocessing Symbols
4660 Preprocessing symbols are defined in @emph{definition files} and referenced in the
4661 sources to be preprocessed. A preprocessing symbol is an identifier, following
4662 normal Ada (case-insensitive) rules for its syntax, with the restriction that
4663 all characters need to be in the ASCII set (no accented letters).
4665 @node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4666 @anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{a8}@anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{a9}
4667 @subsubsection Using @cite{gnatprep}
4670 To call @cite{gnatprep} use:
4672 @example
4673 $ gnatprep [`switches`] `infile` `outfile` [`deffile`]
4674 @end example
4676 where
4679 @itemize *
4681 @item 
4683 @table @asis
4685 @item @emph{switches}
4687 is an optional sequence of switches as described in the next section.
4688 @end table
4690 @item 
4692 @table @asis
4694 @item @emph{infile}
4696 is the full name of the input file, which is an Ada source
4697 file containing preprocessor directives.
4698 @end table
4700 @item 
4702 @table @asis
4704 @item @emph{outfile}
4706 is the full name of the output file, which is an Ada source
4707 in standard Ada form. When used with GNAT, this file name will
4708 normally have an @emph{ads} or @emph{adb} suffix.
4709 @end table
4711 @item 
4713 @table @asis
4715 @item @emph{deffile}
4717 is the full name of a text file containing definitions of
4718 preprocessing symbols to be referenced by the preprocessor. This argument is
4719 optional, and can be replaced by the use of the @emph{-D} switch.
4720 @end table
4721 @end itemize
4723 @node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4724 @anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{aa}@anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{ab}
4725 @subsubsection Switches for @cite{gnatprep}
4728 @geindex --version (gnatprep)
4731 @table @asis
4733 @item @code{--version}
4735 Display Copyright and version, then exit disregarding all other options.
4736 @end table
4738 @geindex --help (gnatprep)
4741 @table @asis
4743 @item @code{--help}
4745 If @code{--version} was not used, display usage and then exit disregarding
4746 all other options.
4747 @end table
4749 @geindex -b (gnatprep)
4752 @table @asis
4754 @item @code{-b}
4756 Causes both preprocessor lines and the lines deleted by
4757 preprocessing to be replaced by blank lines in the output source file,
4758 preserving line numbers in the output file.
4759 @end table
4761 @geindex -c (gnatprep)
4764 @table @asis
4766 @item @code{-c}
4768 Causes both preprocessor lines and the lines deleted
4769 by preprocessing to be retained in the output source as comments marked
4770 with the special string @cite{"--! "}. This option will result in line numbers
4771 being preserved in the output file.
4772 @end table
4774 @geindex -C (gnatprep)
4777 @table @asis
4779 @item @code{-C}
4781 Causes comments to be scanned. Normally comments are ignored by gnatprep.
4782 If this option is specified, then comments are scanned and any $symbol
4783 substitutions performed as in program text. This is particularly useful
4784 when structured comments are used (e.g., for programs written in a
4785 pre-2014 version of the SPARK Ada subset). Note that this switch is not
4786 available when  doing integrated preprocessing (it would be useless in
4787 this context since comments are ignored by the compiler in any case).
4788 @end table
4790 @geindex -D (gnatprep)
4793 @table @asis
4795 @item @code{-D@emph{symbol}[=@emph{value}]}
4797 Defines a new preprocessing symbol with the specified value. If no value is given
4798 on the command line, then symbol is considered to be @cite{True}. This switch
4799 can be used in place of a definition file.
4800 @end table
4802 @geindex -r (gnatprep)
4805 @table @asis
4807 @item @code{-r}
4809 Causes a @cite{Source_Reference} pragma to be generated that
4810 references the original input file, so that error messages will use
4811 the file name of this original file. The use of this switch implies
4812 that preprocessor lines are not to be removed from the file, so its
4813 use will force @emph{-b} mode if @emph{-c}
4814 has not been specified explicitly.
4816 Note that if the file to be preprocessed contains multiple units, then
4817 it will be necessary to @cite{gnatchop} the output file from
4818 @cite{gnatprep}. If a @cite{Source_Reference} pragma is present
4819 in the preprocessed file, it will be respected by
4820 @cite{gnatchop -r}
4821 so that the final chopped files will correctly refer to the original
4822 input source file for @cite{gnatprep}.
4823 @end table
4825 @geindex -s (gnatprep)
4828 @table @asis
4830 @item @code{-s}
4832 Causes a sorted list of symbol names and values to be
4833 listed on the standard output file.
4834 @end table
4836 @geindex -T (gnatprep)
4839 @table @asis
4841 @item @code{-T}
4843 Use LF as line terminators when writing files. By default the line terminator
4844 of the host (LF under unix, CR/LF under Windows) is used.
4845 @end table
4847 @geindex -u (gnatprep)
4850 @table @asis
4852 @item @code{-u}
4854 Causes undefined symbols to be treated as having the value FALSE in the context
4855 of a preprocessor test. In the absence of this option, an undefined symbol in
4856 a @cite{#if} or @cite{#elsif} test will be treated as an error.
4857 @end table
4859 @geindex -v (gnatprep)
4862 @table @asis
4864 @item @code{-v}
4866 Verbose mode: generates more output about work done.
4867 @end table
4869 Note: if neither @emph{-b} nor @emph{-c} is present,
4870 then preprocessor lines and
4871 deleted lines are completely removed from the output, unless -r is
4872 specified, in which case -b is assumed.
4874 @node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4875 @anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{ad}
4876 @subsubsection Form of Definitions File
4879 The definitions file contains lines of the form:
4881 @example
4882 symbol := value
4883 @end example
4885 where @cite{symbol} is a preprocessing symbol, and @cite{value} is one of the following:
4888 @itemize *
4890 @item 
4891 Empty, corresponding to a null substitution,
4893 @item 
4894 A string literal using normal Ada syntax, or
4896 @item 
4897 Any sequence of characters from the set @{letters, digits, period, underline@}.
4898 @end itemize
4900 Comment lines may also appear in the definitions file, starting with
4901 the usual @code{--},
4902 and comments may be added to the definitions lines.
4904 @node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4905 @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}
4906 @subsubsection Form of Input Text for @cite{gnatprep}
4909 The input text may contain preprocessor conditional inclusion lines,
4910 as well as general symbol substitution sequences.
4912 The preprocessor conditional inclusion commands have the form:
4914 @example
4915 #if <expression> [then]
4916    lines
4917 #elsif <expression> [then]
4918    lines
4919 #elsif <expression> [then]
4920    lines
4922 #else
4923    lines
4924 #end if;
4925 @end example
4927 In this example, <expression> is defined by the following grammar:
4929 @example
4930 <expression> ::=  <symbol>
4931 <expression> ::=  <symbol> = "<value>"
4932 <expression> ::=  <symbol> = <symbol>
4933 <expression> ::=  <symbol> = <integer>
4934 <expression> ::=  <symbol> > <integer>
4935 <expression> ::=  <symbol> >= <integer>
4936 <expression> ::=  <symbol> < <integer>
4937 <expression> ::=  <symbol> <= <integer>
4938 <expression> ::=  <symbol> 'Defined
4939 <expression> ::=  not <expression>
4940 <expression> ::=  <expression> and <expression>
4941 <expression> ::=  <expression> or <expression>
4942 <expression> ::=  <expression> and then <expression>
4943 <expression> ::=  <expression> or else <expression>
4944 <expression> ::=  ( <expression> )
4945 @end example
4947 Note the following restriction: it is not allowed to have "and" or "or"
4948 following "not" in the same expression without parentheses. For example, this
4949 is not allowed:
4951 @example
4952 not X or Y
4953 @end example
4955 This can be expressed instead as one of the following forms:
4957 @example
4958 (not X) or Y
4959 not (X or Y)
4960 @end example
4962 For the first test (<expression> ::= <symbol>) the symbol must have
4963 either the value true or false, that is to say the right-hand of the
4964 symbol definition must be one of the (case-insensitive) literals
4965 @cite{True} or @cite{False}. If the value is true, then the
4966 corresponding lines are included, and if the value is false, they are
4967 excluded.
4969 When comparing a symbol to an integer, the integer is any non negative
4970 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
4971 2#11#. The symbol value must also be a non negative integer. Integer values
4972 in the range 0 .. 2**31-1 are supported.
4974 The test (<expression> ::= <symbol>'Defined) is true only if
4975 the symbol has been defined in the definition file or by a @emph{-D}
4976 switch on the command line. Otherwise, the test is false.
4978 The equality tests are case insensitive, as are all the preprocessor lines.
4980 If the symbol referenced is not defined in the symbol definitions file,
4981 then the effect depends on whether or not switch @emph{-u}
4982 is specified. If so, then the symbol is treated as if it had the value
4983 false and the test fails. If this switch is not specified, then
4984 it is an error to reference an undefined symbol. It is also an error to
4985 reference a symbol that is defined with a value other than @cite{True}
4986 or @cite{False}.
4988 The use of the @cite{not} operator inverts the sense of this logical test.
4989 The @cite{not} operator cannot be combined with the @cite{or} or @cite{and}
4990 operators, without parentheses. For example, "if not X or Y then" is not
4991 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
4993 The @cite{then} keyword is optional as shown
4995 The @cite{#} must be the first non-blank character on a line, but
4996 otherwise the format is free form. Spaces or tabs may appear between
4997 the @cite{#} and the keyword. The keywords and the symbols are case
4998 insensitive as in normal Ada code. Comments may be used on a
4999 preprocessor line, but other than that, no other tokens may appear on a
5000 preprocessor line. Any number of @cite{elsif} clauses can be present,
5001 including none at all. The @cite{else} is optional, as in Ada.
5003 The @cite{#} marking the start of a preprocessor line must be the first
5004 non-blank character on the line, i.e., it must be preceded only by
5005 spaces or horizontal tabs.
5007 Symbol substitution outside of preprocessor lines is obtained by using
5008 the sequence:
5010 @example
5011 $symbol
5012 @end example
5014 anywhere within a source line, except in a comment or within a
5015 string literal. The identifier
5016 following the @cite{$} must match one of the symbols defined in the symbol
5017 definition file, and the result is to substitute the value of the
5018 symbol in place of @cite{$symbol} in the output file.
5020 Note that although the substitution of strings within a string literal
5021 is not possible, it is possible to have a symbol whose defined value is
5022 a string literal. So instead of setting XYZ to @cite{hello} and writing:
5024 @example
5025 Header : String := "$XYZ";
5026 @end example
5028 you should set XYZ to @cite{"hello"} and write:
5030 @example
5031 Header : String := $XYZ;
5032 @end example
5034 and then the substitution will occur as desired.
5036 @node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
5037 @anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{b0}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{18}
5038 @subsection Integrated Preprocessing
5041 As noted above, a file to be preprocessed consists of Ada source code
5042 in which preprocessing lines have been inserted. However,
5043 instead of using @emph{gnatprep} to explicitly preprocess a file as a separate
5044 step before compilation, you can carry out the preprocessing implicitly
5045 as part of compilation. Such @emph{integrated preprocessing}, which is the common
5046 style with C, is performed when either or both of the following switches
5047 are passed to the compiler:
5049 @quotation
5052 @itemize *
5054 @item 
5055 @code{-gnatep}, which specifies the @emph{preprocessor data file}.
5056 This file dictates how the source files will be preprocessed (e.g., which
5057 symbol definition files apply to which sources).
5059 @item 
5060 @code{-gnateD}, which defines values for preprocessing symbols.
5061 @end itemize
5062 @end quotation
5064 Integrated preprocessing applies only to Ada source files, it is
5065 not available for configuration pragma files.
5067 With integrated preprocessing, the output from the preprocessor is not,
5068 by default, written to any external file. Instead it is passed
5069 internally to the compiler. To preserve the result of
5070 preprocessing in a file, either run @emph{gnatprep}
5071 in standalone mode or else supply the @code{-gnateG} switch
5072 (described below) to the compiler.
5074 The @emph{gnatmake} switch @code{-s} should be used with integrated
5075 preprocessing; otherwise the use of a different preprocessor data file
5076 without changing the sources will not cause recompilation.
5078 Note that the @emph{gnatmake} switch @code{-m} will almost
5079 always trigger recompilation for sources that are preprocessed,
5080 because @emph{gnatmake} cannot compute the checksum of the source after
5081 preprocessing.
5083 The actual preprocessing function is described in detail in
5084 @ref{17,,Preprocessing with gnatprep}. This section explains the switches
5085 that relate to integrated preprocessing.
5087 @geindex -gnatep (gcc)
5090 @table @asis
5092 @item @code{-gnatep=@emph{preprocessor_data_file}}
5094 This switch specifies the file name (without directory
5095 information) of the preprocessor data file. Either place this file
5096 in one of the source directories, or, when using project
5097 files, reference the project file's directory via the
5098 @code{project_name'Project_Dir} project attribute; e.g:
5100 @quotation
5102 @example
5103 project Prj is
5104    package Compiler is
5105       for Switches ("Ada") use
5106         ("-gnatep=" & Prj'Project_Dir & "prep.def");
5107    end Compiler;
5108 end Prj;
5109 @end example
5110 @end quotation
5112 A preprocessor data file is a text file that contains @emph{preprocessor
5113 control lines}.  A preprocessor control line directs the preprocessing of
5114 either a particular source file, or, analogous to @emph{others} in Ada,
5115 all sources not specified elsewhere in  the preprocessor data file.
5116 A preprocessor control line
5117 can optionally identify a @emph{definition file} that assigns values to
5118 preprocessor symbols, as well as a list of switches that relate to
5119 preprocessing.
5120 Empty lines and comments (using Ada syntax) are also permitted, with no
5121 semantic effect.
5123 Here's an example of a preprocessor data file:
5125 @quotation
5127 @example
5128 "toto.adb"  "prep.def" -u
5129 --  Preprocess toto.adb, using definition file prep.def
5130 --  Undefined symbols are treated as False
5132 * -c -DVERSION=V101
5133 --  Preprocess all other sources without using a definition file
5134 --  Suppressed lined are commented
5135 --  Symbol VERSION has the value V101
5137 "tata.adb" "prep2.def" -s
5138 --  Preprocess tata.adb, using definition file prep2.def
5139 --  List all symbols with their values
5140 @end example
5141 @end quotation
5143 A preprocessor control line has the following syntax:
5145 @quotation
5147 @example
5148 <preprocessor_control_line> ::=
5149    <preprocessor_input> [ <definition_file_name> ] @{ <switch> @}
5151 <preprocessor_input> ::= <source_file_name> | '*'
5153 <definition_file_name> ::= <string_literal>
5155 <source_file_name> := <string_literal>
5157 <switch> := (See below for list)
5158 @end example
5159 @end quotation
5161 Thus  each preprocessor control line starts with either a literal string or
5162 the character '*':
5165 @itemize *
5167 @item 
5168 A literal string is the file name (without directory information) of the source
5169 file that will be input to the preprocessor.
5171 @item 
5172 The character '*' is a wild-card indicator; the additional parameters on the line
5173 indicate the preprocessing for all the sources
5174 that are not specified explicitly on other lines (the order of the lines is not
5175 significant).
5176 @end itemize
5178 It is an error to have two lines with the same file name or two
5179 lines starting with the character '*'.
5181 After the file name or '*', an optional literal string specifies the name of
5182 the definition file to be used for preprocessing
5183 (@ref{ac,,Form of Definitions File}). The definition files are found by the
5184 compiler in one of the source directories. In some cases, when compiling
5185 a source in a directory other than the current directory, if the definition
5186 file is in the current directory, it may be necessary to add the current
5187 directory as a source directory through the @code{-I} switch; otherwise
5188 the compiler would not find the definition file.
5190 Finally, switches similar to those of @emph{gnatprep} may optionally appear:
5193 @table @asis
5195 @item @code{-b}
5197 Causes both preprocessor lines and the lines deleted by
5198 preprocessing to be replaced by blank lines, preserving the line number.
5199 This switch is always implied; however, if specified after @code{-c}
5200 it cancels the effect of @code{-c}.
5202 @item @code{-c}
5204 Causes both preprocessor lines and the lines deleted
5205 by preprocessing to be retained as comments marked
5206 with the special string '@cite{--!}'.
5208 @item @code{-D@emph{symbol}=@emph{new_value}}
5210 Define or redefine @emph{symbol} to have @emph{new_value} as its value.
5211 The permitted form for @emph{symbol} is either an Ada identifier, or any Ada reserved word
5212 aside from @cite{if},
5213 @cite{else}, @cite{elsif}, @cite{end}, @cite{and}, @cite{or} and @cite{then}.
5214 The permitted form for @cite{new_value} is a literal string, an Ada identifier or any Ada reserved
5215 word. A symbol declared with this switch replaces a symbol with the
5216 same name defined in a definition file.
5218 @item @code{-s}
5220 Causes a sorted list of symbol names and values to be
5221 listed on the standard output file.
5223 @item @code{-u}
5225 Causes undefined symbols to be treated as having the value @cite{FALSE}
5226 in the context
5227 of a preprocessor test. In the absence of this option, an undefined symbol in
5228 a @cite{#if} or @cite{#elsif} test will be treated as an error.
5229 @end table
5230 @end table
5232 @geindex -gnateD (gcc)
5235 @table @asis
5237 @item @code{-gnateD@emph{symbol}[=@emph{new_value}]}
5239 Define or redefine @emph{symbol} to have @emph{new_value} as its value. If no value
5240 is supplied, then the value of @emph{symbol} is @cite{True}.
5241 The form of @emph{symbol} is an identifier, following normal Ada (case-insensitive)
5242 rules for its syntax, and @emph{new_value} is either an arbitrary string between double
5243 quotes or any sequence (including an empty sequence) of characters from the
5244 set (letters, digits, period, underline).
5245 Ada reserved words may be used as symbols, with the exceptions of @cite{if},
5246 @cite{else}, @cite{elsif}, @cite{end}, @cite{and}, @cite{or} and @cite{then}.
5248 Examples:
5250 @quotation
5252 @example
5253 -gnateDToto=Tata
5254 -gnateDFoo
5255 -gnateDFoo=\"Foo-Bar\"
5256 @end example
5257 @end quotation
5259 A symbol declared with this switch on the command line replaces a
5260 symbol with the same name either in a definition file or specified with a
5261 switch @code{-D} in the preprocessor data file.
5263 This switch is similar to switch @code{-D} of @cite{gnatprep}.
5265 @item @code{-gnateG}
5267 When integrated preprocessing is performed on source file @code{filename.extension},
5268 create or overwrite @code{filename.extension.prep} to contain
5269 the result of the preprocessing.
5270 For example if the source file is @code{foo.adb} then
5271 the output file will be @code{foo.adb.prep}.
5272 @end table
5274 @node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5275 @anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{44}@anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{b1}
5276 @section Mixed Language Programming
5279 @geindex Mixed Language Programming
5281 This section describes how to develop a mixed-language program,
5282 with a focus on combining Ada with C or C++.
5284 @menu
5285 * Interfacing to C:: 
5286 * Calling Conventions:: 
5287 * Building Mixed Ada and C++ Programs:: 
5288 * Generating Ada Bindings for C and C++ headers:: 
5289 * Generating C Headers for Ada Specifications:: 
5291 @end menu
5293 @node Interfacing to C,Calling Conventions,,Mixed Language Programming
5294 @anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{b2}@anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{b3}
5295 @subsection Interfacing to C
5298 Interfacing Ada with a foreign language such as C involves using
5299 compiler directives to import and/or export entity definitions in each
5300 language -- using @cite{extern} statements in C, for instance, and the
5301 @cite{Import}, @cite{Export}, and @cite{Convention} pragmas in Ada.
5302 A full treatment of these topics is provided in Appendix B, section 1
5303 of the Ada Reference Manual.
5305 There are two ways to build a program using GNAT that contains some Ada
5306 sources and some foreign language sources, depending on whether or not
5307 the main subprogram is written in Ada.  Here is a source example with
5308 the main subprogram in Ada:
5310 @example
5311 /* file1.c */
5312 #include <stdio.h>
5314 void print_num (int num)
5316   printf ("num is %d.\\n", num);
5317   return;
5319 @end example
5321 @example
5322 /* file2.c */
5324 /* num_from_Ada is declared in my_main.adb */
5325 extern int num_from_Ada;
5327 int get_num (void)
5329   return num_from_Ada;
5331 @end example
5333 @example
5334 --  my_main.adb
5335 procedure My_Main is
5337    --  Declare then export an Integer entity called num_from_Ada
5338    My_Num : Integer := 10;
5339    pragma Export (C, My_Num, "num_from_Ada");
5341    --  Declare an Ada function spec for Get_Num, then use
5342    --  C function get_num for the implementation.
5343    function Get_Num return Integer;
5344    pragma Import (C, Get_Num, "get_num");
5346    --  Declare an Ada procedure spec for Print_Num, then use
5347    --  C function print_num for the implementation.
5348    procedure Print_Num (Num : Integer);
5349    pragma Import (C, Print_Num, "print_num");
5351 begin
5352    Print_Num (Get_Num);
5353 end My_Main;
5354 @end example
5356 To build this example:
5359 @itemize *
5361 @item 
5362 First compile the foreign language files to
5363 generate object files:
5365 @example
5366 $ gcc -c file1.c
5367 $ gcc -c file2.c
5368 @end example
5370 @item 
5371 Then, compile the Ada units to produce a set of object files and ALI
5372 files:
5374 @example
5375 $ gnatmake -c my_main.adb
5376 @end example
5378 @item 
5379 Run the Ada binder on the Ada main program:
5381 @example
5382 $ gnatbind my_main.ali
5383 @end example
5385 @item 
5386 Link the Ada main program, the Ada objects and the other language
5387 objects:
5389 @example
5390 $ gnatlink my_main.ali file1.o file2.o
5391 @end example
5392 @end itemize
5394 The last three steps can be grouped in a single command:
5396 @example
5397 $ gnatmake my_main.adb -largs file1.o file2.o
5398 @end example
5400 @geindex Binder output file
5402 If the main program is in a language other than Ada, then you may have
5403 more than one entry point into the Ada subsystem. You must use a special
5404 binder option to generate callable routines that initialize and
5405 finalize the Ada units (@ref{b4,,Binding with Non-Ada Main Programs}).
5406 Calls to the initialization and finalization routines must be inserted
5407 in the main program, or some other appropriate point in the code. The
5408 call to initialize the Ada units must occur before the first Ada
5409 subprogram is called, and the call to finalize the Ada units must occur
5410 after the last Ada subprogram returns. The binder will place the
5411 initialization and finalization subprograms into the
5412 @code{b~xxx.adb} file where they can be accessed by your C
5413 sources.  To illustrate, we have the following example:
5415 @example
5416 /* main.c */
5417 extern void adainit (void);
5418 extern void adafinal (void);
5419 extern int add (int, int);
5420 extern int sub (int, int);
5422 int main (int argc, char *argv[])
5424    int a = 21, b = 7;
5426    adainit();
5428    /* Should print "21 + 7 = 28" */
5429    printf ("%d + %d = %d\\n", a, b, add (a, b));
5431    /* Should print "21 - 7 = 14" */
5432    printf ("%d - %d = %d\\n", a, b, sub (a, b));
5434    adafinal();
5436 @end example
5438 @example
5439 --  unit1.ads
5440 package Unit1 is
5441    function Add (A, B : Integer) return Integer;
5442    pragma Export (C, Add, "add");
5443 end Unit1;
5444 @end example
5446 @example
5447 --  unit1.adb
5448 package body Unit1 is
5449    function Add (A, B : Integer) return Integer is
5450    begin
5451       return A + B;
5452    end Add;
5453 end Unit1;
5454 @end example
5456 @example
5457 --  unit2.ads
5458 package Unit2 is
5459    function Sub (A, B : Integer) return Integer;
5460    pragma Export (C, Sub, "sub");
5461 end Unit2;
5462 @end example
5464 @example
5465 --  unit2.adb
5466 package body Unit2 is
5467    function Sub (A, B : Integer) return Integer is
5468    begin
5469       return A - B;
5470    end Sub;
5471 end Unit2;
5472 @end example
5474 The build procedure for this application is similar to the last
5475 example's:
5478 @itemize *
5480 @item 
5481 First, compile the foreign language files to generate object files:
5483 @example
5484 $ gcc -c main.c
5485 @end example
5487 @item 
5488 Next, compile the Ada units to produce a set of object files and ALI
5489 files:
5491 @example
5492 $ gnatmake -c unit1.adb
5493 $ gnatmake -c unit2.adb
5494 @end example
5496 @item 
5497 Run the Ada binder on every generated ALI file.  Make sure to use the
5498 @code{-n} option to specify a foreign main program:
5500 @example
5501 $ gnatbind -n unit1.ali unit2.ali
5502 @end example
5504 @item 
5505 Link the Ada main program, the Ada objects and the foreign language
5506 objects. You need only list the last ALI file here:
5508 @example
5509 $ gnatlink unit2.ali main.o -o exec_file
5510 @end example
5512 This procedure yields a binary executable called @code{exec_file}.
5513 @end itemize
5515 Depending on the circumstances (for example when your non-Ada main object
5516 does not provide symbol @cite{main}), you may also need to instruct the
5517 GNAT linker not to include the standard startup objects by passing the
5518 @code{-nostartfiles} switch to @cite{gnatlink}.
5520 @node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5521 @anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{b5}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{b6}
5522 @subsection Calling Conventions
5525 @geindex Foreign Languages
5527 @geindex Calling Conventions
5529 GNAT follows standard calling sequence conventions and will thus interface
5530 to any other language that also follows these conventions. The following
5531 Convention identifiers are recognized by GNAT:
5533 @geindex Interfacing to Ada
5535 @geindex Other Ada compilers
5537 @geindex Convention Ada
5540 @table @asis
5542 @item @emph{Ada}
5544 This indicates that the standard Ada calling sequence will be
5545 used and all Ada data items may be passed without any limitations in the
5546 case where GNAT is used to generate both the caller and callee. It is also
5547 possible to mix GNAT generated code and code generated by another Ada
5548 compiler. In this case, the data types should be restricted to simple
5549 cases, including primitive types. Whether complex data types can be passed
5550 depends on the situation. Probably it is safe to pass simple arrays, such
5551 as arrays of integers or floats. Records may or may not work, depending
5552 on whether both compilers lay them out identically. Complex structures
5553 involving variant records, access parameters, tasks, or protected types,
5554 are unlikely to be able to be passed.
5556 Note that in the case of GNAT running
5557 on a platform that supports HP Ada 83, a higher degree of compatibility
5558 can be guaranteed, and in particular records are laid out in an identical
5559 manner in the two compilers. Note also that if output from two different
5560 compilers is mixed, the program is responsible for dealing with elaboration
5561 issues. Probably the safest approach is to write the main program in the
5562 version of Ada other than GNAT, so that it takes care of its own elaboration
5563 requirements, and then call the GNAT-generated adainit procedure to ensure
5564 elaboration of the GNAT components. Consult the documentation of the other
5565 Ada compiler for further details on elaboration.
5567 However, it is not possible to mix the tasking run time of GNAT and
5568 HP Ada 83, All the tasking operations must either be entirely within
5569 GNAT compiled sections of the program, or entirely within HP Ada 83
5570 compiled sections of the program.
5571 @end table
5573 @geindex Interfacing to Assembly
5575 @geindex Convention Assembler
5578 @table @asis
5580 @item @emph{Assembler}
5582 Specifies assembler as the convention. In practice this has the
5583 same effect as convention Ada (but is not equivalent in the sense of being
5584 considered the same convention).
5585 @end table
5587 @geindex Convention Asm
5589 @geindex Asm
5592 @table @asis
5594 @item @emph{Asm}
5596 Equivalent to Assembler.
5598 @geindex Interfacing to COBOL
5600 @geindex Convention COBOL
5601 @end table
5603 @geindex COBOL
5606 @table @asis
5608 @item @emph{COBOL}
5610 Data will be passed according to the conventions described
5611 in section B.4 of the Ada Reference Manual.
5612 @end table
5614 @geindex C
5616 @geindex Interfacing to C
5618 @geindex Convention C
5621 @table @asis
5623 @item @emph{C}
5625 Data will be passed according to the conventions described
5626 in section B.3 of the Ada Reference Manual.
5628 A note on interfacing to a C 'varargs' function:
5630 @quotation
5632 @geindex C varargs function
5634 @geindex Interfacing to C varargs function
5636 @geindex varargs function interfaces
5638 In C, @cite{varargs} allows a function to take a variable number of
5639 arguments. There is no direct equivalent in this to Ada. One
5640 approach that can be used is to create a C wrapper for each
5641 different profile and then interface to this C wrapper. For
5642 example, to print an @cite{int} value using @cite{printf},
5643 create a C function @cite{printfi} that takes two arguments, a
5644 pointer to a string and an int, and calls @cite{printf}.
5645 Then in the Ada program, use pragma @cite{Import} to
5646 interface to @cite{printfi}.
5648 It may work on some platforms to directly interface to
5649 a @cite{varargs} function by providing a specific Ada profile
5650 for a particular call. However, this does not work on
5651 all platforms, since there is no guarantee that the
5652 calling sequence for a two argument normal C function
5653 is the same as for calling a @cite{varargs} C function with
5654 the same two arguments.
5655 @end quotation
5656 @end table
5658 @geindex Convention Default
5660 @geindex Default
5663 @table @asis
5665 @item @emph{Default}
5667 Equivalent to C.
5668 @end table
5670 @geindex Convention External
5672 @geindex External
5675 @table @asis
5677 @item @emph{External}
5679 Equivalent to C.
5680 @end table
5682 @geindex C++
5684 @geindex Interfacing to C++
5686 @geindex Convention C++
5689 @table @asis
5691 @item @emph{C_Plus_Plus (or CPP)}
5693 This stands for C++. For most purposes this is identical to C.
5694 See the separate description of the specialized GNAT pragmas relating to
5695 C++ interfacing for further details.
5696 @end table
5698 @geindex Fortran
5700 @geindex Interfacing to Fortran
5702 @geindex Convention Fortran
5705 @table @asis
5707 @item @emph{Fortran}
5709 Data will be passed according to the conventions described
5710 in section B.5 of the Ada Reference Manual.
5712 @item @emph{Intrinsic}
5714 This applies to an intrinsic operation, as defined in the Ada
5715 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5716 this means that the body of the subprogram is provided by the compiler itself,
5717 usually by means of an efficient code sequence, and that the user does not
5718 supply an explicit body for it. In an application program, the pragma may
5719 be applied to the following sets of names:
5722 @itemize *
5724 @item 
5725 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5726 The corresponding subprogram declaration must have
5727 two formal parameters. The
5728 first one must be a signed integer type or a modular type with a binary
5729 modulus, and the second parameter must be of type Natural.
5730 The return type must be the same as the type of the first argument. The size
5731 of this type can only be 8, 16, 32, or 64.
5733 @item 
5734 Binary arithmetic operators: '+', '-', '*', '/'.
5735 The corresponding operator declaration must have parameters and result type
5736 that have the same root numeric type (for example, all three are long_float
5737 types). This simplifies the definition of operations that use type checking
5738 to perform dimensional checks:
5739 @end itemize
5741 @example
5742   type Distance is new Long_Float;
5743   type Time     is new Long_Float;
5744   type Velocity is new Long_Float;
5745   function "/" (D : Distance; T : Time)
5746     return Velocity;
5747   pragma Import (Intrinsic, "/");
5749 This common idiom is often programmed with a generic definition and an
5750 explicit body. The pragma makes it simpler to introduce such declarations.
5751 It incurs no overhead in compilation time or code size, because it is
5752 implemented as a single machine instruction.
5753 @end example
5756 @itemize *
5758 @item 
5759 General subprogram entities. This is used  to bind an Ada subprogram
5760 declaration to
5761 a compiler builtin by name with back-ends where such interfaces are
5762 available. A typical example is the set of @cite{__builtin} functions
5763 exposed by the GCC back-end, as in the following example:
5765 @example
5766 function builtin_sqrt (F : Float) return Float;
5767 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5768 @end example
5770 Most of the GCC builtins are accessible this way, and as for other
5771 import conventions (e.g. C), it is the user's responsibility to ensure
5772 that the Ada subprogram profile matches the underlying builtin
5773 expectations.
5774 @end itemize
5775 @end table
5777 @geindex Stdcall
5779 @geindex Convention Stdcall
5782 @table @asis
5784 @item @emph{Stdcall}
5786 This is relevant only to Windows implementations of GNAT,
5787 and specifies that the @cite{Stdcall} calling sequence will be used,
5788 as defined by the NT API. Nevertheless, to ease building
5789 cross-platform bindings this convention will be handled as a @cite{C} calling
5790 convention on non-Windows platforms.
5791 @end table
5793 @geindex DLL
5795 @geindex Convention DLL
5798 @table @asis
5800 @item @emph{DLL}
5802 This is equivalent to @cite{Stdcall}.
5803 @end table
5805 @geindex Win32
5807 @geindex Convention Win32
5810 @table @asis
5812 @item @emph{Win32}
5814 This is equivalent to @cite{Stdcall}.
5815 @end table
5817 @geindex Stubbed
5819 @geindex Convention Stubbed
5822 @table @asis
5824 @item @emph{Stubbed}
5826 This is a special convention that indicates that the compiler
5827 should provide a stub body that raises @cite{Program_Error}.
5828 @end table
5830 GNAT additionally provides a useful pragma @cite{Convention_Identifier}
5831 that can be used to parameterize conventions and allow additional synonyms
5832 to be specified. For example if you have legacy code in which the convention
5833 identifier Fortran77 was used for Fortran, you can use the configuration
5834 pragma:
5836 @example
5837 pragma Convention_Identifier (Fortran77, Fortran);
5838 @end example
5840 And from now on the identifier Fortran77 may be used as a convention
5841 identifier (for example in an @cite{Import} pragma) with the same
5842 meaning as Fortran.
5844 @node Building Mixed Ada and C++ Programs,Generating Ada Bindings for C and C++ headers,Calling Conventions,Mixed Language Programming
5845 @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}
5846 @subsection Building Mixed Ada and C++ Programs
5849 A programmer inexperienced with mixed-language development may find that
5850 building an application containing both Ada and C++ code can be a
5851 challenge.  This section gives a few hints that should make this task easier.
5853 @menu
5854 * Interfacing to C++:: 
5855 * Linking a Mixed C++ & Ada Program:: 
5856 * A Simple Example:: 
5857 * Interfacing with C++ constructors:: 
5858 * Interfacing with C++ at the Class Level:: 
5860 @end menu
5862 @node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5863 @anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{b9}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{ba}
5864 @subsubsection Interfacing to C++
5867 GNAT supports interfacing with the G++ compiler (or any C++ compiler
5868 generating code that is compatible with the G++ Application Binary
5869 Interface ---see @indicateurl{http://www.codesourcery.com/archives/cxx-abi}).
5871 Interfacing can be done at 3 levels: simple data, subprograms, and
5872 classes. In the first two cases, GNAT offers a specific @cite{Convention C_Plus_Plus}
5873 (or @cite{CPP}) that behaves exactly like @cite{Convention C}.
5874 Usually, C++ mangles the names of subprograms. To generate proper mangled
5875 names automatically, see @ref{19,,Generating Ada Bindings for C and C++ headers}).
5876 This problem can also be addressed manually in two ways:
5879 @itemize *
5881 @item 
5882 by modifying the C++ code in order to force a C convention using
5883 the @cite{extern "C"} syntax.
5885 @item 
5886 by figuring out the mangled name (using e.g. @emph{nm}) and using it as the
5887 Link_Name argument of the pragma import.
5888 @end itemize
5890 Interfacing at the class level can be achieved by using the GNAT specific
5891 pragmas such as @cite{CPP_Constructor}.  See the @cite{GNAT_Reference_Manual} for additional information.
5893 @node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5894 @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}
5895 @subsubsection Linking a Mixed C++ & Ada Program
5898 Usually the linker of the C++ development system must be used to link
5899 mixed applications because most C++ systems will resolve elaboration
5900 issues (such as calling constructors on global class instances)
5901 transparently during the link phase. GNAT has been adapted to ease the
5902 use of a foreign linker for the last phase. Three cases can be
5903 considered:
5906 @itemize *
5908 @item 
5909 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5910 The C++ linker can simply be called by using the C++ specific driver
5911 called @cite{g++}.
5913 Note that if the C++ code uses inline functions, you will need to
5914 compile your C++ code with the @cite{-fkeep-inline-functions} switch in
5915 order to provide an existing function implementation that the Ada code can
5916 link with.
5918 @example
5919 $ g++ -c -fkeep-inline-functions file1.C
5920 $ g++ -c -fkeep-inline-functions file2.C
5921 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5922 @end example
5924 @item 
5925 Using GNAT and G++ from two different GCC installations: If both
5926 compilers are on the :envvar`PATH`, the previous method may be used. It is
5927 important to note that environment variables such as
5928 @geindex C_INCLUDE_PATH
5929 @geindex environment variable; C_INCLUDE_PATH
5930 @code{C_INCLUDE_PATH}, 
5931 @geindex GCC_EXEC_PREFIX
5932 @geindex environment variable; GCC_EXEC_PREFIX
5933 @code{GCC_EXEC_PREFIX},
5934 @geindex BINUTILS_ROOT
5935 @geindex environment variable; BINUTILS_ROOT
5936 @code{BINUTILS_ROOT}, and
5937 @geindex GCC_ROOT
5938 @geindex environment variable; GCC_ROOT
5939 @code{GCC_ROOT} will affect both compilers
5940 at the same time and may make one of the two compilers operate
5941 improperly if set during invocation of the wrong compiler.  It is also
5942 very important that the linker uses the proper @code{libgcc.a} GCC
5943 library -- that is, the one from the C++ compiler installation. The
5944 implicit link command as suggested in the @cite{gnatmake} command
5945 from the former example can be replaced by an explicit link command with
5946 the full-verbosity option in order to verify which library is used:
5948 @example
5949 $ gnatbind ada_unit
5950 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5951 @end example
5953 If there is a problem due to interfering environment variables, it can
5954 be worked around by using an intermediate script. The following example
5955 shows the proper script to use when GNAT has not been installed at its
5956 default location and g++ has been installed at its default location:
5958 @example
5959 $ cat ./my_script
5960 #!/bin/sh
5961 unset BINUTILS_ROOT
5962 unset GCC_ROOT
5963 c++ $*
5964 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5965 @end example
5967 @item 
5968 Using a non-GNU C++ compiler: The commands previously described can be
5969 used to insure that the C++ linker is used. Nonetheless, you need to add
5970 a few more parameters to the link command line, depending on the exception
5971 mechanism used.
5973 If the @cite{setjmp/longjmp} exception mechanism is used, only the paths
5974 to the libgcc libraries are required:
5976 @example
5977 $ cat ./my_script
5978 #!/bin/sh
5979 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
5980 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5981 @end example
5983 where CC is the name of the non-GNU C++ compiler.
5985 If the @cite{zero cost} exception mechanism is used, and the platform
5986 supports automatic registration of exception tables (e.g., Solaris),
5987 paths to more objects are required:
5989 @example
5990 $ cat ./my_script
5991 #!/bin/sh
5992 CC `gcc -print-file-name=crtbegin.o` $* \\
5993 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \\
5994 `gcc -print-file-name=crtend.o`
5995 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5996 @end example
5998 If the "zero cost exception" mechanism is used, and the platform
5999 doesn't support automatic registration of exception tables (e.g., HP-UX
6000 or AIX), the simple approach described above will not work and
6001 a pre-linking phase using GNAT will be necessary.
6002 @end itemize
6004 Another alternative is to use the @code{gprbuild} multi-language builder
6005 which has a large knowledge base and knows how to link Ada and C++ code
6006 together automatically in most cases.
6008 @node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
6009 @anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{bd}@anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{be}
6010 @subsubsection A Simple Example
6013 The following example, provided as part of the GNAT examples, shows how
6014 to achieve procedural interfacing between Ada and C++ in both
6015 directions. The C++ class A has two methods. The first method is exported
6016 to Ada by the means of an extern C wrapper function. The second method
6017 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
6018 a limited record with a layout comparable to the C++ class. The Ada
6019 subprogram, in turn, calls the C++ method. So, starting from the C++
6020 main program, the process passes back and forth between the two
6021 languages.
6023 Here are the compilation commands:
6025 @example
6026 $ gnatmake -c simple_cpp_interface
6027 $ g++ -c cpp_main.C
6028 $ g++ -c ex7.C
6029 $ gnatbind -n simple_cpp_interface
6030 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
6031 @end example
6033 Here are the corresponding sources:
6035 @example
6036 //cpp_main.C
6038 #include "ex7.h"
6040 extern "C" @{
6041   void adainit (void);
6042   void adafinal (void);
6043   void method1 (A *t);
6046 void method1 (A *t)
6048   t->method1 ();
6051 int main ()
6053   A obj;
6054   adainit ();
6055   obj.method2 (3030);
6056   adafinal ();
6058 @end example
6060 @example
6061 //ex7.h
6063 class Origin @{
6064  public:
6065   int o_value;
6067 class A : public Origin @{
6068  public:
6069   void method1 (void);
6070   void method2 (int v);
6071   A();
6072   int   a_value;
6074 @end example
6076 @example
6077 //ex7.C
6079 #include "ex7.h"
6080 #include <stdio.h>
6082 extern "C" @{ void ada_method2 (A *t, int v);@}
6084 void A::method1 (void)
6086   a_value = 2020;
6087   printf ("in A::method1, a_value = %d \\n",a_value);
6090 void A::method2 (int v)
6092    ada_method2 (this, v);
6093    printf ("in A::method2, a_value = %d \\n",a_value);
6096 A::A(void)
6098    a_value = 1010;
6099   printf ("in A::A, a_value = %d \\n",a_value);
6101 @end example
6103 @example
6104 -- simple_cpp_interface.ads
6105 with System;
6106 package Simple_Cpp_Interface is
6107    type A is limited
6108       record
6109          Vptr    : System.Address;
6110          O_Value : Integer;
6111          A_Value : Integer;
6112       end record;
6113    pragma Convention (C, A);
6115    procedure Method1 (This : in out A);
6116    pragma Import (C, Method1);
6118    procedure Ada_Method2 (This : in out A; V : Integer);
6119    pragma Export (C, Ada_Method2);
6121 end Simple_Cpp_Interface;
6122 @end example
6124 @example
6125 -- simple_cpp_interface.adb
6126 package body Simple_Cpp_Interface is
6128    procedure Ada_Method2 (This : in out A; V : Integer) is
6129    begin
6130       Method1 (This);
6131       This.A_Value := V;
6132    end Ada_Method2;
6134 end Simple_Cpp_Interface;
6135 @end example
6137 @node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
6138 @anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{bf}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{c0}
6139 @subsubsection Interfacing with C++ constructors
6142 In order to interface with C++ constructors GNAT provides the
6143 @cite{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
6144 for additional information).
6145 In this section we present some common uses of C++ constructors
6146 in mixed-languages programs in GNAT.
6148 Let us assume that we need to interface with the following
6149 C++ class:
6151 @example
6152 class Root @{
6153 public:
6154   int  a_value;
6155   int  b_value;
6156   virtual int Get_Value ();
6157   Root();              // Default constructor
6158   Root(int v);         // 1st non-default constructor
6159   Root(int v, int w);  // 2nd non-default constructor
6161 @end example
6163 For this purpose we can write the following package spec (further
6164 information on how to build this spec is available in
6165 @ref{c1,,Interfacing with C++ at the Class Level} and
6166 @ref{19,,Generating Ada Bindings for C and C++ headers}).
6168 @example
6169 with Interfaces.C; use Interfaces.C;
6170 package Pkg_Root is
6171   type Root is tagged limited record
6172      A_Value : int;
6173      B_Value : int;
6174   end record;
6175   pragma Import (CPP, Root);
6177   function Get_Value (Obj : Root) return int;
6178   pragma Import (CPP, Get_Value);
6180   function Constructor return Root;
6181   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
6183   function Constructor (v : Integer) return Root;
6184   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
6186   function Constructor (v, w : Integer) return Root;
6187   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
6188 end Pkg_Root;
6189 @end example
6191 On the Ada side the constructor is represented by a function (whose
6192 name is arbitrary) that returns the classwide type corresponding to
6193 the imported C++ class. Although the constructor is described as a
6194 function, it is typically a procedure with an extra implicit argument
6195 (the object being initialized) at the implementation level. GNAT
6196 issues the appropriate call, whatever it is, to get the object
6197 properly initialized.
6199 Constructors can only appear in the following contexts:
6202 @itemize *
6204 @item 
6205 On the right side of an initialization of an object of type @cite{T}.
6207 @item 
6208 On the right side of an initialization of a record component of type @cite{T}.
6210 @item 
6211 In an Ada 2005 limited aggregate.
6213 @item 
6214 In an Ada 2005 nested limited aggregate.
6216 @item 
6217 In an Ada 2005 limited aggregate that initializes an object built in
6218 place by an extended return statement.
6219 @end itemize
6221 In a declaration of an object whose type is a class imported from C++,
6222 either the default C++ constructor is implicitly called by GNAT, or
6223 else the required C++ constructor must be explicitly called in the
6224 expression that initializes the object. For example:
6226 @example
6227 Obj1 : Root;
6228 Obj2 : Root := Constructor;
6229 Obj3 : Root := Constructor (v => 10);
6230 Obj4 : Root := Constructor (30, 40);
6231 @end example
6233 The first two declarations are equivalent: in both cases the default C++
6234 constructor is invoked (in the former case the call to the constructor is
6235 implicit, and in the latter case the call is explicit in the object
6236 declaration). @cite{Obj3} is initialized by the C++ non-default constructor
6237 that takes an integer argument, and @cite{Obj4} is initialized by the
6238 non-default C++ constructor that takes two integers.
6240 Let us derive the imported C++ class in the Ada side. For example:
6242 @example
6243 type DT is new Root with record
6244    C_Value : Natural := 2009;
6245 end record;
6246 @end example
6248 In this case the components DT inherited from the C++ side must be
6249 initialized by a C++ constructor, and the additional Ada components
6250 of type DT are initialized by GNAT. The initialization of such an
6251 object is done either by default, or by means of a function returning
6252 an aggregate of type DT, or by means of an extension aggregate.
6254 @example
6255 Obj5 : DT;
6256 Obj6 : DT := Function_Returning_DT (50);
6257 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6258 @end example
6260 The declaration of @cite{Obj5} invokes the default constructors: the
6261 C++ default constructor of the parent type takes care of the initialization
6262 of the components inherited from Root, and GNAT takes care of the default
6263 initialization of the additional Ada components of type DT (that is,
6264 @cite{C_Value} is initialized to value 2009). The order of invocation of
6265 the constructors is consistent with the order of elaboration required by
6266 Ada and C++. That is, the constructor of the parent type is always called
6267 before the constructor of the derived type.
6269 Let us now consider a record that has components whose type is imported
6270 from C++. For example:
6272 @example
6273 type Rec1 is limited record
6274    Data1 : Root := Constructor (10);
6275    Value : Natural := 1000;
6276 end record;
6278 type Rec2 (D : Integer := 20) is limited record
6279    Rec   : Rec1;
6280    Data2 : Root := Constructor (D, 30);
6281 end record;
6282 @end example
6284 The initialization of an object of type @cite{Rec2} will call the
6285 non-default C++ constructors specified for the imported components.
6286 For example:
6288 @example
6289 Obj8 : Rec2 (40);
6290 @end example
6292 Using Ada 2005 we can use limited aggregates to initialize an object
6293 invoking C++ constructors that differ from those specified in the type
6294 declarations. For example:
6296 @example
6297 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6298                         others => <>),
6299                 others => <>);
6300 @end example
6302 The above declaration uses an Ada 2005 limited aggregate to
6303 initialize @cite{Obj9}, and the C++ constructor that has two integer
6304 arguments is invoked to initialize the @cite{Data1} component instead
6305 of the constructor specified in the declaration of type @cite{Rec1}. In
6306 Ada 2005 the box in the aggregate indicates that unspecified components
6307 are initialized using the expression (if any) available in the component
6308 declaration. That is, in this case discriminant @cite{D} is initialized
6309 to value @cite{20}, @cite{Value} is initialized to value 1000, and the
6310 non-default C++ constructor that handles two integers takes care of
6311 initializing component @cite{Data2} with values @cite{20@comma{}30}.
6313 In Ada 2005 we can use the extended return statement to build the Ada
6314 equivalent to C++ non-default constructors. For example:
6316 @example
6317 function Constructor (V : Integer) return Rec2 is
6318 begin
6319    return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
6320                                  others => <>),
6321                          others => <>) do
6322       --  Further actions required for construction of
6323       --  objects of type Rec2
6324       ...
6325    end record;
6326 end Constructor;
6327 @end example
6329 In this example the extended return statement construct is used to
6330 build in place the returned object whose components are initialized
6331 by means of a limited aggregate. Any further action associated with
6332 the constructor can be placed inside the construct.
6334 @node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6335 @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}
6336 @subsubsection Interfacing with C++ at the Class Level
6339 In this section we demonstrate the GNAT features for interfacing with
6340 C++ by means of an example making use of Ada 2005 abstract interface
6341 types. This example consists of a classification of animals; classes
6342 have been used to model our main classification of animals, and
6343 interfaces provide support for the management of secondary
6344 classifications. We first demonstrate a case in which the types and
6345 constructors are defined on the C++ side and imported from the Ada
6346 side, and latter the reverse case.
6348 The root of our derivation will be the @cite{Animal} class, with a
6349 single private attribute (the @cite{Age} of the animal), a constructor,
6350 and two public primitives to set and get the value of this attribute.
6352 @example
6353 class Animal @{
6354  public:
6355    virtual void Set_Age (int New_Age);
6356    virtual int Age ();
6357    Animal() @{Age_Count = 0;@};
6358  private:
6359    int Age_Count;
6361 @end example
6363 Abstract interface types are defined in C++ by means of classes with pure
6364 virtual functions and no data members. In our example we will use two
6365 interfaces that provide support for the common management of @cite{Carnivore}
6366 and @cite{Domestic} animals:
6368 @example
6369 class Carnivore @{
6370 public:
6371    virtual int Number_Of_Teeth () = 0;
6374 class Domestic @{
6375 public:
6376    virtual void Set_Owner (char* Name) = 0;
6378 @end example
6380 Using these declarations, we can now say that a @cite{Dog} is an animal that is
6381 both Carnivore and Domestic, that is:
6383 @example
6384 class Dog : Animal, Carnivore, Domestic @{
6385  public:
6386    virtual int  Number_Of_Teeth ();
6387    virtual void Set_Owner (char* Name);
6389    Dog(); // Constructor
6390  private:
6391    int  Tooth_Count;
6392    char *Owner;
6394 @end example
6396 In the following examples we will assume that the previous declarations are
6397 located in a file named @cite{animals.h}. The following package demonstrates
6398 how to import these C++ declarations from the Ada side:
6400 @example
6401 with Interfaces.C.Strings; use Interfaces.C.Strings;
6402 package Animals is
6403   type Carnivore is limited interface;
6404   pragma Convention (C_Plus_Plus, Carnivore);
6405   function Number_Of_Teeth (X : Carnivore)
6406      return Natural is abstract;
6408   type Domestic is limited interface;
6409   pragma Convention (C_Plus_Plus, Domestic);
6410   procedure Set_Owner
6411     (X    : in out Domestic;
6412      Name : Chars_Ptr) is abstract;
6414   type Animal is tagged limited record
6415     Age : Natural;
6416   end record;
6417   pragma Import (C_Plus_Plus, Animal);
6419   procedure Set_Age (X : in out Animal; Age : Integer);
6420   pragma Import (C_Plus_Plus, Set_Age);
6422   function Age (X : Animal) return Integer;
6423   pragma Import (C_Plus_Plus, Age);
6425   function New_Animal return Animal;
6426   pragma CPP_Constructor (New_Animal);
6427   pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6429   type Dog is new Animal and Carnivore and Domestic with record
6430     Tooth_Count : Natural;
6431     Owner       : String (1 .. 30);
6432   end record;
6433   pragma Import (C_Plus_Plus, Dog);
6435   function Number_Of_Teeth (A : Dog) return Natural;
6436   pragma Import (C_Plus_Plus, Number_Of_Teeth);
6438   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6439   pragma Import (C_Plus_Plus, Set_Owner);
6441   function New_Dog return Dog;
6442   pragma CPP_Constructor (New_Dog);
6443   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6444 end Animals;
6445 @end example
6447 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6448 interfacing with these C++ classes is easy. The only requirement is that all
6449 the primitives and components must be declared exactly in the same order in
6450 the two languages.
6452 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6453 means of a @cite{pragma Convention (C_Plus_Plus)}, the convention used to pass
6454 the arguments to the called primitives will be the same as for C++. For the
6455 imported classes we use @cite{pragma Import} with convention @cite{C_Plus_Plus}
6456 to indicate that they have been defined on the C++ side; this is required
6457 because the dispatch table associated with these tagged types will be built
6458 in the C++ side and therefore will not contain the predefined Ada primitives
6459 which Ada would otherwise expect.
6461 As the reader can see there is no need to indicate the C++ mangled names
6462 associated with each subprogram because it is assumed that all the calls to
6463 these primitives will be dispatching calls. The only exception is the
6464 constructor, which must be registered with the compiler by means of
6465 @cite{pragma CPP_Constructor} and needs to provide its associated C++
6466 mangled name because the Ada compiler generates direct calls to it.
6468 With the above packages we can now declare objects of type Dog on the Ada side
6469 and dispatch calls to the corresponding subprograms on the C++ side. We can
6470 also extend the tagged type Dog with further fields and primitives, and
6471 override some of its C++ primitives on the Ada side. For example, here we have
6472 a type derivation defined on the Ada side that inherits all the dispatching
6473 primitives of the ancestor from the C++ side.
6475 @example
6476 with Animals; use Animals;
6477 package Vaccinated_Animals is
6478   type Vaccinated_Dog is new Dog with null record;
6479   function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6480 end Vaccinated_Animals;
6481 @end example
6483 It is important to note that, because of the ABI compatibility, the programmer
6484 does not need to add any further information to indicate either the object
6485 layout or the dispatch table entry associated with each dispatching operation.
6487 Now let us define all the types and constructors on the Ada side and export
6488 them to C++, using the same hierarchy of our previous example:
6490 @example
6491 with Interfaces.C.Strings;
6492 use Interfaces.C.Strings;
6493 package Animals is
6494   type Carnivore is limited interface;
6495   pragma Convention (C_Plus_Plus, Carnivore);
6496   function Number_Of_Teeth (X : Carnivore)
6497      return Natural is abstract;
6499   type Domestic is limited interface;
6500   pragma Convention (C_Plus_Plus, Domestic);
6501   procedure Set_Owner
6502     (X    : in out Domestic;
6503      Name : Chars_Ptr) is abstract;
6505   type Animal is tagged record
6506     Age : Natural;
6507   end record;
6508   pragma Convention (C_Plus_Plus, Animal);
6510   procedure Set_Age (X : in out Animal; Age : Integer);
6511   pragma Export (C_Plus_Plus, Set_Age);
6513   function Age (X : Animal) return Integer;
6514   pragma Export (C_Plus_Plus, Age);
6516   function New_Animal return Animal'Class;
6517   pragma Export (C_Plus_Plus, New_Animal);
6519   type Dog is new Animal and Carnivore and Domestic with record
6520     Tooth_Count : Natural;
6521     Owner       : String (1 .. 30);
6522   end record;
6523   pragma Convention (C_Plus_Plus, Dog);
6525   function Number_Of_Teeth (A : Dog) return Natural;
6526   pragma Export (C_Plus_Plus, Number_Of_Teeth);
6528   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6529   pragma Export (C_Plus_Plus, Set_Owner);
6531   function New_Dog return Dog'Class;
6532   pragma Export (C_Plus_Plus, New_Dog);
6533 end Animals;
6534 @end example
6536 Compared with our previous example the only differences are the use of
6537 @cite{pragma Convention} (instead of @cite{pragma Import}), and the use of
6538 @cite{pragma Export} to indicate to the GNAT compiler that the primitives will
6539 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6540 nothing else to be done; as explained above, the only requirement is that all
6541 the primitives and components are declared in exactly the same order.
6543 For completeness, let us see a brief C++ main program that uses the
6544 declarations available in @cite{animals.h} (presented in our first example) to
6545 import and use the declarations from the Ada side, properly initializing and
6546 finalizing the Ada run-time system along the way:
6548 @example
6549 #include "animals.h"
6550 #include <iostream>
6551 using namespace std;
6553 void Check_Carnivore (Carnivore *obj) @{...@}
6554 void Check_Domestic (Domestic *obj)   @{...@}
6555 void Check_Animal (Animal *obj)       @{...@}
6556 void Check_Dog (Dog *obj)             @{...@}
6558 extern "C" @{
6559   void adainit (void);
6560   void adafinal (void);
6561   Dog* new_dog ();
6564 void test ()
6566   Dog *obj = new_dog();  // Ada constructor
6567   Check_Carnivore (obj); // Check secondary DT
6568   Check_Domestic (obj);  // Check secondary DT
6569   Check_Animal (obj);    // Check primary DT
6570   Check_Dog (obj);       // Check primary DT
6573 int main ()
6575   adainit ();  test();  adafinal ();
6576   return 0;
6578 @end example
6580 @node Generating Ada Bindings for C and C++ headers,Generating C Headers for Ada Specifications,Building Mixed Ada and C++ Programs,Mixed Language Programming
6581 @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}
6582 @subsection Generating Ada Bindings for C and C++ headers
6585 @geindex Binding generation (for C and C++ headers)
6587 @geindex C headers (binding generation)
6589 @geindex C++ headers (binding generation)
6591 GNAT includes a binding generator for C and C++ headers which is
6592 intended to do 95% of the tedious work of generating Ada specs from C
6593 or C++ header files.
6595 Note that this capability is not intended to generate 100% correct Ada specs,
6596 and will is some cases require manual adjustments, although it can often
6597 be used out of the box in practice.
6599 Some of the known limitations include:
6602 @itemize *
6604 @item 
6605 only very simple character constant macros are translated into Ada
6606 constants. Function macros (macros with arguments) are partially translated
6607 as comments, to be completed manually if needed.
6609 @item 
6610 some extensions (e.g. vector types) are not supported
6612 @item 
6613 pointers to pointers or complex structures are mapped to System.Address
6615 @item 
6616 identifiers with identical name (except casing) will generate compilation
6617 errors (e.g. @cite{shm_get} vs @cite{SHM_GET}).
6618 @end itemize
6620 The code generated is using the Ada 2005 syntax, which makes it
6621 easier to interface with other languages than previous versions of Ada.
6623 @menu
6624 * Running the Binding Generator:: 
6625 * Generating Bindings for C++ Headers:: 
6626 * Switches:: 
6628 @end menu
6630 @node Running the Binding Generator,Generating Bindings for C++ Headers,,Generating Ada Bindings for C and C++ headers
6631 @anchor{gnat_ugn/the_gnat_compilation_model id71}@anchor{c4}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{c5}
6632 @subsubsection Running the Binding Generator
6635 The binding generator is part of the @emph{gcc} compiler and can be
6636 invoked via the @emph{-fdump-ada-spec} switch, which will generate Ada
6637 spec files for the header files specified on the command line, and all
6638 header files needed by these files transitively. For example:
6640 @example
6641 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
6642 $ gcc -c -gnat05 *.ads
6643 @end example
6645 will generate, under GNU/Linux, the following files: @code{time_h.ads},
6646 @code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6647 correspond to the files @code{/usr/include/time.h},
6648 @code{/usr/include/bits/time.h}, etc..., and will then compile in Ada 2005
6649 mode these Ada specs.
6651 The @cite{-C} switch tells @emph{gcc} to extract comments from headers,
6652 and will attempt to generate corresponding Ada comments.
6654 If you want to generate a single Ada file and not the transitive closure, you
6655 can use instead the @emph{-fdump-ada-spec-slim} switch.
6657 You can optionally specify a parent unit, of which all generated units will
6658 be children, using @cite{-fada-spec-parent=<unit>}.
6660 Note that we recommend when possible to use the @emph{g++} driver to
6661 generate bindings, even for most C headers, since this will in general
6662 generate better Ada specs. For generating bindings for C++ headers, it is
6663 mandatory to use the @emph{g++} command, or @emph{gcc -x c++} which
6664 is equivalent in this case. If @emph{g++} cannot work on your C headers
6665 because of incompatibilities between C and C++, then you can fallback to
6666 @emph{gcc} instead.
6668 For an example of better bindings generated from the C++ front-end,
6669 the name of the parameters (when available) are actually ignored by the C
6670 front-end. Consider the following C header:
6672 @example
6673 extern void foo (int variable);
6674 @end example
6676 with the C front-end, @cite{variable} is ignored, and the above is handled as:
6678 @example
6679 extern void foo (int);
6680 @end example
6682 generating a generic:
6684 @example
6685 procedure foo (param1 : int);
6686 @end example
6688 with the C++ front-end, the name is available, and we generate:
6690 @example
6691 procedure foo (variable : int);
6692 @end example
6694 In some cases, the generated bindings will be more complete or more meaningful
6695 when defining some macros, which you can do via the @emph{-D} switch. This
6696 is for example the case with @code{Xlib.h} under GNU/Linux:
6698 @example
6699 $ g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6700 @end example
6702 The above will generate more complete bindings than a straight call without
6703 the @emph{-DXLIB_ILLEGAL_ACCESS} switch.
6705 In other cases, it is not possible to parse a header file in a stand-alone
6706 manner, because other include files need to be included first. In this
6707 case, the solution is to create a small header file including the needed
6708 @cite{#include} and possible @cite{#define} directives. For example, to
6709 generate Ada bindings for @code{readline/readline.h}, you need to first
6710 include @code{stdio.h}, so you can create a file with the following two
6711 lines in e.g. @code{readline1.h}:
6713 @example
6714 #include <stdio.h>
6715 #include <readline/readline.h>
6716 @end example
6718 and then generate Ada bindings from this file:
6720 @example
6721 $ g++ -c -fdump-ada-spec readline1.h
6722 @end example
6724 @node Generating Bindings for C++ Headers,Switches,Running the Binding Generator,Generating Ada Bindings for C and C++ headers
6725 @anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{c6}@anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{c7}
6726 @subsubsection Generating Bindings for C++ Headers
6729 Generating bindings for C++ headers is done using the same options, always
6730 with the @emph{g++} compiler. Note that generating Ada spec from C++ headers is a
6731 much more complex job and support for C++ headers is much more limited that
6732 support for C headers. As a result, you will need to modify the resulting
6733 bindings by hand more extensively when using C++ headers.
6735 In this mode, C++ classes will be mapped to Ada tagged types, constructors
6736 will be mapped using the @cite{CPP_Constructor} pragma, and when possible,
6737 multiple inheritance of abstract classes will be mapped to Ada interfaces
6738 (see the @emph{Interfacing to C++} section in the @cite{GNAT Reference Manual}
6739 for additional information on interfacing to C++).
6741 For example, given the following C++ header file:
6743 @example
6744 class Carnivore @{
6745 public:
6746    virtual int Number_Of_Teeth () = 0;
6749 class Domestic @{
6750 public:
6751    virtual void Set_Owner (char* Name) = 0;
6754 class Animal @{
6755 public:
6756   int Age_Count;
6757   virtual void Set_Age (int New_Age);
6760 class Dog : Animal, Carnivore, Domestic @{
6761  public:
6762   int  Tooth_Count;
6763   char *Owner;
6765   virtual int  Number_Of_Teeth ();
6766   virtual void Set_Owner (char* Name);
6768   Dog();
6770 @end example
6772 The corresponding Ada code is generated:
6774 @example
6775 package Class_Carnivore is
6776   type Carnivore is limited interface;
6777   pragma Import (CPP, Carnivore);
6779   function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6780 end;
6781 use Class_Carnivore;
6783 package Class_Domestic is
6784   type Domestic is limited interface;
6785   pragma Import (CPP, Domestic);
6787   procedure Set_Owner
6788     (this : access Domestic;
6789      Name : Interfaces.C.Strings.chars_ptr) is abstract;
6790 end;
6791 use Class_Domestic;
6793 package Class_Animal is
6794   type Animal is tagged limited record
6795     Age_Count : aliased int;
6796   end record;
6797   pragma Import (CPP, Animal);
6799   procedure Set_Age (this : access Animal; New_Age : int);
6800   pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6801 end;
6802 use Class_Animal;
6804 package Class_Dog is
6805   type Dog is new Animal and Carnivore and Domestic with record
6806     Tooth_Count : aliased int;
6807     Owner : Interfaces.C.Strings.chars_ptr;
6808   end record;
6809   pragma Import (CPP, Dog);
6811   function Number_Of_Teeth (this : access Dog) return int;
6812   pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6814   procedure Set_Owner
6815     (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6816   pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6818   function New_Dog return Dog;
6819   pragma CPP_Constructor (New_Dog);
6820   pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6821 end;
6822 use Class_Dog;
6823 @end example
6825 @node Switches,,Generating Bindings for C++ Headers,Generating Ada Bindings for C and C++ headers
6826 @anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{c8}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{c9}
6827 @subsubsection Switches
6830 @geindex -fdump-ada-spec (gcc)
6833 @table @asis
6835 @item @code{-fdump-ada-spec}
6837 Generate Ada spec files for the given header files transitively (including
6838 all header files that these headers depend upon).
6839 @end table
6841 @geindex -fdump-ada-spec-slim (gcc)
6844 @table @asis
6846 @item @code{-fdump-ada-spec-slim}
6848 Generate Ada spec files for the header files specified on the command line
6849 only.
6850 @end table
6852 @geindex -fada-spec-parent (gcc)
6855 @table @asis
6857 @item @code{-fada-spec-parent=@emph{unit}}
6859 Specifies that all files generated by @emph{-fdump-ada-spec*} are
6860 to be child units of the specified parent unit.
6861 @end table
6863 @geindex -C (gcc)
6866 @table @asis
6868 @item @code{-C}
6870 Extract comments from headers and generate Ada comments in the Ada spec files.
6871 @end table
6873 @node Generating C Headers for Ada Specifications,,Generating Ada Bindings for C and C++ headers,Mixed Language Programming
6874 @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}
6875 @subsection Generating C Headers for Ada Specifications
6878 @geindex Binding generation (for Ada specs)
6880 @geindex C headers (binding generation)
6882 GNAT includes a C header generator for Ada specifications which supports
6883 Ada types that have a direct mapping to C types. This includes in particular
6884 support for:
6887 @itemize *
6889 @item 
6890 Scalar types
6892 @item 
6893 Constrained arrays
6895 @item 
6896 Records (untagged)
6898 @item 
6899 Composition of the above types
6901 @item 
6902 Constant declarations
6904 @item 
6905 Object declarations
6907 @item 
6908 Subprogram declarations
6909 @end itemize
6911 @menu
6912 * Running the C Header Generator:: 
6914 @end menu
6916 @node Running the C Header Generator,,,Generating C Headers for Ada Specifications
6917 @anchor{gnat_ugn/the_gnat_compilation_model running-the-c-header-generator}@anchor{cc}
6918 @subsubsection Running the C Header Generator
6921 The C header generator is part of the GNAT compiler and can be invoked via
6922 the @emph{-gnatceg} combination of switches, which will generate a @code{.h}
6923 file corresponding to the given input file (Ada spec or body). Note that
6924 only spec files are processed in any case, so giving a spec or a body file
6925 as input is equivalent. For example:
6927 @example
6928 $ gcc -c -gnatceg pack1.ads
6929 @end example
6931 will generate a self-contained file called @code{pack1.h} including
6932 common definitions from the Ada Standard package, followed by the
6933 definitions included in @code{pack1.ads}, as well as all the other units
6934 withed by this file.
6936 For instance, given the following Ada files:
6938 @example
6939 package Pack2 is
6940    type Int is range 1 .. 10;
6941 end Pack2;
6942 @end example
6944 @example
6945 with Pack2;
6947 package Pack1 is
6948    type Rec is record
6949       Field1, Field2 : Pack2.Int;
6950    end record;
6952    Global : Rec := (1, 2);
6954    procedure Proc1 (R : Rec);
6955    procedure Proc2 (R : in out Rec);
6956 end Pack1;
6957 @end example
6959 The above @cite{gcc} command will generate the following @code{pack1.h} file:
6961 @example
6962 /* Standard definitions skipped */
6963 #ifndef PACK2_ADS
6964 #define PACK2_ADS
6965 typedef short_short_integer pack2__TintB;
6966 typedef pack2__TintB pack2__int;
6967 #endif /* PACK2_ADS */
6969 #ifndef PACK1_ADS
6970 #define PACK1_ADS
6971 typedef struct _pack1__rec @{
6972   pack2__int field1;
6973   pack2__int field2;
6974 @} pack1__rec;
6975 extern pack1__rec pack1__global;
6976 extern void pack1__proc1(const pack1__rec r);
6977 extern void pack1__proc2(pack1__rec *r);
6978 #endif /* PACK1_ADS */
6979 @end example
6981 You can then @cite{include} @code{pack1.h} from a C source file and use the types,
6982 call subprograms, reference objects, and constants.
6984 @node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
6985 @anchor{gnat_ugn/the_gnat_compilation_model id74}@anchor{cd}@anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{45}
6986 @section GNAT and Other Compilation Models
6989 This section compares the GNAT model with the approaches taken in
6990 other environents, first the C/C++ model and then the mechanism that
6991 has been used in other Ada systems, in particular those traditionally
6992 used for Ada 83.
6994 @menu
6995 * Comparison between GNAT and C/C++ Compilation Models:: 
6996 * Comparison between GNAT and Conventional Ada Library Models:: 
6998 @end menu
7000 @node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
7001 @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}
7002 @subsection Comparison between GNAT and C/C++ Compilation Models
7005 The GNAT model of compilation is close to the C and C++ models. You can
7006 think of Ada specs as corresponding to header files in C. As in C, you
7007 don't need to compile specs; they are compiled when they are used. The
7008 Ada @emph{with} is similar in effect to the @cite{#include} of a C
7009 header.
7011 One notable difference is that, in Ada, you may compile specs separately
7012 to check them for semantic and syntactic accuracy. This is not always
7013 possible with C headers because they are fragments of programs that have
7014 less specific syntactic or semantic rules.
7016 The other major difference is the requirement for running the binder,
7017 which performs two important functions. First, it checks for
7018 consistency. In C or C++, the only defense against assembling
7019 inconsistent programs lies outside the compiler, in a makefile, for
7020 example. The binder satisfies the Ada requirement that it be impossible
7021 to construct an inconsistent program when the compiler is used in normal
7022 mode.
7024 @geindex Elaboration order control
7026 The other important function of the binder is to deal with elaboration
7027 issues. There are also elaboration issues in C++ that are handled
7028 automatically. This automatic handling has the advantage of being
7029 simpler to use, but the C++ programmer has no control over elaboration.
7030 Where @cite{gnatbind} might complain there was no valid order of
7031 elaboration, a C++ compiler would simply construct a program that
7032 malfunctioned at run time.
7034 @node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
7035 @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}
7036 @subsection Comparison between GNAT and Conventional Ada Library Models
7039 This section is intended for Ada programmers who have
7040 used an Ada compiler implementing the traditional Ada library
7041 model, as described in the Ada Reference Manual.
7043 @geindex GNAT library
7045 In GNAT, there is no 'library' in the normal sense. Instead, the set of
7046 source files themselves acts as the library. Compiling Ada programs does
7047 not generate any centralized information, but rather an object file and
7048 a ALI file, which are of interest only to the binder and linker.
7049 In a traditional system, the compiler reads information not only from
7050 the source file being compiled, but also from the centralized library.
7051 This means that the effect of a compilation depends on what has been
7052 previously compiled. In particular:
7055 @itemize *
7057 @item 
7058 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7059 to the version of the unit most recently compiled into the library.
7061 @item 
7062 Inlining is effective only if the necessary body has already been
7063 compiled into the library.
7065 @item 
7066 Compiling a unit may obsolete other units in the library.
7067 @end itemize
7069 In GNAT, compiling one unit never affects the compilation of any other
7070 units because the compiler reads only source files. Only changes to source
7071 files can affect the results of a compilation. In particular:
7074 @itemize *
7076 @item 
7077 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7078 to the source version of the unit that is currently accessible to the
7079 compiler.
7081 @geindex Inlining
7083 @item 
7084 Inlining requires the appropriate source files for the package or
7085 subprogram bodies to be available to the compiler. Inlining is always
7086 effective, independent of the order in which units are compiled.
7088 @item 
7089 Compiling a unit never affects any other compilations. The editing of
7090 sources may cause previous compilations to be out of date if they
7091 depended on the source file being modified.
7092 @end itemize
7094 The most important result of these differences is that order of compilation
7095 is never significant in GNAT. There is no situation in which one is
7096 required to do one compilation before another. What shows up as order of
7097 compilation requirements in the traditional Ada library becomes, in
7098 GNAT, simple source dependencies; in other words, there is only a set
7099 of rules saying what source files must be present when a file is
7100 compiled.
7102 @node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
7103 @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}
7104 @section Using GNAT Files with External Tools
7107 This section explains how files that are produced by GNAT may be
7108 used with tools designed for other languages.
7110 @menu
7111 * Using Other Utility Programs with GNAT:: 
7112 * The External Symbol Naming Scheme of GNAT:: 
7114 @end menu
7116 @node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
7117 @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}
7118 @subsection Using Other Utility Programs with GNAT
7121 The object files generated by GNAT are in standard system format and in
7122 particular the debugging information uses this format. This means
7123 programs generated by GNAT can be used with existing utilities that
7124 depend on these formats.
7126 In general, any utility program that works with C will also often work with
7127 Ada programs generated by GNAT. This includes software utilities such as
7128 gprof (a profiling program), gdb (the FSF debugger), and utilities such
7129 as Purify.
7131 @node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
7132 @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}
7133 @subsection The External Symbol Naming Scheme of GNAT
7136 In order to interpret the output from GNAT, when using tools that are
7137 originally intended for use with other languages, it is useful to
7138 understand the conventions used to generate link names from the Ada
7139 entity names.
7141 All link names are in all lowercase letters. With the exception of library
7142 procedure names, the mechanism used is simply to use the full expanded
7143 Ada name with dots replaced by double underscores. For example, suppose
7144 we have the following package spec:
7146 @example
7147 package QRS is
7148    MN : Integer;
7149 end QRS;
7150 @end example
7152 @geindex pragma Export
7154 The variable @cite{MN} has a full expanded Ada name of @cite{QRS.MN}, so
7155 the corresponding link name is @cite{qrs__mn}.
7156 Of course if a @cite{pragma Export} is used this may be overridden:
7158 @example
7159 package Exports is
7160    Var1 : Integer;
7161    pragma Export (Var1, C, External_Name => "var1_name");
7162    Var2 : Integer;
7163    pragma Export (Var2, C, Link_Name => "var2_link_name");
7164 end Exports;
7165 @end example
7167 In this case, the link name for @cite{Var1} is whatever link name the
7168 C compiler would assign for the C function @cite{var1_name}. This typically
7169 would be either @cite{var1_name} or @cite{_var1_name}, depending on operating
7170 system conventions, but other possibilities exist. The link name for
7171 @cite{Var2} is @cite{var2_link_name}, and this is not operating system
7172 dependent.
7174 One exception occurs for library level procedures. A potential ambiguity
7175 arises between the required name @cite{_main} for the C main program,
7176 and the name we would otherwise assign to an Ada library level procedure
7177 called @cite{Main} (which might well not be the main program).
7179 To avoid this ambiguity, we attach the prefix @cite{_ada_} to such
7180 names. So if we have a library level procedure such as:
7182 @example
7183 procedure Hello (S : String);
7184 @end example
7186 the external name of this procedure will be @cite{_ada_hello}.
7188 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7190 @node Building Executable Programs with GNAT,GNAT Utility Programs,The GNAT Compilation Model,Top
7191 @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}
7192 @chapter Building Executable Programs with GNAT
7195 This chapter describes first the gnatmake tool
7196 (@ref{1b,,Building with gnatmake}),
7197 which automatically determines the set of sources
7198 needed by an Ada compilation unit and executes the necessary
7199 (re)compilations, binding and linking.
7200 It also explains how to use each tool individually: the
7201 compiler (gcc, see @ref{1c,,Compiling with gcc}),
7202 binder (gnatbind, see @ref{1d,,Binding with gnatbind}),
7203 and linker (gnatlink, see @ref{1e,,Linking with gnatlink})
7204 to build executable programs.
7205 Finally, this chapter provides examples of
7206 how to make use of the general GNU make mechanism
7207 in a GNAT context (see @ref{1f,,Using the GNU make Utility}).
7210 @menu
7211 * Building with gnatmake:: 
7212 * Compiling with gcc:: 
7213 * Compiler Switches:: 
7214 * Linker Switches:: 
7215 * Binding with gnatbind:: 
7216 * Linking with gnatlink:: 
7217 * Using the GNU make Utility:: 
7219 @end menu
7221 @node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
7222 @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}
7223 @section Building with @emph{gnatmake}
7226 @geindex gnatmake
7228 A typical development cycle when working on an Ada program consists of
7229 the following steps:
7232 @enumerate 
7234 @item 
7235 Edit some sources to fix bugs;
7237 @item 
7238 Add enhancements;
7240 @item 
7241 Compile all sources affected;
7243 @item 
7244 Rebind and relink; and
7246 @item 
7247 Test.
7248 @end enumerate
7250 @geindex Dependency rules (compilation)
7252 The third step in particular can be tricky, because not only do the modified
7253 files have to be compiled, but any files depending on these files must also be
7254 recompiled. The dependency rules in Ada can be quite complex, especially
7255 in the presence of overloading, @cite{use} clauses, generics and inlined
7256 subprograms.
7258 @emph{gnatmake} automatically takes care of the third and fourth steps
7259 of this process. It determines which sources need to be compiled,
7260 compiles them, and binds and links the resulting object files.
7262 Unlike some other Ada make programs, the dependencies are always
7263 accurately recomputed from the new sources. The source based approach of
7264 the GNAT compilation model makes this possible. This means that if
7265 changes to the source program cause corresponding changes in
7266 dependencies, they will always be tracked exactly correctly by
7267 @emph{gnatmake}.
7269 Note that for advanced forms of project structure, we recommend creating
7270 a project file as explained in the @emph{GNAT_Project_Manager} chapter in the
7271 @emph{GPRbuild User's Guide}, and using the
7272 @emph{gprbuild} tool which supports building with project files and works similarly
7273 to @emph{gnatmake}.
7275 @menu
7276 * Running gnatmake:: 
7277 * Switches for gnatmake:: 
7278 * Mode Switches for gnatmake:: 
7279 * Notes on the Command Line:: 
7280 * How gnatmake Works:: 
7281 * Examples of gnatmake Usage:: 
7283 @end menu
7285 @node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7286 @anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{da}@anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{db}
7287 @subsection Running @emph{gnatmake}
7290 The usual form of the @emph{gnatmake} command is
7292 @example
7293 $ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7294 @end example
7296 The only required argument is one @cite{file_name}, which specifies
7297 a compilation unit that is a main program. Several @cite{file_names} can be
7298 specified: this will result in several executables being built.
7299 If @cite{switches} are present, they can be placed before the first
7300 @cite{file_name}, between @cite{file_names} or after the last @cite{file_name}.
7301 If @cite{mode_switches} are present, they must always be placed after
7302 the last @cite{file_name} and all @cite{switches}.
7304 If you are using standard file extensions (@code{.adb} and
7305 @code{.ads}), then the
7306 extension may be omitted from the @cite{file_name} arguments. However, if
7307 you are using non-standard extensions, then it is required that the
7308 extension be given. A relative or absolute directory path can be
7309 specified in a @cite{file_name}, in which case, the input source file will
7310 be searched for in the specified directory only. Otherwise, the input
7311 source file will first be searched in the directory where
7312 @emph{gnatmake} was invoked and if it is not found, it will be search on
7313 the source path of the compiler as described in
7314 @ref{89,,Search Paths and the Run-Time Library (RTL)}.
7316 All @emph{gnatmake} output (except when you specify @emph{-M}) is sent to
7317 @code{stderr}. The output produced by the
7318 @emph{-M} switch is sent to @code{stdout}.
7320 @node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7321 @anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{dc}@anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{dd}
7322 @subsection Switches for @emph{gnatmake}
7325 You may specify any of the following switches to @emph{gnatmake}:
7327 @geindex --version (gnatmake)
7330 @table @asis
7332 @item @code{--version}
7334 Display Copyright and version, then exit disregarding all other options.
7335 @end table
7337 @geindex --help (gnatmake)
7340 @table @asis
7342 @item @code{--help}
7344 If @code{--version} was not used, display usage, then exit disregarding
7345 all other options.
7346 @end table
7348 @geindex --GCC=compiler_name (gnatmake)
7351 @table @asis
7353 @item @code{--GCC=@emph{compiler_name}}
7355 Program used for compiling. The default is @code{gcc}. You need to use
7356 quotes around @cite{compiler_name} if @cite{compiler_name} contains
7357 spaces or other separator characters.
7358 As an example @code{--GCC="foo -x  -y"}
7359 will instruct @emph{gnatmake} to use @code{foo -x -y} as your
7360 compiler. A limitation of this syntax is that the name and path name of
7361 the executable itself must not include any embedded spaces. Note that
7362 switch @code{-c} is always inserted after your command name. Thus in the
7363 above example the compiler command that will be used by @emph{gnatmake}
7364 will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7365 used, only the last @cite{compiler_name} is taken into account. However,
7366 all the additional switches are also taken into account. Thus,
7367 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7368 @code{--GCC="bar -x -y -z -t"}.
7369 @end table
7371 @geindex --GNATBIND=binder_name (gnatmake)
7374 @table @asis
7376 @item @code{--GNATBIND=@emph{binder_name}}
7378 Program used for binding. The default is @code{gnatbind}. You need to
7379 use quotes around @cite{binder_name} if @cite{binder_name} contains spaces
7380 or other separator characters.
7381 As an example @code{--GNATBIND="bar -x  -y"}
7382 will instruct @emph{gnatmake} to use @cite{bar -x -y} as your
7383 binder. Binder switches that are normally appended by @emph{gnatmake}
7384 to @code{gnatbind} are now appended to the end of @cite{bar -x -y}.
7385 A limitation of this syntax is that the name and path name of the executable
7386 itself must not include any embedded spaces.
7387 @end table
7389 @geindex --GNATLINK=linker_name (gnatmake)
7392 @table @asis
7394 @item @code{--GNATLINK=@emph{linker_name}}
7396 Program used for linking. The default is @code{gnatlink}. You need to
7397 use quotes around @cite{linker_name} if @cite{linker_name} contains spaces
7398 or other separator characters.
7399 As an example @code{--GNATLINK="lan -x  -y"}
7400 will instruct @emph{gnatmake} to use @code{lan -x -y} as your
7401 linker. Linker switches that are normally appended by @code{gnatmake} to
7402 @code{gnatlink} are now appended to the end of @code{lan -x -y}.
7403 A limitation of this syntax is that the name and path name of the executable
7404 itself must not include any embedded spaces.
7406 @item @code{--create-map-file}
7408 When linking an executable, create a map file. The name of the map file
7409 has the same name as the executable with extension ".map".
7411 @item @code{--create-map-file=@emph{mapfile}}
7413 When linking an executable, create a map file with the specified name.
7414 @end table
7416 @geindex --create-missing-dirs (gnatmake)
7419 @table @asis
7421 @item @code{--create-missing-dirs}
7423 When using project files (@code{-P@emph{project}}), automatically create
7424 missing object directories, library directories and exec
7425 directories.
7427 @item @code{--single-compile-per-obj-dir}
7429 Disallow simultaneous compilations in the same object directory when
7430 project files are used.
7432 @item @code{--subdirs=@emph{subdir}}
7434 Actual object directory of each project file is the subdirectory subdir of the
7435 object directory specified or defaulted in the project file.
7437 @item @code{--unchecked-shared-lib-imports}
7439 By default, shared library projects are not allowed to import static library
7440 projects. When this switch is used on the command line, this restriction is
7441 relaxed.
7443 @item @code{--source-info=@emph{source info file}}
7445 Specify a source info file. This switch is active only when project files
7446 are used. If the source info file is specified as a relative path, then it is
7447 relative to the object directory of the main project. If the source info file
7448 does not exist, then after the Project Manager has successfully parsed and
7449 processed the project files and found the sources, it creates the source info
7450 file. If the source info file already exists and can be read successfully,
7451 then the Project Manager will get all the needed information about the sources
7452 from the source info file and will not look for them. This reduces the time
7453 to process the project files, especially when looking for sources that take a
7454 long time. If the source info file exists but cannot be parsed successfully,
7455 the Project Manager will attempt to recreate it. If the Project Manager fails
7456 to create the source info file, a message is issued, but gnatmake does not
7457 fail. @emph{gnatmake} "trusts" the source info file. This means that
7458 if the source files have changed (addition, deletion, moving to a different
7459 source directory), then the source info file need to be deleted and recreated.
7460 @end table
7462 @geindex -a (gnatmake)
7465 @table @asis
7467 @item @code{-a}
7469 Consider all files in the make process, even the GNAT internal system
7470 files (for example, the predefined Ada library files), as well as any
7471 locked files. Locked files are files whose ALI file is write-protected.
7472 By default,
7473 @emph{gnatmake} does not check these files,
7474 because the assumption is that the GNAT internal files are properly up
7475 to date, and also that any write protected ALI files have been properly
7476 installed. Note that if there is an installation problem, such that one
7477 of these files is not up to date, it will be properly caught by the
7478 binder.
7479 You may have to specify this switch if you are working on GNAT
7480 itself. The switch @code{-a} is also useful
7481 in conjunction with @code{-f}
7482 if you need to recompile an entire application,
7483 including run-time files, using special configuration pragmas,
7484 such as a @cite{Normalize_Scalars} pragma.
7486 By default
7487 @code{gnatmake -a} compiles all GNAT
7488 internal files with
7489 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7490 @end table
7492 @geindex -b (gnatmake)
7495 @table @asis
7497 @item @code{-b}
7499 Bind only. Can be combined with @emph{-c} to do
7500 compilation and binding, but no link.
7501 Can be combined with @emph{-l}
7502 to do binding and linking. When not combined with
7503 @emph{-c}
7504 all the units in the closure of the main program must have been previously
7505 compiled and must be up to date. The root unit specified by @cite{file_name}
7506 may be given without extension, with the source extension or, if no GNAT
7507 Project File is specified, with the ALI file extension.
7508 @end table
7510 @geindex -c (gnatmake)
7513 @table @asis
7515 @item @code{-c}
7517 Compile only. Do not perform binding, except when @emph{-b}
7518 is also specified. Do not perform linking, except if both
7519 @emph{-b} and
7520 @emph{-l} are also specified.
7521 If the root unit specified by @cite{file_name} is not a main unit, this is the
7522 default. Otherwise @emph{gnatmake} will attempt binding and linking
7523 unless all objects are up to date and the executable is more recent than
7524 the objects.
7525 @end table
7527 @geindex -C (gnatmake)
7530 @table @asis
7532 @item @code{-C}
7534 Use a temporary mapping file. A mapping file is a way to communicate
7535 to the compiler two mappings: from unit names to file names (without
7536 any directory information) and from file names to path names (with
7537 full directory information). A mapping file can make the compiler's
7538 file searches faster, especially if there are many source directories,
7539 or the sources are read over a slow network connection. If
7540 @emph{-P} is used, a mapping file is always used, so
7541 @emph{-C} is unnecessary; in this case the mapping file
7542 is initially populated based on the project file. If
7543 @emph{-C} is used without
7544 @emph{-P},
7545 the mapping file is initially empty. Each invocation of the compiler
7546 will add any newly accessed sources to the mapping file.
7547 @end table
7549 @geindex -C= (gnatmake)
7552 @table @asis
7554 @item @code{-C=@emph{file}}
7556 Use a specific mapping file. The file, specified as a path name (absolute or
7557 relative) by this switch, should already exist, otherwise the switch is
7558 ineffective. The specified mapping file will be communicated to the compiler.
7559 This switch is not compatible with a project file
7560 (-P`file`) or with multiple compiling processes
7561 (-jnnn, when nnn is greater than 1).
7562 @end table
7564 @geindex -d (gnatmake)
7567 @table @asis
7569 @item @code{-d}
7571 Display progress for each source, up to date or not, as a single line:
7573 @example
7574 completed x out of y (zz%)
7575 @end example
7577 If the file needs to be compiled this is displayed after the invocation of
7578 the compiler. These lines are displayed even in quiet output mode.
7579 @end table
7581 @geindex -D (gnatmake)
7584 @table @asis
7586 @item @code{-D @emph{dir}}
7588 Put all object files and ALI file in directory @cite{dir}.
7589 If the @emph{-D} switch is not used, all object files
7590 and ALI files go in the current working directory.
7592 This switch cannot be used when using a project file.
7593 @end table
7595 @geindex -eI (gnatmake)
7598 @table @asis
7600 @item @code{-eI@emph{nnn}}
7602 Indicates that the main source is a multi-unit source and the rank of the unit
7603 in the source file is nnn. nnn needs to be a positive number and a valid
7604 index in the source. This switch cannot be used when @emph{gnatmake} is
7605 invoked for several mains.
7606 @end table
7608 @geindex -eL (gnatmake)
7610 @geindex symbolic links
7613 @table @asis
7615 @item @code{-eL}
7617 Follow all symbolic links when processing project files.
7618 This should be used if your project uses symbolic links for files or
7619 directories, but is not needed in other cases.
7621 @geindex naming scheme
7623 This also assumes that no directory matches the naming scheme for files (for
7624 instance that you do not have a directory called "sources.ads" when using the
7625 default GNAT naming scheme).
7627 When you do not have to use this switch (i.e., by default), gnatmake is able to
7628 save a lot of system calls (several per source file and object file), which
7629 can result in a significant speed up to load and manipulate a project file,
7630 especially when using source files from a remote system.
7631 @end table
7633 @geindex -eS (gnatmake)
7636 @table @asis
7638 @item @code{-eS}
7640 Output the commands for the compiler, the binder and the linker
7641 on standard output,
7642 instead of standard error.
7643 @end table
7645 @geindex -f (gnatmake)
7648 @table @asis
7650 @item @code{-f}
7652 Force recompilations. Recompile all sources, even though some object
7653 files may be up to date, but don't recompile predefined or GNAT internal
7654 files or locked files (files with a write-protected ALI file),
7655 unless the @emph{-a} switch is also specified.
7656 @end table
7658 @geindex -F (gnatmake)
7661 @table @asis
7663 @item @code{-F}
7665 When using project files, if some errors or warnings are detected during
7666 parsing and verbose mode is not in effect (no use of switch
7667 -v), then error lines start with the full path name of the project
7668 file, rather than its simple file name.
7669 @end table
7671 @geindex -g (gnatmake)
7674 @table @asis
7676 @item @code{-g}
7678 Enable debugging. This switch is simply passed to the compiler and to the
7679 linker.
7680 @end table
7682 @geindex -i (gnatmake)
7685 @table @asis
7687 @item @code{-i}
7689 In normal mode, @emph{gnatmake} compiles all object files and ALI files
7690 into the current directory. If the @emph{-i} switch is used,
7691 then instead object files and ALI files that already exist are overwritten
7692 in place. This means that once a large project is organized into separate
7693 directories in the desired manner, then @emph{gnatmake} will automatically
7694 maintain and update this organization. If no ALI files are found on the
7695 Ada object path (see @ref{89,,Search Paths and the Run-Time Library (RTL)}),
7696 the new object and ALI files are created in the
7697 directory containing the source being compiled. If another organization
7698 is desired, where objects and sources are kept in different directories,
7699 a useful technique is to create dummy ALI files in the desired directories.
7700 When detecting such a dummy file, @emph{gnatmake} will be forced to
7701 recompile the corresponding source file, and it will be put the resulting
7702 object and ALI files in the directory where it found the dummy file.
7703 @end table
7705 @geindex -j (gnatmake)
7707 @geindex Parallel make
7710 @table @asis
7712 @item @code{-j@emph{n}}
7714 Use @cite{n} processes to carry out the (re)compilations. On a multiprocessor
7715 machine compilations will occur in parallel. If @cite{n} is 0, then the
7716 maximum number of parallel compilations is the number of core processors
7717 on the platform. In the event of compilation errors, messages from various
7718 compilations might get interspersed (but @emph{gnatmake} will give you the
7719 full ordered list of failing compiles at the end). If this is problematic,
7720 rerun the make process with n set to 1 to get a clean list of messages.
7721 @end table
7723 @geindex -k (gnatmake)
7726 @table @asis
7728 @item @code{-k}
7730 Keep going. Continue as much as possible after a compilation error. To
7731 ease the programmer's task in case of compilation errors, the list of
7732 sources for which the compile fails is given when @emph{gnatmake}
7733 terminates.
7735 If @emph{gnatmake} is invoked with several @code{file_names} and with this
7736 switch, if there are compilation errors when building an executable,
7737 @emph{gnatmake} will not attempt to build the following executables.
7738 @end table
7740 @geindex -l (gnatmake)
7743 @table @asis
7745 @item @code{-l}
7747 Link only. Can be combined with @emph{-b} to binding
7748 and linking. Linking will not be performed if combined with
7749 @emph{-c}
7750 but not with @emph{-b}.
7751 When not combined with @emph{-b}
7752 all the units in the closure of the main program must have been previously
7753 compiled and must be up to date, and the main program needs to have been bound.
7754 The root unit specified by @cite{file_name}
7755 may be given without extension, with the source extension or, if no GNAT
7756 Project File is specified, with the ALI file extension.
7757 @end table
7759 @geindex -m (gnatmake)
7762 @table @asis
7764 @item @code{-m}
7766 Specify that the minimum necessary amount of recompilations
7767 be performed. In this mode @emph{gnatmake} ignores time
7768 stamp differences when the only
7769 modifications to a source file consist in adding/removing comments,
7770 empty lines, spaces or tabs. This means that if you have changed the
7771 comments in a source file or have simply reformatted it, using this
7772 switch will tell @emph{gnatmake} not to recompile files that depend on it
7773 (provided other sources on which these files depend have undergone no
7774 semantic modifications). Note that the debugging information may be
7775 out of date with respect to the sources if the @emph{-m} switch causes
7776 a compilation to be switched, so the use of this switch represents a
7777 trade-off between compilation time and accurate debugging information.
7778 @end table
7780 @geindex Dependencies
7781 @geindex producing list
7783 @geindex -M (gnatmake)
7786 @table @asis
7788 @item @code{-M}
7790 Check if all objects are up to date. If they are, output the object
7791 dependences to @code{stdout} in a form that can be directly exploited in
7792 a @code{Makefile}. By default, each source file is prefixed with its
7793 (relative or absolute) directory name. This name is whatever you
7794 specified in the various @emph{-aI}
7795 and @emph{-I} switches. If you use
7796 @cite{gnatmake -M}  @emph{-q}
7797 (see below), only the source file names,
7798 without relative paths, are output. If you just specify the  @emph{-M}
7799 switch, dependencies of the GNAT internal system files are omitted. This
7800 is typically what you want. If you also specify
7801 the @emph{-a} switch,
7802 dependencies of the GNAT internal files are also listed. Note that
7803 dependencies of the objects in external Ada libraries (see
7804 switch  @code{-aL@emph{dir}} in the following list)
7805 are never reported.
7806 @end table
7808 @geindex -n (gnatmake)
7811 @table @asis
7813 @item @code{-n}
7815 Don't compile, bind, or link. Checks if all objects are up to date.
7816 If they are not, the full name of the first file that needs to be
7817 recompiled is printed.
7818 Repeated use of this option, followed by compiling the indicated source
7819 file, will eventually result in recompiling all required units.
7820 @end table
7822 @geindex -o (gnatmake)
7825 @table @asis
7827 @item @code{-o @emph{exec_name}}
7829 Output executable name. The name of the final executable program will be
7830 @cite{exec_name}. If the @emph{-o} switch is omitted the default
7831 name for the executable will be the name of the input file in appropriate form
7832 for an executable file on the host system.
7834 This switch cannot be used when invoking @emph{gnatmake} with several
7835 @code{file_names}.
7836 @end table
7838 @geindex -p (gnatmake)
7841 @table @asis
7843 @item @code{-p}
7845 Same as @code{--create-missing-dirs}
7846 @end table
7848 @geindex -P (gnatmake)
7851 @table @asis
7853 @item @code{-P@emph{project}}
7855 Use project file @cite{project}. Only one such switch can be used.
7856 @end table
7858 @c -- Comment:
7859 @c :ref:`gnatmake_and_Project_Files`.
7861 @geindex -q (gnatmake)
7864 @table @asis
7866 @item @code{-q}
7868 Quiet. When this flag is not set, the commands carried out by
7869 @emph{gnatmake} are displayed.
7870 @end table
7872 @geindex -s (gnatmake)
7875 @table @asis
7877 @item @code{-s}
7879 Recompile if compiler switches have changed since last compilation.
7880 All compiler switches but -I and -o are taken into account in the
7881 following way:
7882 orders between different 'first letter' switches are ignored, but
7883 orders between same switches are taken into account. For example,
7884 @emph{-O -O2} is different than @emph{-O2 -O}, but @emph{-g -O}
7885 is equivalent to @emph{-O -g}.
7887 This switch is recommended when Integrated Preprocessing is used.
7888 @end table
7890 @geindex -u (gnatmake)
7893 @table @asis
7895 @item @code{-u}
7897 Unique. Recompile at most the main files. It implies -c. Combined with
7898 -f, it is equivalent to calling the compiler directly. Note that using
7899 -u with a project file and no main has a special meaning.
7900 @end table
7902 @c --Comment:
7903 @c (See :ref:`Project_Files_and_Main_Subprograms`.)
7905 @geindex -U (gnatmake)
7908 @table @asis
7910 @item @code{-U}
7912 When used without a project file or with one or several mains on the command
7913 line, is equivalent to -u. When used with a project file and no main
7914 on the command line, all sources of all project files are checked and compiled
7915 if not up to date, and libraries are rebuilt, if necessary.
7916 @end table
7918 @geindex -v (gnatmake)
7921 @table @asis
7923 @item @code{-v}
7925 Verbose. Display the reason for all recompilations @emph{gnatmake}
7926 decides are necessary, with the highest verbosity level.
7927 @end table
7929 @geindex -vl (gnatmake)
7932 @table @asis
7934 @item @code{-vl}
7936 Verbosity level Low. Display fewer lines than in verbosity Medium.
7937 @end table
7939 @geindex -vm (gnatmake)
7942 @table @asis
7944 @item @code{-vm}
7946 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7947 @end table
7949 @geindex -vm (gnatmake)
7952 @table @asis
7954 @item @code{-vh}
7956 Verbosity level High. Equivalent to -v.
7958 @item @code{-vP@emph{x}}
7960 Indicate the verbosity of the parsing of GNAT project files.
7961 See @ref{de,,Switches Related to Project Files}.
7962 @end table
7964 @geindex -x (gnatmake)
7967 @table @asis
7969 @item @code{-x}
7971 Indicate that sources that are not part of any Project File may be compiled.
7972 Normally, when using Project Files, only sources that are part of a Project
7973 File may be compile. When this switch is used, a source outside of all Project
7974 Files may be compiled. The ALI file and the object file will be put in the
7975 object directory of the main Project. The compilation switches used will only
7976 be those specified on the command line. Even when
7977 @emph{-x} is used, mains specified on the
7978 command line need to be sources of a project file.
7980 @item @code{-X@emph{name}=@emph{value}}
7982 Indicate that external variable @cite{name} has the value @cite{value}.
7983 The Project Manager will use this value for occurrences of
7984 @cite{external(name)} when parsing the project file.
7985 @ref{de,,Switches Related to Project Files}.
7986 @end table
7988 @geindex -z (gnatmake)
7991 @table @asis
7993 @item @code{-z}
7995 No main subprogram. Bind and link the program even if the unit name
7996 given on the command line is a package name. The resulting executable
7997 will execute the elaboration routines of the package and its closure,
7998 then the finalization routines.
7999 @end table
8001 @subsubheading GCC switches
8004 Any uppercase or multi-character switch that is not a @emph{gnatmake} switch
8005 is passed to @emph{gcc} (e.g., @emph{-O}, @emph{-gnato,} etc.)
8007 @subsubheading Source and library search path switches
8010 @geindex -aI (gnatmake)
8013 @table @asis
8015 @item @code{-aI@emph{dir}}
8017 When looking for source files also look in directory @cite{dir}.
8018 The order in which source files search is undertaken is
8019 described in @ref{89,,Search Paths and the Run-Time Library (RTL)}.
8020 @end table
8022 @geindex -aL (gnatmake)
8025 @table @asis
8027 @item @code{-aL@emph{dir}}
8029 Consider @cite{dir} as being an externally provided Ada library.
8030 Instructs @emph{gnatmake} to skip compilation units whose @code{.ALI}
8031 files have been located in directory @cite{dir}. This allows you to have
8032 missing bodies for the units in @cite{dir} and to ignore out of date bodies
8033 for the same units. You still need to specify
8034 the location of the specs for these units by using the switches
8035 @code{-aI@emph{dir}}  or @code{-I@emph{dir}}.
8036 Note: this switch is provided for compatibility with previous versions
8037 of @emph{gnatmake}. The easier method of causing standard libraries
8038 to be excluded from consideration is to write-protect the corresponding
8039 ALI files.
8040 @end table
8042 @geindex -aO (gnatmake)
8045 @table @asis
8047 @item @code{-aO@emph{dir}}
8049 When searching for library and object files, look in directory
8050 @cite{dir}. The order in which library files are searched is described in
8051 @ref{8c,,Search Paths for gnatbind}.
8052 @end table
8054 @geindex Search paths
8055 @geindex for gnatmake
8057 @geindex -A (gnatmake)
8060 @table @asis
8062 @item @code{-A@emph{dir}}
8064 Equivalent to @code{-aL@emph{dir}} @code{-aI@emph{dir}}.
8066 @geindex -I (gnatmake)
8068 @item @code{-I@emph{dir}}
8070 Equivalent to @code{-aO@emph{dir} -aI@emph{dir}}.
8071 @end table
8073 @geindex -I- (gnatmake)
8075 @geindex Source files
8076 @geindex suppressing search
8079 @table @asis
8081 @item @code{-I-}
8083 Do not look for source files in the directory containing the source
8084 file named in the command line.
8085 Do not look for ALI or object files in the directory
8086 where @emph{gnatmake} was invoked.
8087 @end table
8089 @geindex -L (gnatmake)
8091 @geindex Linker libraries
8094 @table @asis
8096 @item @code{-L@emph{dir}}
8098 Add directory @cite{dir} to the list of directories in which the linker
8099 will search for libraries. This is equivalent to
8100 @code{-largs} @code{-L@emph{dir}}.
8101 Furthermore, under Windows, the sources pointed to by the libraries path
8102 set in the registry are not searched for.
8103 @end table
8105 @geindex -nostdinc (gnatmake)
8108 @table @asis
8110 @item @code{-nostdinc}
8112 Do not look for source files in the system default directory.
8113 @end table
8115 @geindex -nostdlib (gnatmake)
8118 @table @asis
8120 @item @code{-nostdlib}
8122 Do not look for library files in the system default directory.
8123 @end table
8125 @geindex --RTS (gnatmake)
8128 @table @asis
8130 @item @code{--RTS=@emph{rts-path}}
8132 Specifies the default location of the runtime library. GNAT looks for the
8133 runtime
8134 in the following directories, and stops as soon as a valid runtime is found
8135 (@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
8136 @code{ada_object_path} present):
8139 @itemize *
8141 @item 
8142 @emph{<current directory>/$rts_path}
8144 @item 
8145 @emph{<default-search-dir>/$rts_path}
8147 @item 
8148 @emph{<default-search-dir>/rts-$rts_path}
8150 @item 
8151 The selected path is handled like a normal RTS path.
8152 @end itemize
8153 @end table
8155 @node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
8156 @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}
8157 @subsection Mode Switches for @emph{gnatmake}
8160 The mode switches (referred to as @cite{mode_switches}) allow the
8161 inclusion of switches that are to be passed to the compiler itself, the
8162 binder or the linker. The effect of a mode switch is to cause all
8163 subsequent switches up to the end of the switch list, or up to the next
8164 mode switch, to be interpreted as switches to be passed on to the
8165 designated component of GNAT.
8167 @geindex -cargs (gnatmake)
8170 @table @asis
8172 @item @code{-cargs @emph{switches}}
8174 Compiler switches. Here @cite{switches} is a list of switches
8175 that are valid switches for @emph{gcc}. They will be passed on to
8176 all compile steps performed by @emph{gnatmake}.
8177 @end table
8179 @geindex -bargs (gnatmake)
8182 @table @asis
8184 @item @code{-bargs @emph{switches}}
8186 Binder switches. Here @cite{switches} is a list of switches
8187 that are valid switches for @cite{gnatbind}. They will be passed on to
8188 all bind steps performed by @emph{gnatmake}.
8189 @end table
8191 @geindex -largs (gnatmake)
8194 @table @asis
8196 @item @code{-largs @emph{switches}}
8198 Linker switches. Here @cite{switches} is a list of switches
8199 that are valid switches for @emph{gnatlink}. They will be passed on to
8200 all link steps performed by @emph{gnatmake}.
8201 @end table
8203 @geindex -margs (gnatmake)
8206 @table @asis
8208 @item @code{-margs @emph{switches}}
8210 Make switches. The switches are directly interpreted by @emph{gnatmake},
8211 regardless of any previous occurrence of @emph{-cargs}, @emph{-bargs}
8212 or @emph{-largs}.
8213 @end table
8215 @node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
8216 @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}
8217 @subsection Notes on the Command Line
8220 This section contains some additional useful notes on the operation
8221 of the @emph{gnatmake} command.
8223 @geindex Recompilation (by gnatmake)
8226 @itemize *
8228 @item 
8229 If @emph{gnatmake} finds no ALI files, it recompiles the main program
8230 and all other units required by the main program.
8231 This means that @emph{gnatmake}
8232 can be used for the initial compile, as well as during subsequent steps of
8233 the development cycle.
8235 @item 
8236 If you enter @code{gnatmake foo.adb}, where @code{foo}
8237 is a subunit or body of a generic unit, @emph{gnatmake} recompiles
8238 @code{foo.adb} (because it finds no ALI) and stops, issuing a
8239 warning.
8241 @item 
8242 In @emph{gnatmake} the switch @emph{-I}
8243 is used to specify both source and
8244 library file paths. Use @emph{-aI}
8245 instead if you just want to specify
8246 source paths only and @emph{-aO}
8247 if you want to specify library paths
8248 only.
8250 @item 
8251 @emph{gnatmake} will ignore any files whose ALI file is write-protected.
8252 This may conveniently be used to exclude standard libraries from
8253 consideration and in particular it means that the use of the
8254 @emph{-f} switch will not recompile these files
8255 unless @emph{-a} is also specified.
8257 @item 
8258 @emph{gnatmake} has been designed to make the use of Ada libraries
8259 particularly convenient. Assume you have an Ada library organized
8260 as follows: @emph{obj-dir} contains the objects and ALI files for
8261 of your Ada compilation units,
8262 whereas @emph{include-dir} contains the
8263 specs of these units, but no bodies. Then to compile a unit
8264 stored in @cite{main.adb}, which uses this Ada library you would just type:
8266 @example
8267 $ gnatmake -aI`include-dir`  -aL`obj-dir`  main
8268 @end example
8270 @item 
8271 Using @emph{gnatmake} along with the @emph{-m (minimal recompilation)}
8272 switch provides a mechanism for avoiding unnecessary recompilations. Using
8273 this switch,
8274 you can update the comments/format of your
8275 source files without having to recompile everything. Note, however, that
8276 adding or deleting lines in a source files may render its debugging
8277 info obsolete. If the file in question is a spec, the impact is rather
8278 limited, as that debugging info will only be useful during the
8279 elaboration phase of your program. For bodies the impact can be more
8280 significant. In all events, your debugger will warn you if a source file
8281 is more recent than the corresponding object, and alert you to the fact
8282 that the debugging information may be out of date.
8283 @end itemize
8285 @node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8286 @anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{e3}@anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{e4}
8287 @subsection How @emph{gnatmake} Works
8290 Generally @emph{gnatmake} automatically performs all necessary
8291 recompilations and you don't need to worry about how it works. However,
8292 it may be useful to have some basic understanding of the @emph{gnatmake}
8293 approach and in particular to understand how it uses the results of
8294 previous compilations without incorrectly depending on them.
8296 First a definition: an object file is considered @emph{up to date} if the
8297 corresponding ALI file exists and if all the source files listed in the
8298 dependency section of this ALI file have time stamps matching those in
8299 the ALI file. This means that neither the source file itself nor any
8300 files that it depends on have been modified, and hence there is no need
8301 to recompile this file.
8303 @emph{gnatmake} works by first checking if the specified main unit is up
8304 to date. If so, no compilations are required for the main unit. If not,
8305 @emph{gnatmake} compiles the main program to build a new ALI file that
8306 reflects the latest sources. Then the ALI file of the main unit is
8307 examined to find all the source files on which the main program depends,
8308 and @emph{gnatmake} recursively applies the above procedure on all these
8309 files.
8311 This process ensures that @emph{gnatmake} only trusts the dependencies
8312 in an existing ALI file if they are known to be correct. Otherwise it
8313 always recompiles to determine a new, guaranteed accurate set of
8314 dependencies. As a result the program is compiled 'upside down' from what may
8315 be more familiar as the required order of compilation in some other Ada
8316 systems. In particular, clients are compiled before the units on which
8317 they depend. The ability of GNAT to compile in any order is critical in
8318 allowing an order of compilation to be chosen that guarantees that
8319 @emph{gnatmake} will recompute a correct set of new dependencies if
8320 necessary.
8322 When invoking @emph{gnatmake} with several @cite{file_names}, if a unit is
8323 imported by several of the executables, it will be recompiled at most once.
8325 Note: when using non-standard naming conventions
8326 (@ref{35,,Using Other File Names}), changing through a configuration pragmas
8327 file the version of a source and invoking @emph{gnatmake} to recompile may
8328 have no effect, if the previous version of the source is still accessible
8329 by @emph{gnatmake}. It may be necessary to use the switch
8332 @node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8333 @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}
8334 @subsection Examples of @emph{gnatmake} Usage
8338 @table @asis
8340 @item @emph{gnatmake hello.adb}
8342 Compile all files necessary to bind and link the main program
8343 @code{hello.adb} (containing unit @cite{Hello}) and bind and link the
8344 resulting object files to generate an executable file @code{hello}.
8346 @item @emph{gnatmake main1 main2 main3}
8348 Compile all files necessary to bind and link the main programs
8349 @code{main1.adb} (containing unit @cite{Main1}), @code{main2.adb}
8350 (containing unit @cite{Main2}) and @code{main3.adb}
8351 (containing unit @cite{Main3}) and bind and link the resulting object files
8352 to generate three executable files @code{main1},
8353 @code{main2}  and @code{main3}.
8355 @item @emph{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8357 Compile all files necessary to bind and link the main program unit
8358 @cite{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8359 be done with optimization level 2 and the order of elaboration will be
8360 listed by the binder. @emph{gnatmake} will operate in quiet mode, not
8361 displaying commands it is executing.
8362 @end table
8364 @node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8365 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{1c}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{e7}
8366 @section Compiling with @emph{gcc}
8369 This section discusses how to compile Ada programs using the @emph{gcc}
8370 command. It also describes the set of switches
8371 that can be used to control the behavior of the compiler.
8373 @menu
8374 * Compiling Programs:: 
8375 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
8376 * Order of Compilation Issues:: 
8377 * Examples:: 
8379 @end menu
8381 @node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8382 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{e8}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{e9}
8383 @subsection Compiling Programs
8386 The first step in creating an executable program is to compile the units
8387 of the program using the @emph{gcc} command. You must compile the
8388 following files:
8391 @itemize *
8393 @item 
8394 the body file (@code{.adb}) for a library level subprogram or generic
8395 subprogram
8397 @item 
8398 the spec file (@code{.ads}) for a library level package or generic
8399 package that has no body
8401 @item 
8402 the body file (@code{.adb}) for a library level package
8403 or generic package that has a body
8404 @end itemize
8406 You need @emph{not} compile the following files
8409 @itemize *
8411 @item 
8412 the spec of a library unit which has a body
8414 @item 
8415 subunits
8416 @end itemize
8418 because they are compiled as part of compiling related units. GNAT
8419 package specs
8420 when the corresponding body is compiled, and subunits when the parent is
8421 compiled.
8423 @geindex cannot generate code
8425 If you attempt to compile any of these files, you will get one of the
8426 following error messages (where @cite{fff} is the name of the file you
8427 compiled):
8429 @quotation
8431 @example
8432 cannot generate code for file `fff` (package spec)
8433 to check package spec, use -gnatc
8435 cannot generate code for file `fff` (missing subunits)
8436 to check parent unit, use -gnatc
8438 cannot generate code for file `fff` (subprogram spec)
8439 to check subprogram spec, use -gnatc
8441 cannot generate code for file `fff` (subunit)
8442 to check subunit, use -gnatc
8443 @end example
8444 @end quotation
8446 As indicated by the above error messages, if you want to submit
8447 one of these files to the compiler to check for correct semantics
8448 without generating code, then use the @emph{-gnatc} switch.
8450 The basic command for compiling a file containing an Ada unit is:
8452 @example
8453 $ gcc -c [switches] <file name>
8454 @end example
8456 where @cite{file name} is the name of the Ada file (usually
8457 having an extension @code{.ads} for a spec or @code{.adb} for a body).
8458 You specify the
8459 @code{-c} switch to tell @emph{gcc} to compile, but not link, the file.
8460 The result of a successful compilation is an object file, which has the
8461 same name as the source file but an extension of @code{.o} and an Ada
8462 Library Information (ALI) file, which also has the same name as the
8463 source file, but with @code{.ali} as the extension. GNAT creates these
8464 two output files in the current directory, but you may specify a source
8465 file in any directory using an absolute or relative path specification
8466 containing the directory information.
8468 @geindex gnat1
8470 @emph{gcc} is actually a driver program that looks at the extensions of
8471 the file arguments and loads the appropriate compiler. For example, the
8472 GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8473 These programs are in directories known to the driver program (in some
8474 configurations via environment variables you set), but need not be in
8475 your path. The @emph{gcc} driver also calls the assembler and any other
8476 utilities needed to complete the generation of the required object
8477 files.
8479 It is possible to supply several file names on the same @emph{gcc}
8480 command. This causes @emph{gcc} to call the appropriate compiler for
8481 each file. For example, the following command lists two separate
8482 files to be compiled:
8484 @example
8485 $ gcc -c x.adb y.adb
8486 @end example
8488 calls @cite{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8489 @code{y.adb}.
8490 The compiler generates two object files @code{x.o} and @code{y.o}
8491 and the two ALI files @code{x.ali} and @code{y.ali}.
8493 Any switches apply to all the files listed, see @ref{ea,,Compiler Switches} for a
8494 list of available @emph{gcc} switches.
8496 @node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8497 @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}
8498 @subsection Search Paths and the Run-Time Library (RTL)
8501 With the GNAT source-based library system, the compiler must be able to
8502 find source files for units that are needed by the unit being compiled.
8503 Search paths are used to guide this process.
8505 The compiler compiles one source file whose name must be given
8506 explicitly on the command line. In other words, no searching is done
8507 for this file. To find all other source files that are needed (the most
8508 common being the specs of units), the compiler examines the following
8509 directories, in the following order:
8512 @itemize *
8514 @item 
8515 The directory containing the source file of the main unit being compiled
8516 (the file name on the command line).
8518 @item 
8519 Each directory named by an @emph{-I} switch given on the @emph{gcc}
8520 command line, in the order given.
8522 @geindex ADA_PRJ_INCLUDE_FILE
8524 @item 
8525 Each of the directories listed in the text file whose name is given
8526 by the 
8527 @geindex ADA_PRJ_INCLUDE_FILE
8528 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8529 @code{ADA_PRJ_INCLUDE_FILE} environment variable.
8530 @geindex ADA_PRJ_INCLUDE_FILE
8531 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8532 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8533 driver when project files are used. It should not normally be set
8534 by other means.
8536 @geindex ADA_INCLUDE_PATH
8538 @item 
8539 Each of the directories listed in the value of the
8540 @geindex ADA_INCLUDE_PATH
8541 @geindex environment variable; ADA_INCLUDE_PATH
8542 @code{ADA_INCLUDE_PATH} environment variable.
8543 Construct this value
8544 exactly as the 
8545 @geindex PATH
8546 @geindex environment variable; PATH
8547 @code{PATH} environment variable: a list of directory
8548 names separated by colons (semicolons when working with the NT version).
8550 @item 
8551 The content of the @code{ada_source_path} file which is part of the GNAT
8552 installation tree and is used to store standard libraries such as the
8553 GNAT Run Time Library (RTL) source files.
8554 @ref{87,,Installing a library}
8555 @end itemize
8557 Specifying the switch @emph{-I-}
8558 inhibits the use of the directory
8559 containing the source file named in the command line. You can still
8560 have this directory on your search path, but in this case it must be
8561 explicitly requested with a @emph{-I} switch.
8563 Specifying the switch @emph{-nostdinc}
8564 inhibits the search of the default location for the GNAT Run Time
8565 Library (RTL) source files.
8567 The compiler outputs its object files and ALI files in the current
8568 working directory.
8569 Caution: The object file can be redirected with the @emph{-o} switch;
8570 however, @emph{gcc} and @cite{gnat1} have not been coordinated on this
8571 so the @code{ALI} file will not go to the right place. Therefore, you should
8572 avoid using the @emph{-o} switch.
8574 @geindex System.IO
8576 The packages @cite{Ada}, @cite{System}, and @cite{Interfaces} and their
8577 children make up the GNAT RTL, together with the simple @cite{System.IO}
8578 package used in the @cite{"Hello World"} example. The sources for these units
8579 are needed by the compiler and are kept together in one directory. Not
8580 all of the bodies are needed, but all of the sources are kept together
8581 anyway. In a normal installation, you need not specify these directory
8582 names when compiling or binding. Either the environment variables or
8583 the built-in defaults cause these files to be found.
8585 In addition to the language-defined hierarchies (@cite{System}, @cite{Ada} and
8586 @cite{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8587 consisting of child units of @cite{GNAT}. This is a collection of generally
8588 useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8589 for further details.
8591 Besides simplifying access to the RTL, a major use of search paths is
8592 in compiling sources from multiple directories. This can make
8593 development environments much more flexible.
8595 @node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8596 @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}
8597 @subsection Order of Compilation Issues
8600 If, in our earlier example, there was a spec for the @cite{hello}
8601 procedure, it would be contained in the file @code{hello.ads}; yet this
8602 file would not have to be explicitly compiled. This is the result of the
8603 model we chose to implement library management. Some of the consequences
8604 of this model are as follows:
8607 @itemize *
8609 @item 
8610 There is no point in compiling specs (except for package
8611 specs with no bodies) because these are compiled as needed by clients. If
8612 you attempt a useless compilation, you will receive an error message.
8613 It is also useless to compile subunits because they are compiled as needed
8614 by the parent.
8616 @item 
8617 There are no order of compilation requirements: performing a
8618 compilation never obsoletes anything. The only way you can obsolete
8619 something and require recompilations is to modify one of the
8620 source files on which it depends.
8622 @item 
8623 There is no library as such, apart from the ALI files
8624 (@ref{42,,The Ada Library Information Files}, for information on the format
8625 of these files). For now we find it convenient to create separate ALI files,
8626 but eventually the information therein may be incorporated into the object
8627 file directly.
8629 @item 
8630 When you compile a unit, the source files for the specs of all units
8631 that it @emph{with}s, all its subunits, and the bodies of any generics it
8632 instantiates must be available (reachable by the search-paths mechanism
8633 described above), or you will receive a fatal error message.
8634 @end itemize
8636 @node Examples,,Order of Compilation Issues,Compiling with gcc
8637 @anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{ee}@anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{ef}
8638 @subsection Examples
8641 The following are some typical Ada compilation command line examples:
8643 @example
8644 $ gcc -c xyz.adb
8645 @end example
8647 Compile body in file @code{xyz.adb} with all default options.
8649 @example
8650 $ gcc -c -O2 -gnata xyz-def.adb
8651 @end example
8653 Compile the child unit package in file @code{xyz-def.adb} with extensive
8654 optimizations, and pragma @cite{Assert}/@cite{Debug} statements
8655 enabled.
8657 @example
8658 $ gcc -c -gnatc abc-def.adb
8659 @end example
8661 Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8662 mode.
8664 @node Compiler Switches,Linker Switches,Compiling with gcc,Building Executable Programs with GNAT
8665 @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}
8666 @section Compiler Switches
8669 The @emph{gcc} command accepts switches that control the
8670 compilation process. These switches are fully described in this section:
8671 first an alphabetical listing of all switches with a brief description,
8672 and then functionally grouped sets of switches with more detailed
8673 information.
8675 More switches exist for GCC than those documented here, especially
8676 for specific targets. However, their use is not recommended as
8677 they may change code generation in ways that are incompatible with
8678 the Ada run-time library, or can cause inconsistencies between
8679 compilation units.
8681 @menu
8682 * Alphabetical List of All Switches:: 
8683 * Output and Error Message Control:: 
8684 * Warning Message Control:: 
8685 * Debugging and Assertion Control:: 
8686 * Validity Checking:: 
8687 * Style Checking:: 
8688 * Run-Time Checks:: 
8689 * Using gcc for Syntax Checking:: 
8690 * Using gcc for Semantic Checking:: 
8691 * Compiling Different Versions of Ada:: 
8692 * Character Set Control:: 
8693 * File Naming Control:: 
8694 * Subprogram Inlining Control:: 
8695 * Auxiliary Output Control:: 
8696 * Debugging Control:: 
8697 * Exception Handling Control:: 
8698 * Units to Sources Mapping Files:: 
8699 * Code Generation Control:: 
8701 @end menu
8703 @node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8704 @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}
8705 @subsection Alphabetical List of All Switches
8708 @geindex -b (gcc)
8711 @table @asis
8713 @item @code{-b @emph{target}}
8715 Compile your program to run on @cite{target}, which is the name of a
8716 system configuration. You must have a GNAT cross-compiler built if
8717 @cite{target} is not the same as your host system.
8718 @end table
8720 @geindex -B (gcc)
8723 @table @asis
8725 @item @code{-B@emph{dir}}
8727 Load compiler executables (for example, @cite{gnat1}, the Ada compiler)
8728 from @cite{dir} instead of the default location. Only use this switch
8729 when multiple versions of the GNAT compiler are available.
8730 See the "Options for Directory Search" section in the
8731 @cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8732 You would normally use the @emph{-b} or @emph{-V} switch instead.
8733 @end table
8735 @geindex -c (gcc)
8738 @table @asis
8740 @item @code{-c}
8742 Compile. Always use this switch when compiling Ada programs.
8744 Note: for some other languages when using @emph{gcc}, notably in
8745 the case of C and C++, it is possible to use
8746 use @emph{gcc} without a @emph{-c} switch to
8747 compile and link in one step. In the case of GNAT, you
8748 cannot use this approach, because the binder must be run
8749 and @emph{gcc} cannot be used to run the GNAT binder.
8750 @end table
8752 @geindex -fcallgraph-info (gcc)
8755 @table @asis
8757 @item @code{-fcallgraph-info[=su,da]}
8759 Makes the compiler output callgraph information for the program, on a
8760 per-file basis. The information is generated in the VCG format.  It can
8761 be decorated with additional, per-node and/or per-edge information, if a
8762 list of comma-separated markers is additionally specified. When the
8763 @cite{su} marker is specified, the callgraph is decorated with stack usage
8764 information; it is equivalent to @emph{-fstack-usage}. When the @cite{da}
8765 marker is specified, the callgraph is decorated with information about
8766 dynamically allocated objects.
8767 @end table
8769 @geindex -fdump-scos (gcc)
8772 @table @asis
8774 @item @code{-fdump-scos}
8776 Generates SCO (Source Coverage Obligation) information in the ALI file.
8777 This information is used by advanced coverage tools. See unit @code{SCOs}
8778 in the compiler sources for details in files @code{scos.ads} and
8779 @code{scos.adb}.
8780 @end table
8782 @geindex -fdump-xref (gcc)
8785 @table @asis
8787 @item @code{-fdump-xref}
8789 Generates cross reference information in GLI files for C and C++ sources.
8790 The GLI files have the same syntax as the ALI files for Ada, and can be used
8791 for source navigation in IDEs and on the command line using e.g. gnatxref
8792 and the @emph{--ext=gli} switch.
8793 @end table
8795 @geindex -flto (gcc)
8798 @table @asis
8800 @item @code{-flto[=@emph{n}]}
8802 Enables Link Time Optimization. This switch must be used in conjunction
8803 with the traditional @emph{-Ox} switches and instructs the compiler to
8804 defer most optimizations until the link stage. The advantage of this
8805 approach is that the compiler can do a whole-program analysis and choose
8806 the best interprocedural optimization strategy based on a complete view
8807 of the program, instead of a fragmentary view with the usual approach.
8808 This can also speed up the compilation of big programs and reduce the
8809 size of the executable, compared with a traditional per-unit compilation
8810 with inlining across modules enabled by the @emph{-gnatn} switch.
8811 The drawback of this approach is that it may require more memory and that
8812 the debugging information generated by -g with it might be hardly usable.
8813 The switch, as well as the accompanying @emph{-Ox} switches, must be
8814 specified both for the compilation and the link phases.
8815 If the @cite{n} parameter is specified, the optimization and final code
8816 generation at link time are executed using @cite{n} parallel jobs by
8817 means of an installed @emph{make} program.
8818 @end table
8820 @geindex -fno-inline (gcc)
8823 @table @asis
8825 @item @code{-fno-inline}
8827 Suppresses all inlining, unless requested with pragma @cite{Inline_Always}. The
8828 effect is enforced regardless of other optimization or inlining switches.
8829 Note that inlining can also be suppressed on a finer-grained basis with
8830 pragma @cite{No_Inline}.
8831 @end table
8833 @geindex -fno-inline-functions (gcc)
8836 @table @asis
8838 @item @code{-fno-inline-functions}
8840 Suppresses automatic inlining of subprograms, which is enabled
8841 if @emph{-O3} is used.
8842 @end table
8844 @geindex -fno-inline-small-functions (gcc)
8847 @table @asis
8849 @item @code{-fno-inline-small-functions}
8851 Suppresses automatic inlining of small subprograms, which is enabled
8852 if @emph{-O2} is used.
8853 @end table
8855 @geindex -fno-inline-functions-called-once (gcc)
8858 @table @asis
8860 @item @code{-fno-inline-functions-called-once}
8862 Suppresses inlining of subprograms local to the unit and called once
8863 from within it, which is enabled if @emph{-O1} is used.
8864 @end table
8866 @geindex -fno-ivopts (gcc)
8869 @table @asis
8871 @item @code{-fno-ivopts}
8873 Suppresses high-level loop induction variable optimizations, which are
8874 enabled if @emph{-O1} is used. These optimizations are generally
8875 profitable but, for some specific cases of loops with numerous uses
8876 of the iteration variable that follow a common pattern, they may end
8877 up destroying the regularity that could be exploited at a lower level
8878 and thus producing inferior code.
8879 @end table
8881 @geindex -fno-strict-aliasing (gcc)
8884 @table @asis
8886 @item @code{-fno-strict-aliasing}
8888 Causes the compiler to avoid assumptions regarding non-aliasing
8889 of objects of different types. See
8890 @ref{f3,,Optimization and Strict Aliasing} for details.
8891 @end table
8893 @geindex -fno-strict-overflow (gcc)
8896 @table @asis
8898 @item @code{-fno-strict-overflow}
8900 Causes the compiler to avoid assumptions regarding the rules of signed
8901 integer overflow. These rules specify that signed integer overflow will
8902 result in a Constraint_Error exception at run time and are enforced in
8903 default mode by the compiler, so this switch should not be necessary in
8904 normal operating mode. It might be useful in conjunction with @emph{-gnato0}
8905 for very peculiar cases of low-level programming.
8906 @end table
8908 @geindex -fstack-check (gcc)
8911 @table @asis
8913 @item @code{-fstack-check}
8915 Activates stack checking.
8916 See @ref{f4,,Stack Overflow Checking} for details.
8917 @end table
8919 @geindex -fstack-usage (gcc)
8922 @table @asis
8924 @item @code{-fstack-usage}
8926 Makes the compiler output stack usage information for the program, on a
8927 per-subprogram basis. See @ref{f5,,Static Stack Usage Analysis} for details.
8928 @end table
8930 @geindex -g (gcc)
8933 @table @asis
8935 @item @code{-g}
8937 Generate debugging information. This information is stored in the object
8938 file and copied from there to the final executable file by the linker,
8939 where it can be read by the debugger. You must use the
8940 @emph{-g} switch if you plan on using the debugger.
8941 @end table
8943 @geindex -gnat05 (gcc)
8946 @table @asis
8948 @item @code{-gnat05}
8950 Allow full Ada 2005 features.
8951 @end table
8953 @geindex -gnat12 (gcc)
8956 @table @asis
8958 @item @code{-gnat12}
8960 Allow full Ada 2012 features.
8961 @end table
8963 @geindex -gnat83 (gcc)
8965 @geindex -gnat2005 (gcc)
8968 @table @asis
8970 @item @code{-gnat2005}
8972 Allow full Ada 2005 features (same as @emph{-gnat05})
8973 @end table
8975 @geindex -gnat2012 (gcc)
8978 @table @asis
8980 @item @code{-gnat2012}
8982 Allow full Ada 2012 features (same as @emph{-gnat12})
8984 @item @code{-gnat83}
8986 Enforce Ada 83 restrictions.
8987 @end table
8989 @geindex -gnat95 (gcc)
8992 @table @asis
8994 @item @code{-gnat95}
8996 Enforce Ada 95 restrictions.
8998 Note: for compatibility with some Ada 95 compilers which support only
8999 the @cite{overriding} keyword of Ada 2005, the @emph{-gnatd.D} switch can
9000 be used along with @emph{-gnat95} to achieve a similar effect with GNAT.
9002 @emph{-gnatd.D} instructs GNAT to consider @cite{overriding} as a keyword
9003 and handle its associated semantic checks, even in Ada 95 mode.
9004 @end table
9006 @geindex -gnata (gcc)
9009 @table @asis
9011 @item @code{-gnata}
9013 Assertions enabled. @cite{Pragma Assert} and @cite{pragma Debug} to be
9014 activated. Note that these pragmas can also be controlled using the
9015 configuration pragmas @cite{Assertion_Policy} and @cite{Debug_Policy}.
9016 It also activates pragmas @cite{Check}, @cite{Precondition}, and
9017 @cite{Postcondition}. Note that these pragmas can also be controlled
9018 using the configuration pragma @cite{Check_Policy}. In Ada 2012, it
9019 also activates all assertions defined in the RM as aspects: preconditions,
9020 postconditions, type invariants and (sub)type predicates. In all Ada modes,
9021 corresponding pragmas for type invariants and (sub)type predicates are
9022 also activated. The default is that all these assertions are disabled,
9023 and have no effect, other than being checked for syntactic validity, and
9024 in the case of subtype predicates, constructions such as membership tests
9025 still test predicates even if assertions are turned off.
9026 @end table
9028 @geindex -gnatA (gcc)
9031 @table @asis
9033 @item @code{-gnatA}
9035 Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
9036 it will be ignored.
9037 @end table
9039 @geindex -gnatb (gcc)
9042 @table @asis
9044 @item @code{-gnatb}
9046 Generate brief messages to @code{stderr} even if verbose mode set.
9047 @end table
9049 @geindex -gnatB (gcc)
9052 @table @asis
9054 @item @code{-gnatB}
9056 Assume no invalid (bad) values except for 'Valid attribute use
9057 (@ref{f6,,Validity Checking}).
9058 @end table
9060 @geindex -gnatc (gcc)
9063 @table @asis
9065 @item @code{-gnatc}
9067 Check syntax and semantics only (no code generation attempted). When the
9068 compiler is invoked by @emph{gnatmake}, if the switch @emph{-gnatc} is
9069 only given to the compiler (after @emph{-cargs} or in package Compiler of
9070 the project file, @emph{gnatmake} will fail because it will not find the
9071 object file after compilation. If @emph{gnatmake} is called with
9072 @emph{-gnatc} as a builder switch (before @emph{-cargs} or in package
9073 Builder of the project file) then @emph{gnatmake} will not fail because
9074 it will not look for the object files after compilation, and it will not try
9075 to build and link.
9076 @end table
9078 @geindex -gnatC (gcc)
9081 @table @asis
9083 @item @code{-gnatC}
9085 Generate CodePeer intermediate format (no code generation attempted).
9086 This switch will generate an intermediate representation suitable for
9087 use by CodePeer (@code{.scil} files). This switch is not compatible with
9088 code generation (it will, among other things, disable some switches such
9089 as -gnatn, and enable others such as -gnata).
9090 @end table
9092 @geindex -gnatd (gcc)
9095 @table @asis
9097 @item @code{-gnatd}
9099 Specify debug options for the compiler. The string of characters after
9100 the @emph{-gnatd} specify the specific debug options. The possible
9101 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
9102 compiler source file @code{debug.adb} for details of the implemented
9103 debug options. Certain debug options are relevant to applications
9104 programmers, and these are documented at appropriate points in this
9105 users guide.
9106 @end table
9108 @geindex -gnatD[nn] (gcc)
9111 @table @asis
9113 @item @code{-gnatD}
9115 Create expanded source files for source level debugging. This switch
9116 also suppresses generation of cross-reference information
9117 (see @emph{-gnatx}). Note that this switch is not allowed if a previous
9118 -gnatR switch has been given, since these two switches are not compatible.
9119 @end table
9121 @geindex -gnateA (gcc)
9124 @table @asis
9126 @item @code{-gnateA}
9128 Check that the actual parameters of a subprogram call are not aliases of one
9129 another. To qualify as aliasing, the actuals must denote objects of a composite
9130 type, their memory locations must be identical or overlapping, and at least one
9131 of the corresponding formal parameters must be of mode OUT or IN OUT.
9133 @example
9134 type Rec_Typ is record
9135    Data : Integer := 0;
9136 end record;
9138 function Self (Val : Rec_Typ) return Rec_Typ is
9139 begin
9140    return Val;
9141 end Self;
9143 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
9144 begin
9145    null;
9146 end Detect_Aliasing;
9148 Obj : Rec_Typ;
9150 Detect_Aliasing (Obj, Obj);
9151 Detect_Aliasing (Obj, Self (Obj));
9152 @end example
9154 In the example above, the first call to @cite{Detect_Aliasing} fails with a
9155 @cite{Program_Error} at runtime because the actuals for @cite{Val_1} and
9156 @cite{Val_2} denote the same object. The second call executes without raising
9157 an exception because @cite{Self(Obj)} produces an anonymous object which does
9158 not share the memory location of @cite{Obj}.
9159 @end table
9161 @geindex -gnatec (gcc)
9164 @table @asis
9166 @item @code{-gnatec=@emph{path}}
9168 Specify a configuration pragma file
9169 (the equal sign is optional)
9170 (@ref{79,,The Configuration Pragmas Files}).
9171 @end table
9173 @geindex -gnateC (gcc)
9176 @table @asis
9178 @item @code{-gnateC}
9180 Generate CodePeer messages in a compiler-like format. This switch is only
9181 effective if @emph{-gnatcC} is also specified and requires an installation
9182 of CodePeer.
9183 @end table
9185 @geindex -gnated (gcc)
9188 @table @asis
9190 @item @code{-gnated}
9192 Disable atomic synchronization
9193 @end table
9195 @geindex -gnateD (gcc)
9198 @table @asis
9200 @item @code{-gnateDsymbol[=@emph{value}]}
9202 Defines a symbol, associated with @cite{value}, for preprocessing.
9203 (@ref{18,,Integrated Preprocessing}).
9204 @end table
9206 @geindex -gnateE (gcc)
9209 @table @asis
9211 @item @code{-gnateE}
9213 Generate extra information in exception messages. In particular, display
9214 extra column information and the value and range associated with index and
9215 range check failures, and extra column information for access checks.
9216 In cases where the compiler is able to determine at compile time that
9217 a check will fail, it gives a warning, and the extra information is not
9218 produced at run time.
9219 @end table
9221 @geindex -gnatef (gcc)
9224 @table @asis
9226 @item @code{-gnatef}
9228 Display full source path name in brief error messages.
9229 @end table
9231 @geindex -gnateF (gcc)
9234 @table @asis
9236 @item @code{-gnateF}
9238 Check for overflow on all floating-point operations, including those
9239 for unconstrained predefined types. See description of pragma
9240 @cite{Check_Float_Overflow} in GNAT RM.
9241 @end table
9243 @geindex -gnateg (gcc)
9245 @code{-gnateg}
9246 @code{-gnatceg}
9248 @quotation
9250 The @cite{-gnatc} switch must always be specified before this switch, e.g.
9251 @cite{-gnatceg}. Generate a C header from the Ada input file. See
9252 @ref{ca,,Generating C Headers for Ada Specifications} for more
9253 information.
9254 @end quotation
9256 @geindex -gnateG (gcc)
9259 @table @asis
9261 @item @code{-gnateG}
9263 Save result of preprocessing in a text file.
9264 @end table
9266 @geindex -gnatei (gcc)
9269 @table @asis
9271 @item @code{-gnatei@emph{nnn}}
9273 Set maximum number of instantiations during compilation of a single unit to
9274 @cite{nnn}. This may be useful in increasing the default maximum of 8000 for
9275 the rare case when a single unit legitimately exceeds this limit.
9276 @end table
9278 @geindex -gnateI (gcc)
9281 @table @asis
9283 @item @code{-gnateI@emph{nnn}}
9285 Indicates that the source is a multi-unit source and that the index of the
9286 unit to compile is @cite{nnn}. @cite{nnn} needs to be a positive number and need
9287 to be a valid index in the multi-unit source.
9288 @end table
9290 @geindex -gnatel (gcc)
9293 @table @asis
9295 @item @code{-gnatel}
9297 This switch can be used with the static elaboration model to issue info
9298 messages showing
9299 where implicit @cite{pragma Elaborate} and @cite{pragma Elaborate_All}
9300 are generated. This is useful in diagnosing elaboration circularities
9301 caused by these implicit pragmas when using the static elaboration
9302 model. See See the section in this guide on elaboration checking for
9303 further details. These messages are not generated by default, and are
9304 intended only for temporary use when debugging circularity problems.
9305 @end table
9307 @geindex -gnatel (gcc)
9310 @table @asis
9312 @item @code{-gnateL}
9314 This switch turns off the info messages about implicit elaboration pragmas.
9315 @end table
9317 @geindex -gnatem (gcc)
9320 @table @asis
9322 @item @code{-gnatem=@emph{path}}
9324 Specify a mapping file
9325 (the equal sign is optional)
9326 (@ref{f7,,Units to Sources Mapping Files}).
9327 @end table
9329 @geindex -gnatep (gcc)
9332 @table @asis
9334 @item @code{-gnatep=@emph{file}}
9336 Specify a preprocessing data file
9337 (the equal sign is optional)
9338 (@ref{18,,Integrated Preprocessing}).
9339 @end table
9341 @geindex -gnateP (gcc)
9344 @table @asis
9346 @item @code{-gnateP}
9348 Turn categorization dependency errors into warnings.
9349 Ada requires that units that WITH one another have compatible categories, for
9350 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9351 these errors become warnings (which can be ignored, or suppressed in the usual
9352 manner). This can be useful in some specialized circumstances such as the
9353 temporary use of special test software.
9354 @end table
9356 @geindex -gnateS (gcc)
9359 @table @asis
9361 @item @code{-gnateS}
9363 Synonym of @emph{-fdump-scos}, kept for backwards compatibility.
9364 @end table
9366 @geindex -gnatet=file (gcc)
9369 @table @asis
9371 @item @code{-gnatet=@emph{path}}
9373 Generate target dependent information. The format of the output file is
9374 described in the section about switch @emph{-gnateT}.
9375 @end table
9377 @geindex -gnateT (gcc)
9380 @table @asis
9382 @item @code{-gnateT=@emph{path}}
9384 Read target dependent information, such as endianness or sizes and alignments
9385 of base type. If this switch is passed, the default target dependent
9386 information of the compiler is replaced by the one read from the input file.
9387 This is used by tools other than the compiler, e.g. to do
9388 semantic analysis of programs that will run on some other target than
9389 the machine on which the tool is run.
9391 The following target dependent values should be defined,
9392 where @cite{Nat} denotes a natural integer value, @cite{Pos} denotes a
9393 positive integer value, and fields marked with a question mark are
9394 boolean fields, where a value of 0 is False, and a value of 1 is True:
9396 @example
9397 Bits_BE                    : Nat; -- Bits stored big-endian?
9398 Bits_Per_Unit              : Pos; -- Bits in a storage unit
9399 Bits_Per_Word              : Pos; -- Bits in a word
9400 Bytes_BE                   : Nat; -- Bytes stored big-endian?
9401 Char_Size                  : Pos; -- Standard.Character'Size
9402 Double_Float_Alignment     : Nat; -- Alignment of double float
9403 Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
9404 Double_Size                : Pos; -- Standard.Long_Float'Size
9405 Float_Size                 : Pos; -- Standard.Float'Size
9406 Float_Words_BE             : Nat; -- Float words stored big-endian?
9407 Int_Size                   : Pos; -- Standard.Integer'Size
9408 Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
9409 Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
9410 Long_Size                  : Pos; -- Standard.Long_Integer'Size
9411 Maximum_Alignment          : Pos; -- Maximum permitted alignment
9412 Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
9413 Pointer_Size               : Pos; -- System.Address'Size
9414 Short_Enums                : Nat; -- Short foreign convention enums?
9415 Short_Size                 : Pos; -- Standard.Short_Integer'Size
9416 Strict_Alignment           : Nat; -- Strict alignment?
9417 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9418 Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
9419 Words_BE                   : Nat; -- Words stored big-endian?
9420 @end example
9422 The format of the input file is as follows. First come the values of
9423 the variables defined above, with one line per value:
9425 @example
9426 name  value
9427 @end example
9429 where @cite{name} is the name of the parameter, spelled out in full,
9430 and cased as in the above list, and @cite{value} is an unsigned decimal
9431 integer. Two or more blanks separates the name from the value.
9433 All the variables must be present, in alphabetical order (i.e. the
9434 same order as the list above).
9436 Then there is a blank line to separate the two parts of the file. Then
9437 come the lines showing the floating-point types to be registered, with
9438 one line per registered mode:
9440 @example
9441 name  digs float_rep size alignment
9442 @end example
9444 where @cite{name} is the string name of the type (which can have
9445 single spaces embedded in the name (e.g. long double), @cite{digs} is
9446 the number of digits for the floating-point type, @cite{float_rep} is
9447 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
9448 AAMP), @cite{size} is the size in bits, @cite{alignment} is the
9449 alignment in bits. The name is followed by at least two blanks, fields
9450 are separated by at least one blank, and a LF character immediately
9451 follows the alignment field.
9453 Here is an example of a target parameterization file:
9455 @example
9456 Bits_BE                       0
9457 Bits_Per_Unit                 8
9458 Bits_Per_Word                64
9459 Bytes_BE                      0
9460 Char_Size                     8
9461 Double_Float_Alignment        0
9462 Double_Scalar_Alignment       0
9463 Double_Size                  64
9464 Float_Size                   32
9465 Float_Words_BE                0
9466 Int_Size                     64
9467 Long_Double_Size            128
9468 Long_Long_Size               64
9469 Long_Size                    64
9470 Maximum_Alignment            16
9471 Max_Unaligned_Field          64
9472 Pointer_Size                 64
9473 Short_Size                   16
9474 Strict_Alignment              0
9475 System_Allocator_Alignment   16
9476 Wchar_T_Size                 32
9477 Words_BE                      0
9479 float         15  I  64  64
9480 double        15  I  64  64
9481 long double   18  I  80 128
9482 TF            33  I 128 128
9483 @end example
9484 @end table
9486 @geindex -gnateu (gcc)
9489 @table @asis
9491 @item @code{-gnateu}
9493 Ignore unrecognized validity, warning, and style switches that
9494 appear after this switch is given. This may be useful when
9495 compiling sources developed on a later version of the compiler
9496 with an earlier version. Of course the earlier version must
9497 support this switch.
9498 @end table
9500 @geindex -gnateV (gcc)
9503 @table @asis
9505 @item @code{-gnateV}
9507 Check that all actual parameters of a subprogram call are valid according to
9508 the rules of validity checking (@ref{f6,,Validity Checking}).
9509 @end table
9511 @geindex -gnateY (gcc)
9514 @table @asis
9516 @item @code{-gnateY}
9518 Ignore all STYLE_CHECKS pragmas. Full legality checks
9519 are still carried out, but the pragmas have no effect
9520 on what style checks are active. This allows all style
9521 checking options to be controlled from the command line.
9522 @end table
9524 @geindex -gnatE (gcc)
9527 @table @asis
9529 @item @code{-gnatE}
9531 Full dynamic elaboration checks.
9532 @end table
9534 @geindex -gnatf (gcc)
9537 @table @asis
9539 @item @code{-gnatf}
9541 Full errors. Multiple errors per line, all undefined references, do not
9542 attempt to suppress cascaded errors.
9543 @end table
9545 @geindex -gnatF (gcc)
9548 @table @asis
9550 @item @code{-gnatF}
9552 Externals names are folded to all uppercase.
9553 @end table
9555 @geindex -gnatg (gcc)
9558 @table @asis
9560 @item @code{-gnatg}
9562 Internal GNAT implementation mode. This should not be used for
9563 applications programs, it is intended only for use by the compiler
9564 and its run-time library. For documentation, see the GNAT sources.
9565 Note that @emph{-gnatg} implies
9566 @emph{-gnatw.ge} and
9567 @emph{-gnatyg}
9568 so that all standard warnings and all standard style options are turned on.
9569 All warnings and style messages are treated as errors.
9570 @end table
9572 @geindex -gnatG[nn] (gcc)
9575 @table @asis
9577 @item @code{-gnatG=nn}
9579 List generated expanded code in source form.
9580 @end table
9582 @geindex -gnath (gcc)
9585 @table @asis
9587 @item @code{-gnath}
9589 Output usage information. The output is written to @code{stdout}.
9590 @end table
9592 @geindex -gnati (gcc)
9595 @table @asis
9597 @item @code{-gnati@emph{c}}
9599 Identifier character set (@cite{c} = 1/2/3/4/8/9/p/f/n/w).
9600 For details of the possible selections for @cite{c},
9601 see @ref{48,,Character Set Control}.
9602 @end table
9604 @geindex -gnatI (gcc)
9607 @table @asis
9609 @item @code{-gnatI}
9611 Ignore representation clauses. When this switch is used,
9612 representation clauses are treated as comments. This is useful
9613 when initially porting code where you want to ignore rep clause
9614 problems, and also for compiling foreign code (particularly
9615 for use with ASIS). The representation clauses that are ignored
9616 are: enumeration_representation_clause, record_representation_clause,
9617 and attribute_definition_clause for the following attributes:
9618 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9619 Object_Size, Size, Small, Stream_Size, and Value_Size.
9620 Note that this option should be used only for compiling -- the
9621 code is likely to malfunction at run time.
9623 Note that when @cite{-gnatct} is used to generate trees for input
9624 into @cite{ASIS} tools, these representation clauses are removed
9625 from the tree and ignored. This means that the tool will not see them.
9626 @end table
9628 @geindex -gnatjnn (gcc)
9631 @table @asis
9633 @item @code{-gnatj@emph{nn}}
9635 Reformat error messages to fit on @cite{nn} character lines
9636 @end table
9638 @geindex -gnatk (gcc)
9641 @table @asis
9643 @item @code{-gnatk=@emph{n}}
9645 Limit file names to @cite{n} (1-999) characters (@cite{k} = krunch).
9646 @end table
9648 @geindex -gnatl (gcc)
9651 @table @asis
9653 @item @code{-gnatl}
9655 Output full source listing with embedded error messages.
9656 @end table
9658 @geindex -gnatL (gcc)
9661 @table @asis
9663 @item @code{-gnatL}
9665 Used in conjunction with -gnatG or -gnatD to intersperse original
9666 source lines (as comment lines with line numbers) in the expanded
9667 source output.
9668 @end table
9670 @geindex -gnatm (gcc)
9673 @table @asis
9675 @item @code{-gnatm=@emph{n}}
9677 Limit number of detected error or warning messages to @cite{n}
9678 where @cite{n} is in the range 1..999999. The default setting if
9679 no switch is given is 9999. If the number of warnings reaches this
9680 limit, then a message is output and further warnings are suppressed,
9681 but the compilation is continued. If the number of error messages
9682 reaches this limit, then a message is output and the compilation
9683 is abandoned. The equal sign here is optional. A value of zero
9684 means that no limit applies.
9685 @end table
9687 @geindex -gnatn (gcc)
9690 @table @asis
9692 @item @code{-gnatn[12]}
9694 Activate inlining across modules for subprograms for which pragma @cite{Inline}
9695 is specified. This inlining is performed by the GCC back-end. An optional
9696 digit sets the inlining level: 1 for moderate inlining across modules
9697 or 2 for full inlining across modules. If no inlining level is specified,
9698 the compiler will pick it based on the optimization level.
9699 @end table
9701 @geindex -gnatN (gcc)
9704 @table @asis
9706 @item @code{-gnatN}
9708 Activate front end inlining for subprograms for which
9709 pragma @cite{Inline} is specified. This inlining is performed
9710 by the front end and will be visible in the
9711 @emph{-gnatG} output.
9713 When using a gcc-based back end (in practice this means using any version
9714 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
9715 @emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
9716 Historically front end inlining was more extensive than the gcc back end
9717 inlining, but that is no longer the case.
9718 @end table
9720 @geindex -gnato0 (gcc)
9723 @table @asis
9725 @item @code{-gnato0}
9727 Suppresses overflow checking. This causes the behavior of the compiler to
9728 match the default for older versions where overflow checking was suppressed
9729 by default. This is equivalent to having
9730 @cite{pragma Suppress (Overflow_Mode)} in a configuration pragma file.
9731 @end table
9733 @geindex -gnato?? (gcc)
9736 @table @asis
9738 @item @code{-gnato??}
9740 Set default mode for handling generation of code to avoid intermediate
9741 arithmetic overflow. Here @cite{??} is two digits, a
9742 single digit, or nothing. Each digit is one of the digits @cite{1}
9743 through @cite{3}:
9746 @multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
9747 @item
9749 Digit
9751 @tab
9753 Interpretation
9755 @item
9757 @emph{1}
9759 @tab
9761 All intermediate overflows checked against base type (@cite{STRICT})
9763 @item
9765 @emph{2}
9767 @tab
9769 Minimize intermediate overflows (@cite{MINIMIZED})
9771 @item
9773 @emph{3}
9775 @tab
9777 Eliminate intermediate overflows (@cite{ELIMINATED})
9779 @end multitable
9782 If only one digit appears, then it applies to all
9783 cases; if two digits are given, then the first applies outside
9784 assertions, pre/postconditions, and type invariants, and the second
9785 applies within assertions, pre/postconditions, and type invariants.
9787 If no digits follow the @emph{-gnato}, then it is equivalent to
9788 @emph{-gnato11},
9789 causing all intermediate overflows to be handled in strict
9790 mode.
9792 This switch also causes arithmetic overflow checking to be performed
9793 (as though @cite{pragma Unsuppress (Overflow_Mode)} had been specified).
9795 The default if no option @emph{-gnato} is given is that overflow handling
9796 is in @cite{STRICT} mode (computations done using the base type), and that
9797 overflow checking is enabled.
9799 Note that division by zero is a separate check that is not
9800 controlled by this switch (divide-by-zero checking is on by default).
9802 See also @ref{f8,,Specifying the Desired Mode}.
9803 @end table
9805 @geindex -gnatp (gcc)
9808 @table @asis
9810 @item @code{-gnatp}
9812 Suppress all checks. See @ref{f9,,Run-Time Checks} for details. This switch
9813 has no effect if cancelled by a subsequent @emph{-gnat-p} switch.
9814 @end table
9816 @geindex -gnat-p (gcc)
9819 @table @asis
9821 @item @code{-gnat-p}
9823 Cancel effect of previous @emph{-gnatp} switch.
9824 @end table
9826 @geindex -gnatP (gcc)
9829 @table @asis
9831 @item @code{-gnatP}
9833 Enable polling. This is required on some systems (notably Windows NT) to
9834 obtain asynchronous abort and asynchronous transfer of control capability.
9835 See @cite{Pragma_Polling} in the @cite{GNAT_Reference_Manual} for full
9836 details.
9837 @end table
9839 @geindex -gnatq (gcc)
9842 @table @asis
9844 @item @code{-gnatq}
9846 Don't quit. Try semantics, even if parse errors.
9847 @end table
9849 @geindex -gnatQ (gcc)
9852 @table @asis
9854 @item @code{-gnatQ}
9856 Don't quit. Generate @code{ALI} and tree files even if illegalities.
9857 Note that code generation is still suppressed in the presence of any
9858 errors, so even with @emph{-gnatQ} no object file is generated.
9859 @end table
9861 @geindex -gnatr (gcc)
9864 @table @asis
9866 @item @code{-gnatr}
9868 Treat pragma Restrictions as Restriction_Warnings.
9869 @end table
9871 @geindex -gnatR (gcc)
9874 @table @asis
9876 @item @code{-gnatR[0/1/2/3[s]]}
9878 Output representation information for declared types and objects.
9879 Note that this switch is not allowed if a previous @cite{-gnatD} switch has
9880 been given, since these two switches are not compatible.
9882 @item @code{-gnatRm[s]}
9884 Output convention and parameter passing mechanisms for all subprograms.
9885 @end table
9887 @geindex -gnats (gcc)
9890 @table @asis
9892 @item @code{-gnats}
9894 Syntax check only.
9895 @end table
9897 @geindex -gnatS (gcc)
9900 @table @asis
9902 @item @code{-gnatS}
9904 Print package Standard.
9905 @end table
9907 @geindex -gnatt (gcc)
9910 @table @asis
9912 @item @code{-gnatt}
9914 Generate tree output file.
9915 @end table
9917 @geindex -gnatT (gcc)
9920 @table @asis
9922 @item @code{-gnatT@emph{nnn}}
9924 All compiler tables start at @cite{nnn} times usual starting size.
9925 @end table
9927 @geindex -gnatu (gcc)
9930 @table @asis
9932 @item @code{-gnatu}
9934 List units for this compilation.
9935 @end table
9937 @geindex -gnatU (gcc)
9940 @table @asis
9942 @item @code{-gnatU}
9944 Tag all error messages with the unique string 'error:'
9945 @end table
9947 @geindex -gnatv (gcc)
9950 @table @asis
9952 @item @code{-gnatv}
9954 Verbose mode. Full error output with source lines to @code{stdout}.
9955 @end table
9957 @geindex -gnatV (gcc)
9960 @table @asis
9962 @item @code{-gnatV}
9964 Control level of validity checking (@ref{f6,,Validity Checking}).
9965 @end table
9967 @geindex -gnatw (gcc)
9970 @table @asis
9972 @item @code{-gnatw@emph{xxx}}
9974 Warning mode where
9975 @cite{xxx} is a string of option letters that denotes
9976 the exact warnings that
9977 are enabled or disabled (@ref{fa,,Warning Message Control}).
9978 @end table
9980 @geindex -gnatW (gcc)
9983 @table @asis
9985 @item @code{-gnatW@emph{e}}
9987 Wide character encoding method
9988 (@cite{e}=n/h/u/s/e/8).
9989 @end table
9991 @geindex -gnatx (gcc)
9994 @table @asis
9996 @item @code{-gnatx}
9998 Suppress generation of cross-reference information.
9999 @end table
10001 @geindex -gnatX (gcc)
10004 @table @asis
10006 @item @code{-gnatX}
10008 Enable GNAT implementation extensions and latest Ada version.
10009 @end table
10011 @geindex -gnaty (gcc)
10014 @table @asis
10016 @item @code{-gnaty}
10018 Enable built-in style checks (@ref{fb,,Style Checking}).
10019 @end table
10021 @geindex -gnatz (gcc)
10024 @table @asis
10026 @item @code{-gnatz@emph{m}}
10028 Distribution stub generation and compilation
10029 (@cite{m}=r/c for receiver/caller stubs).
10030 @end table
10032 @geindex -I (gcc)
10035 @table @asis
10037 @item @code{-I@emph{dir}}
10039 @geindex RTL
10041 Direct GNAT to search the @cite{dir} directory for source files needed by
10042 the current compilation
10043 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
10044 @end table
10046 @geindex -I- (gcc)
10049 @table @asis
10051 @item @code{-I-}
10053 @geindex RTL
10055 Except for the source file named in the command line, do not look for source
10056 files in the directory containing the source file named in the command line
10057 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
10058 @end table
10060 @geindex -o (gcc)
10063 @table @asis
10065 @item @code{-o @emph{file}}
10067 This switch is used in @emph{gcc} to redirect the generated object file
10068 and its associated ALI file. Beware of this switch with GNAT, because it may
10069 cause the object file and ALI file to have different names which in turn
10070 may confuse the binder and the linker.
10071 @end table
10073 @geindex -nostdinc (gcc)
10076 @table @asis
10078 @item @code{-nostdinc}
10080 Inhibit the search of the default location for the GNAT Run Time
10081 Library (RTL) source files.
10082 @end table
10084 @geindex -nostdlib (gcc)
10087 @table @asis
10089 @item @code{-nostdlib}
10091 Inhibit the search of the default location for the GNAT Run Time
10092 Library (RTL) ALI files.
10093 @end table
10095 @geindex -O (gcc)
10098 @table @asis
10100 @item @code{-O[@emph{n}]}
10102 @cite{n} controls the optimization level:
10105 @multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
10106 @item
10108 @emph{n}
10110 @tab
10112 Effect
10114 @item
10116 @emph{0}
10118 @tab
10120 No optimization, the default setting if no @emph{-O} appears
10122 @item
10124 @emph{1}
10126 @tab
10128 Normal optimization, the default if you specify @emph{-O} without an
10129 operand. A good compromise between code quality and compilation
10130 time.
10132 @item
10134 @emph{2}
10136 @tab
10138 Extensive optimization, may improve execution time, possibly at
10139 the cost of substantially increased compilation time.
10141 @item
10143 @emph{3}
10145 @tab
10147 Same as @emph{-O2}, and also includes inline expansion for small
10148 subprograms in the same unit.
10150 @item
10152 @emph{s}
10154 @tab
10156 Optimize space usage
10158 @end multitable
10161 See also @ref{fc,,Optimization Levels}.
10162 @end table
10164 @geindex -pass-exit-codes (gcc)
10167 @table @asis
10169 @item @code{-pass-exit-codes}
10171 Catch exit codes from the compiler and use the most meaningful as
10172 exit status.
10173 @end table
10175 @geindex --RTS (gcc)
10178 @table @asis
10180 @item @code{--RTS=@emph{rts-path}}
10182 Specifies the default location of the runtime library. Same meaning as the
10183 equivalent @emph{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
10184 @end table
10186 @geindex -S (gcc)
10189 @table @asis
10191 @item @code{-S}
10193 Used in place of @emph{-c} to
10194 cause the assembler source file to be
10195 generated, using @code{.s} as the extension,
10196 instead of the object file.
10197 This may be useful if you need to examine the generated assembly code.
10198 @end table
10200 @geindex -fverbose-asm (gcc)
10203 @table @asis
10205 @item @code{-fverbose-asm}
10207 Used in conjunction with @emph{-S}
10208 to cause the generated assembly code file to be annotated with variable
10209 names, making it significantly easier to follow.
10210 @end table
10212 @geindex -v (gcc)
10215 @table @asis
10217 @item @code{-v}
10219 Show commands generated by the @emph{gcc} driver. Normally used only for
10220 debugging purposes or if you need to be sure what version of the
10221 compiler you are executing.
10222 @end table
10224 @geindex -V (gcc)
10227 @table @asis
10229 @item @code{-V @emph{ver}}
10231 Execute @cite{ver} version of the compiler. This is the @emph{gcc}
10232 version, not the GNAT version.
10233 @end table
10235 @geindex -w (gcc)
10238 @table @asis
10240 @item @code{-w}
10242 Turn off warnings generated by the back end of the compiler. Use of
10243 this switch also causes the default for front end warnings to be set
10244 to suppress (as though @emph{-gnatws} had appeared at the start of
10245 the options).
10246 @end table
10248 @geindex Combining GNAT switches
10250 You may combine a sequence of GNAT switches into a single switch. For
10251 example, the combined switch
10253 @quotation
10255 @example
10256 -gnatofi3
10257 @end example
10258 @end quotation
10260 is equivalent to specifying the following sequence of switches:
10262 @quotation
10264 @example
10265 -gnato -gnatf -gnati3
10266 @end example
10267 @end quotation
10269 The following restrictions apply to the combination of switches
10270 in this manner:
10273 @itemize *
10275 @item 
10276 The switch @emph{-gnatc} if combined with other switches must come
10277 first in the string.
10279 @item 
10280 The switch @emph{-gnats} if combined with other switches must come
10281 first in the string.
10283 @item 
10284 The switches
10285 @emph{-gnatzc} and @emph{-gnatzr} may not be combined with any other
10286 switches, and only one of them may appear in the command line.
10288 @item 
10289 The switch @emph{-gnat-p} may not be combined with any other switch.
10291 @item 
10292 Once a 'y' appears in the string (that is a use of the @emph{-gnaty}
10293 switch), then all further characters in the switch are interpreted
10294 as style modifiers (see description of @emph{-gnaty}).
10296 @item 
10297 Once a 'd' appears in the string (that is a use of the @emph{-gnatd}
10298 switch), then all further characters in the switch are interpreted
10299 as debug flags (see description of @emph{-gnatd}).
10301 @item 
10302 Once a 'w' appears in the string (that is a use of the @emph{-gnatw}
10303 switch), then all further characters in the switch are interpreted
10304 as warning mode modifiers (see description of @emph{-gnatw}).
10306 @item 
10307 Once a 'V' appears in the string (that is a use of the @emph{-gnatV}
10308 switch), then all further characters in the switch are interpreted
10309 as validity checking options (@ref{f6,,Validity Checking}).
10311 @item 
10312 Option 'em', 'ec', 'ep', 'l=' and 'R' must be the last options in
10313 a combined list of options.
10314 @end itemize
10316 @node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10317 @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}
10318 @subsection Output and Error Message Control
10321 @geindex stderr
10323 The standard default format for error messages is called 'brief format'.
10324 Brief format messages are written to @code{stderr} (the standard error
10325 file) and have the following form:
10327 @example
10328 e.adb:3:04: Incorrect spelling of keyword "function"
10329 e.adb:4:20: ";" should be "is"
10330 @end example
10332 The first integer after the file name is the line number in the file,
10333 and the second integer is the column number within the line.
10334 @cite{GPS} can parse the error messages
10335 and point to the referenced character.
10336 The following switches provide control over the error message
10337 format:
10339 @geindex -gnatv (gcc)
10342 @table @asis
10344 @item @code{-gnatv}
10346 The @cite{v} stands for verbose.
10347 The effect of this setting is to write long-format error
10348 messages to @code{stdout} (the standard output file.
10349 The same program compiled with the
10350 @emph{-gnatv} switch would generate:
10352 @example
10353 3. funcion X (Q : Integer)
10354    |
10355 >>> Incorrect spelling of keyword "function"
10356 4. return Integer;
10357                  |
10358 >>> ";" should be "is"
10359 @end example
10361 The vertical bar indicates the location of the error, and the @code{>>>}
10362 prefix can be used to search for error messages. When this switch is
10363 used the only source lines output are those with errors.
10364 @end table
10366 @geindex -gnatl (gcc)
10369 @table @asis
10371 @item @code{-gnatl}
10373 The @cite{l} stands for list.
10374 This switch causes a full listing of
10375 the file to be generated. In the case where a body is
10376 compiled, the corresponding spec is also listed, along
10377 with any subunits. Typical output from compiling a package
10378 body @code{p.adb} might look like:
10380 @example
10381 Compiling: p.adb
10383      1. package body p is
10384      2.    procedure a;
10385      3.    procedure a is separate;
10386      4. begin
10387      5.    null
10388                |
10389         >>> missing ";"
10391      6. end;
10393 Compiling: p.ads
10395      1. package p is
10396      2.    pragma Elaborate_Body
10397                                 |
10398         >>> missing ";"
10400      3. end p;
10402 Compiling: p-a.adb
10404      1. separate p
10405                 |
10406         >>> missing "("
10408      2. procedure a is
10409      3. begin
10410      4.    null
10411                |
10412         >>> missing ";"
10414      5. end;
10415 @end example
10417 When you specify the @emph{-gnatv} or @emph{-gnatl} switches and
10418 standard output is redirected, a brief summary is written to
10419 @code{stderr} (standard error) giving the number of error messages and
10420 warning messages generated.
10421 @end table
10423 @geindex -gnatl=fname (gcc)
10426 @table @asis
10428 @item @code{-gnatl=@emph{fname}}
10430 This has the same effect as @emph{-gnatl} except that the output is
10431 written to a file instead of to standard output. If the given name
10432 @code{fname} does not start with a period, then it is the full name
10433 of the file to be written. If @code{fname} is an extension, it is
10434 appended to the name of the file being compiled. For example, if
10435 file @code{xyz.adb} is compiled with @emph{-gnatl=.lst},
10436 then the output is written to file xyz.adb.lst.
10437 @end table
10439 @geindex -gnatU (gcc)
10442 @table @asis
10444 @item @code{-gnatU}
10446 This switch forces all error messages to be preceded by the unique
10447 string 'error:'. This means that error messages take a few more
10448 characters in space, but allows easy searching for and identification
10449 of error messages.
10450 @end table
10452 @geindex -gnatb (gcc)
10455 @table @asis
10457 @item @code{-gnatb}
10459 The @cite{b} stands for brief.
10460 This switch causes GNAT to generate the
10461 brief format error messages to @code{stderr} (the standard error
10462 file) as well as the verbose
10463 format message or full listing (which as usual is written to
10464 @code{stdout} (the standard output file).
10465 @end table
10467 @geindex -gnatm (gcc)
10470 @table @asis
10472 @item @code{-gnatm=@emph{n}}
10474 The @cite{m} stands for maximum.
10475 @cite{n} is a decimal integer in the
10476 range of 1 to 999999 and limits the number of error or warning
10477 messages to be generated. For example, using
10478 @emph{-gnatm2} might yield
10480 @example
10481 e.adb:3:04: Incorrect spelling of keyword "function"
10482 e.adb:5:35: missing ".."
10483 fatal error: maximum number of errors detected
10484 compilation abandoned
10485 @end example
10487 The default setting if
10488 no switch is given is 9999. If the number of warnings reaches this
10489 limit, then a message is output and further warnings are suppressed,
10490 but the compilation is continued. If the number of error messages
10491 reaches this limit, then a message is output and the compilation
10492 is abandoned. A value of zero means that no limit applies.
10494 Note that the equal sign is optional, so the switches
10495 @emph{-gnatm2} and @emph{-gnatm=2} are equivalent.
10496 @end table
10498 @geindex -gnatf (gcc)
10501 @table @asis
10503 @item @code{-gnatf}
10505 @geindex Error messages
10506 @geindex suppressing
10508 The @cite{f} stands for full.
10509 Normally, the compiler suppresses error messages that are likely to be
10510 redundant. This switch causes all error
10511 messages to be generated. In particular, in the case of
10512 references to undefined variables. If a given variable is referenced
10513 several times, the normal format of messages is
10515 @example
10516 e.adb:7:07: "V" is undefined (more references follow)
10517 @end example
10519 where the parenthetical comment warns that there are additional
10520 references to the variable @cite{V}. Compiling the same program with the
10521 @emph{-gnatf} switch yields
10523 @example
10524 e.adb:7:07: "V" is undefined
10525 e.adb:8:07: "V" is undefined
10526 e.adb:8:12: "V" is undefined
10527 e.adb:8:16: "V" is undefined
10528 e.adb:9:07: "V" is undefined
10529 e.adb:9:12: "V" is undefined
10530 @end example
10532 The @emph{-gnatf} switch also generates additional information for
10533 some error messages.  Some examples are:
10536 @itemize *
10538 @item 
10539 Details on possibly non-portable unchecked conversion
10541 @item 
10542 List possible interpretations for ambiguous calls
10544 @item 
10545 Additional details on incorrect parameters
10546 @end itemize
10547 @end table
10549 @geindex -gnatjnn (gcc)
10552 @table @asis
10554 @item @code{-gnatjnn}
10556 In normal operation mode (or if @emph{-gnatj0} is used), then error messages
10557 with continuation lines are treated as though the continuation lines were
10558 separate messages (and so a warning with two continuation lines counts as
10559 three warnings, and is listed as three separate messages).
10561 If the @emph{-gnatjnn} switch is used with a positive value for nn, then
10562 messages are output in a different manner. A message and all its continuation
10563 lines are treated as a unit, and count as only one warning or message in the
10564 statistics totals. Furthermore, the message is reformatted so that no line
10565 is longer than nn characters.
10566 @end table
10568 @geindex -gnatq (gcc)
10571 @table @asis
10573 @item @code{-gnatq}
10575 The @cite{q} stands for quit (really 'don't quit').
10576 In normal operation mode, the compiler first parses the program and
10577 determines if there are any syntax errors. If there are, appropriate
10578 error messages are generated and compilation is immediately terminated.
10579 This switch tells
10580 GNAT to continue with semantic analysis even if syntax errors have been
10581 found. This may enable the detection of more errors in a single run. On
10582 the other hand, the semantic analyzer is more likely to encounter some
10583 internal fatal error when given a syntactically invalid tree.
10584 @end table
10586 @geindex -gnatQ (gcc)
10589 @table @asis
10591 @item @code{-gnatQ}
10593 In normal operation mode, the @code{ALI} file is not generated if any
10594 illegalities are detected in the program. The use of @emph{-gnatQ} forces
10595 generation of the @code{ALI} file. This file is marked as being in
10596 error, so it cannot be used for binding purposes, but it does contain
10597 reasonably complete cross-reference information, and thus may be useful
10598 for use by tools (e.g., semantic browsing tools or integrated development
10599 environments) that are driven from the @code{ALI} file. This switch
10600 implies @emph{-gnatq}, since the semantic phase must be run to get a
10601 meaningful ALI file.
10603 In addition, if @emph{-gnatt} is also specified, then the tree file is
10604 generated even if there are illegalities. It may be useful in this case
10605 to also specify @emph{-gnatq} to ensure that full semantic processing
10606 occurs. The resulting tree file can be processed by ASIS, for the purpose
10607 of providing partial information about illegal units, but if the error
10608 causes the tree to be badly malformed, then ASIS may crash during the
10609 analysis.
10611 When @emph{-gnatQ} is used and the generated @code{ALI} file is marked as
10612 being in error, @emph{gnatmake} will attempt to recompile the source when it
10613 finds such an @code{ALI} file, including with switch @emph{-gnatc}.
10615 Note that @emph{-gnatQ} has no effect if @emph{-gnats} is specified,
10616 since ALI files are never generated if @emph{-gnats} is set.
10617 @end table
10619 @node Warning Message Control,Debugging and Assertion Control,Output and Error Message Control,Compiler Switches
10620 @anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{fa}@anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{ff}
10621 @subsection Warning Message Control
10624 @geindex Warning messages
10626 In addition to error messages, which correspond to illegalities as defined
10627 in the Ada Reference Manual, the compiler detects two kinds of warning
10628 situations.
10630 First, the compiler considers some constructs suspicious and generates a
10631 warning message to alert you to a possible error. Second, if the
10632 compiler detects a situation that is sure to raise an exception at
10633 run time, it generates a warning message. The following shows an example
10634 of warning messages:
10636 @example
10637 e.adb:4:24: warning: creation of object may raise Storage_Error
10638 e.adb:10:17: warning: static value out of range
10639 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10640 @end example
10642 GNAT considers a large number of situations as appropriate
10643 for the generation of warning messages. As always, warnings are not
10644 definite indications of errors. For example, if you do an out-of-range
10645 assignment with the deliberate intention of raising a
10646 @cite{Constraint_Error} exception, then the warning that may be
10647 issued does not indicate an error. Some of the situations for which GNAT
10648 issues warnings (at least some of the time) are given in the following
10649 list. This list is not complete, and new warnings are often added to
10650 subsequent versions of GNAT. The list is intended to give a general idea
10651 of the kinds of warnings that are generated.
10654 @itemize *
10656 @item 
10657 Possible infinitely recursive calls
10659 @item 
10660 Out-of-range values being assigned
10662 @item 
10663 Possible order of elaboration problems
10665 @item 
10666 Size not a multiple of alignment for a record type
10668 @item 
10669 Assertions (pragma Assert) that are sure to fail
10671 @item 
10672 Unreachable code
10674 @item 
10675 Address clauses with possibly unaligned values, or where an attempt is
10676 made to overlay a smaller variable with a larger one.
10678 @item 
10679 Fixed-point type declarations with a null range
10681 @item 
10682 Direct_IO or Sequential_IO instantiated with a type that has access values
10684 @item 
10685 Variables that are never assigned a value
10687 @item 
10688 Variables that are referenced before being initialized
10690 @item 
10691 Task entries with no corresponding @cite{accept} statement
10693 @item 
10694 Duplicate accepts for the same task entry in a @cite{select}
10696 @item 
10697 Objects that take too much storage
10699 @item 
10700 Unchecked conversion between types of differing sizes
10702 @item 
10703 Missing @cite{return} statement along some execution path in a function
10705 @item 
10706 Incorrect (unrecognized) pragmas
10708 @item 
10709 Incorrect external names
10711 @item 
10712 Allocation from empty storage pool
10714 @item 
10715 Potentially blocking operation in protected type
10717 @item 
10718 Suspicious parenthesization of expressions
10720 @item 
10721 Mismatching bounds in an aggregate
10723 @item 
10724 Attempt to return local value by reference
10726 @item 
10727 Premature instantiation of a generic body
10729 @item 
10730 Attempt to pack aliased components
10732 @item 
10733 Out of bounds array subscripts
10735 @item 
10736 Wrong length on string assignment
10738 @item 
10739 Violations of style rules if style checking is enabled
10741 @item 
10742 Unused @emph{with} clauses
10744 @item 
10745 @cite{Bit_Order} usage that does not have any effect
10747 @item 
10748 @cite{Standard.Duration} used to resolve universal fixed expression
10750 @item 
10751 Dereference of possibly null value
10753 @item 
10754 Declaration that is likely to cause storage error
10756 @item 
10757 Internal GNAT unit @emph{with}ed by application unit
10759 @item 
10760 Values known to be out of range at compile time
10762 @item 
10763 Unreferenced or unmodified variables. Note that a special
10764 exemption applies to variables which contain any of the substrings
10765 @cite{DISCARD@comma{} DUMMY@comma{} IGNORE@comma{} JUNK@comma{} UNUSED}, in any casing. Such variables
10766 are considered likely to be intentionally used in a situation where
10767 otherwise a warning would be given, so warnings of this kind are
10768 always suppressed for such variables.
10770 @item 
10771 Address overlays that could clobber memory
10773 @item 
10774 Unexpected initialization when address clause present
10776 @item 
10777 Bad alignment for address clause
10779 @item 
10780 Useless type conversions
10782 @item 
10783 Redundant assignment statements and other redundant constructs
10785 @item 
10786 Useless exception handlers
10788 @item 
10789 Accidental hiding of name by child unit
10791 @item 
10792 Access before elaboration detected at compile time
10794 @item 
10795 A range in a @cite{for} loop that is known to be null or might be null
10796 @end itemize
10798 The following section lists compiler switches that are available
10799 to control the handling of warning messages. It is also possible
10800 to exercise much finer control over what warnings are issued and
10801 suppressed using the GNAT pragma Warnings (see the description
10802 of the pragma in the @cite{GNAT_Reference_manual}).
10804 @geindex -gnatwa (gcc)
10807 @table @asis
10809 @item @code{-gnatwa}
10811 @emph{Activate most optional warnings.}
10813 This switch activates most optional warning messages.  See the remaining list
10814 in this section for details on optional warning messages that can be
10815 individually controlled.  The warnings that are not turned on by this
10816 switch are:
10819 @itemize *
10821 @item 
10822 @code{-gnatwd} (implicit dereferencing)
10824 @item 
10825 @code{-gnatw.d} (tag warnings with -gnatw switch)
10827 @item 
10828 @code{-gnatwh} (hiding)
10830 @item 
10831 @code{-gnatw.h} (holes in record layouts)
10833 @item 
10834 @code{-gnatw.j} (late primitives of tagged types)
10836 @item 
10837 @code{-gnatw.k} (redefinition of names in standard)
10839 @item 
10840 @code{-gnatwl} (elaboration warnings)
10842 @item 
10843 @code{-gnatw.l} (inherited aspects)
10845 @item 
10846 @code{-gnatw.n} (atomic synchronization)
10848 @item 
10849 @code{-gnatwo} (address clause overlay)
10851 @item 
10852 @code{-gnatw.o} (values set by out parameters ignored)
10854 @item 
10855 @code{-gnatw.s} (overridden size clause)
10857 @item 
10858 @code{-gnatwt} (tracking of deleted conditional code)
10860 @item 
10861 @code{-gnatw.u} (unordered enumeration)
10863 @item 
10864 @code{-gnatw.w} (use of Warnings Off)
10866 @item 
10867 @code{-gnatw.y} (reasons for package needing body)
10868 @end itemize
10870 All other optional warnings are turned on.
10871 @end table
10873 @geindex -gnatwA (gcc)
10876 @table @asis
10878 @item @code{-gnatwA}
10880 @emph{Suppress all optional errors.}
10882 This switch suppresses all optional warning messages, see remaining list
10883 in this section for details on optional warning messages that can be
10884 individually controlled. Note that unlike switch @emph{-gnatws}, the
10885 use of switch @emph{-gnatwA} does not suppress warnings that are
10886 normally given unconditionally and cannot be individually controlled
10887 (for example, the warning about a missing exit path in a function).
10888 Also, again unlike switch @emph{-gnatws}, warnings suppressed by
10889 the use of switch @emph{-gnatwA} can be individually turned back
10890 on. For example the use of switch @emph{-gnatwA} followed by
10891 switch @emph{-gnatwd} will suppress all optional warnings except
10892 the warnings for implicit dereferencing.
10893 @end table
10895 @geindex -gnatw.a (gcc)
10898 @table @asis
10900 @item @code{-gnatw.a}
10902 @emph{Activate warnings on failing assertions.}
10904 @geindex Assert failures
10906 This switch activates warnings for assertions where the compiler can tell at
10907 compile time that the assertion will fail. Note that this warning is given
10908 even if assertions are disabled. The default is that such warnings are
10909 generated.
10910 @end table
10912 @geindex -gnatw.A (gcc)
10915 @table @asis
10917 @item @code{-gnatw.A}
10919 @emph{Suppress warnings on failing assertions.}
10921 @geindex Assert failures
10923 This switch suppresses warnings for assertions where the compiler can tell at
10924 compile time that the assertion will fail.
10925 @end table
10927 @geindex -gnatwb (gcc)
10930 @table @asis
10932 @item @code{-gnatwb}
10934 @emph{Activate warnings on bad fixed values.}
10936 @geindex Bad fixed values
10938 @geindex Fixed-point Small value
10940 @geindex Small value
10942 This switch activates warnings for static fixed-point expressions whose
10943 value is not an exact multiple of Small. Such values are implementation
10944 dependent, since an implementation is free to choose either of the multiples
10945 that surround the value. GNAT always chooses the closer one, but this is not
10946 required behavior, and it is better to specify a value that is an exact
10947 multiple, ensuring predictable execution. The default is that such warnings
10948 are not generated.
10949 @end table
10951 @geindex -gnatwB (gcc)
10954 @table @asis
10956 @item @code{-gnatwB}
10958 @emph{Suppress warnings on bad fixed values.}
10960 This switch suppresses warnings for static fixed-point expressions whose
10961 value is not an exact multiple of Small.
10962 @end table
10964 @geindex -gnatw.b (gcc)
10967 @table @asis
10969 @item @code{-gnatw.b}
10971 @emph{Activate warnings on biased representation.}
10973 @geindex Biased representation
10975 This switch activates warnings when a size clause, value size clause, component
10976 clause, or component size clause forces the use of biased representation for an
10977 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
10978 to represent 10/11). The default is that such warnings are generated.
10979 @end table
10981 @geindex -gnatwB (gcc)
10984 @table @asis
10986 @item @code{-gnatw.B}
10988 @emph{Suppress warnings on biased representation.}
10990 This switch suppresses warnings for representation clauses that force the use
10991 of biased representation.
10992 @end table
10994 @geindex -gnatwc (gcc)
10997 @table @asis
10999 @item @code{-gnatwc}
11001 @emph{Activate warnings on conditionals.}
11003 @geindex Conditionals
11004 @geindex constant
11006 This switch activates warnings for conditional expressions used in
11007 tests that are known to be True or False at compile time. The default
11008 is that such warnings are not generated.
11009 Note that this warning does
11010 not get issued for the use of boolean variables or constants whose
11011 values are known at compile time, since this is a standard technique
11012 for conditional compilation in Ada, and this would generate too many
11013 false positive warnings.
11015 This warning option also activates a special test for comparisons using
11016 the operators '>=' and' <='.
11017 If the compiler can tell that only the equality condition is possible,
11018 then it will warn that the '>' or '<' part of the test
11019 is useless and that the operator could be replaced by '='.
11020 An example would be comparing a @cite{Natural} variable <= 0.
11022 This warning option also generates warnings if
11023 one or both tests is optimized away in a membership test for integer
11024 values if the result can be determined at compile time. Range tests on
11025 enumeration types are not included, since it is common for such tests
11026 to include an end point.
11028 This warning can also be turned on using @emph{-gnatwa}.
11029 @end table
11031 @geindex -gnatwC (gcc)
11034 @table @asis
11036 @item @code{-gnatwC}
11038 @emph{Suppress warnings on conditionals.}
11040 This switch suppresses warnings for conditional expressions used in
11041 tests that are known to be True or False at compile time.
11042 @end table
11044 @geindex -gnatw.c (gcc)
11047 @table @asis
11049 @item @code{-gnatw.c}
11051 @emph{Activate warnings on missing component clauses.}
11053 @geindex Component clause
11054 @geindex missing
11056 This switch activates warnings for record components where a record
11057 representation clause is present and has component clauses for the
11058 majority, but not all, of the components. A warning is given for each
11059 component for which no component clause is present.
11060 @end table
11062 @geindex -gnatwC (gcc)
11065 @table @asis
11067 @item @code{-gnatw.C}
11069 @emph{Suppress warnings on missing component clauses.}
11071 This switch suppresses warnings for record components that are
11072 missing a component clause in the situation described above.
11073 @end table
11075 @geindex -gnatwd (gcc)
11078 @table @asis
11080 @item @code{-gnatwd}
11082 @emph{Activate warnings on implicit dereferencing.}
11084 If this switch is set, then the use of a prefix of an access type
11085 in an indexed component, slice, or selected component without an
11086 explicit @cite{.all} will generate a warning. With this warning
11087 enabled, access checks occur only at points where an explicit
11088 @cite{.all} appears in the source code (assuming no warnings are
11089 generated as a result of this switch). The default is that such
11090 warnings are not generated.
11091 @end table
11093 @geindex -gnatwD (gcc)
11096 @table @asis
11098 @item @code{-gnatwD}
11100 @emph{Suppress warnings on implicit dereferencing.}
11102 @geindex Implicit dereferencing
11104 @geindex Dereferencing
11105 @geindex implicit
11107 This switch suppresses warnings for implicit dereferences in
11108 indexed components, slices, and selected components.
11109 @end table
11111 @geindex -gnatw.d (gcc)
11114 @table @asis
11116 @item @code{-gnatw.d}
11118 @emph{Activate tagging of warning and info messages.}
11120 If this switch is set, then warning messages are tagged, with one of the
11121 following strings:
11123 @quotation
11126 @itemize -
11128 @item 
11129 @emph{[-gnatw?]}
11130 Used to tag warnings controlled by the switch @emph{-gnatwx} where x
11131 is a letter a-z.
11133 @item 
11134 @emph{[-gnatw.?]}
11135 Used to tag warnings controlled by the switch @emph{-gnatw.x} where x
11136 is a letter a-z.
11138 @item 
11139 @emph{[-gnatel]}
11140 Used to tag elaboration information (info) messages generated when the
11141 static model of elaboration is used and the @emph{-gnatel} switch is set.
11143 @item 
11144 @emph{[restriction warning]}
11145 Used to tag warning messages for restriction violations, activated by use
11146 of the pragma @emph{Restriction_Warnings}.
11148 @item 
11149 @emph{[warning-as-error]}
11150 Used to tag warning messages that have been converted to error messages by
11151 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
11152 the string "error: " rather than "warning: ".
11154 @item 
11155 @emph{[enabled by default]}
11156 Used to tag all other warnings that are always given by default, unless
11157 warnings are completely suppressed using pragma @emph{Warnings(Off)} or
11158 the switch @emph{-gnatws}.
11159 @end itemize
11160 @end quotation
11161 @end table
11163 @geindex -gnatw.d (gcc)
11166 @table @asis
11168 @item @code{-gnatw.D}
11170 @emph{Deactivate tagging of warning and info messages messages.}
11172 If this switch is set, then warning messages return to the default
11173 mode in which warnings and info messages are not tagged as described above for
11174 @cite{-gnatw.d}.
11175 @end table
11177 @geindex -gnatwe (gcc)
11179 @geindex Warnings
11180 @geindex treat as error
11183 @table @asis
11185 @item @code{-gnatwe}
11187 @emph{Treat warnings and style checks as errors.}
11189 This switch causes warning messages and style check messages to be
11190 treated as errors.
11191 The warning string still appears, but the warning messages are counted
11192 as errors, and prevent the generation of an object file. Note that this
11193 is the only -gnatw switch that affects the handling of style check messages.
11194 Note also that this switch has no effect on info (information) messages, which
11195 are not treated as errors if this switch is present.
11196 @end table
11198 @geindex -gnatw.e (gcc)
11201 @table @asis
11203 @item @code{-gnatw.e}
11205 @emph{Activate every optional warning.}
11207 @geindex Warnings
11208 @geindex activate every optional warning
11210 This switch activates all optional warnings, including those which
11211 are not activated by @cite{-gnatwa}. The use of this switch is not
11212 recommended for normal use. If you turn this switch on, it is almost
11213 certain that you will get large numbers of useless warnings. The
11214 warnings that are excluded from @cite{-gnatwa} are typically highly
11215 specialized warnings that are suitable for use only in code that has
11216 been specifically designed according to specialized coding rules.
11217 @end table
11219 @geindex -gnatwf (gcc)
11222 @table @asis
11224 @item @code{-gnatwf}
11226 @emph{Activate warnings on unreferenced formals.}
11228 @geindex Formals
11229 @geindex unreferenced
11231 This switch causes a warning to be generated if a formal parameter
11232 is not referenced in the body of the subprogram. This warning can
11233 also be turned on using @emph{-gnatwu}. The
11234 default is that these warnings are not generated.
11235 @end table
11237 @geindex -gnatwF (gcc)
11240 @table @asis
11242 @item @code{-gnatwF}
11244 @emph{Suppress warnings on unreferenced formals.}
11246 This switch suppresses warnings for unreferenced formal
11247 parameters. Note that the
11248 combination @emph{-gnatwu} followed by @emph{-gnatwF} has the
11249 effect of warning on unreferenced entities other than subprogram
11250 formals.
11251 @end table
11253 @geindex -gnatwg (gcc)
11256 @table @asis
11258 @item @code{-gnatwg}
11260 @emph{Activate warnings on unrecognized pragmas.}
11262 @geindex Pragmas
11263 @geindex unrecognized
11265 This switch causes a warning to be generated if an unrecognized
11266 pragma is encountered. Apart from issuing this warning, the
11267 pragma is ignored and has no effect. The default
11268 is that such warnings are issued (satisfying the Ada Reference
11269 Manual requirement that such warnings appear).
11270 @end table
11272 @geindex -gnatwG (gcc)
11275 @table @asis
11277 @item @code{-gnatwG}
11279 @emph{Suppress warnings on unrecognized pragmas.}
11281 This switch suppresses warnings for unrecognized pragmas.
11282 @end table
11284 @geindex -gnatw.g (gcc)
11287 @table @asis
11289 @item @code{-gnatw.g}
11291 @emph{Warnings used for GNAT sources.}
11293 This switch sets the warning categories that are used by the standard
11294 GNAT style. Currently this is equivalent to
11295 @emph{-gnatwAao.sI.C.V.X}
11296 but more warnings may be added in the future without advanced notice.
11297 @end table
11299 @geindex -gnatwh (gcc)
11302 @table @asis
11304 @item @code{-gnatwh}
11306 @emph{Activate warnings on hiding.}
11308 @geindex Hiding of Declarations
11310 This switch activates warnings on hiding declarations that are considered
11311 potentially confusing. Not all cases of hiding cause warnings; for example an
11312 overriding declaration hides an implicit declaration, which is just normal
11313 code. The default is that warnings on hiding are not generated.
11314 @end table
11316 @geindex -gnatwH (gcc)
11319 @table @asis
11321 @item @code{-gnatwH}
11323 @emph{Suppress warnings on hiding.}
11325 This switch suppresses warnings on hiding declarations.
11326 @end table
11328 @geindex -gnatw.h (gcc)
11331 @table @asis
11333 @item @code{-gnatw.h}
11335 @emph{Activate warnings on holes/gaps in records.}
11337 @geindex Record Representation (gaps)
11339 This switch activates warnings on component clauses in record
11340 representation clauses that leave holes (gaps) in the record layout.
11341 If this warning option is active, then record representation clauses
11342 should specify a contiguous layout, adding unused fill fields if needed.
11343 @end table
11345 @geindex -gnatw.H (gcc)
11348 @table @asis
11350 @item @code{-gnatw.H}
11352 @emph{Suppress warnings on holes/gaps in records.}
11354 This switch suppresses warnings on component clauses in record
11355 representation clauses that leave holes (haps) in the record layout.
11356 @end table
11358 @geindex -gnatwi (gcc)
11361 @table @asis
11363 @item @code{-gnatwi}
11365 @emph{Activate warnings on implementation units.}
11367 This switch activates warnings for a @emph{with} of an internal GNAT
11368 implementation unit, defined as any unit from the @cite{Ada},
11369 @cite{Interfaces}, @cite{GNAT},
11370 or @cite{System}
11371 hierarchies that is not
11372 documented in either the Ada Reference Manual or the GNAT
11373 Programmer's Reference Manual. Such units are intended only
11374 for internal implementation purposes and should not be @emph{with}ed
11375 by user programs. The default is that such warnings are generated
11376 @end table
11378 @geindex -gnatwI (gcc)
11381 @table @asis
11383 @item @code{-gnatwI}
11385 @emph{Disable warnings on implementation units.}
11387 This switch disables warnings for a @emph{with} of an internal GNAT
11388 implementation unit.
11389 @end table
11391 @geindex -gnatw.i (gcc)
11394 @table @asis
11396 @item @code{-gnatw.i}
11398 @emph{Activate warnings on overlapping actuals.}
11400 This switch enables a warning on statically detectable overlapping actuals in
11401 a subprogram call, when one of the actuals is an in-out parameter, and the
11402 types of the actuals are not by-copy types. This warning is off by default.
11403 @end table
11405 @geindex -gnatw.I (gcc)
11408 @table @asis
11410 @item @code{-gnatw.I}
11412 @emph{Disable warnings on overlapping actuals.}
11414 This switch disables warnings on overlapping actuals in a call..
11415 @end table
11417 @geindex -gnatwj (gcc)
11420 @table @asis
11422 @item @code{-gnatwj}
11424 @emph{Activate warnings on obsolescent features (Annex J).}
11426 @geindex Features
11427 @geindex obsolescent
11429 @geindex Obsolescent features
11431 If this warning option is activated, then warnings are generated for
11432 calls to subprograms marked with @cite{pragma Obsolescent} and
11433 for use of features in Annex J of the Ada Reference Manual. In the
11434 case of Annex J, not all features are flagged. In particular use
11435 of the renamed packages (like @cite{Text_IO}) and use of package
11436 @cite{ASCII} are not flagged, since these are very common and
11437 would generate many annoying positive warnings. The default is that
11438 such warnings are not generated.
11440 In addition to the above cases, warnings are also generated for
11441 GNAT features that have been provided in past versions but which
11442 have been superseded (typically by features in the new Ada standard).
11443 For example, @cite{pragma Ravenscar} will be flagged since its
11444 function is replaced by @cite{pragma Profile(Ravenscar)}, and
11445 @cite{pragma Interface_Name} will be flagged since its function
11446 is replaced by @cite{pragma Import}.
11448 Note that this warning option functions differently from the
11449 restriction @cite{No_Obsolescent_Features} in two respects.
11450 First, the restriction applies only to annex J features.
11451 Second, the restriction does flag uses of package @cite{ASCII}.
11452 @end table
11454 @geindex -gnatwJ (gcc)
11457 @table @asis
11459 @item @code{-gnatwJ}
11461 @emph{Suppress warnings on obsolescent features (Annex J).}
11463 This switch disables warnings on use of obsolescent features.
11464 @end table
11466 @geindex -gnatw.j (gcc)
11469 @table @asis
11471 @item @code{-gnatw.j}
11473 @emph{Activate warnings on late declarations of tagged type primitives.}
11475 This switch activates warnings on visible primitives added to a
11476 tagged type after deriving a private extension from it.
11477 @end table
11479 @geindex -gnatw.J (gcc)
11482 @table @asis
11484 @item @code{-gnatw.J}
11486 @emph{Suppress warnings on late declarations of tagged type primitives.}
11488 This switch suppresses warnings on visible primitives added to a
11489 tagged type after deriving a private extension from it.
11490 @end table
11492 @geindex -gnatwk (gcc)
11495 @table @asis
11497 @item @code{-gnatwk}
11499 @emph{Activate warnings on variables that could be constants.}
11501 This switch activates warnings for variables that are initialized but
11502 never modified, and then could be declared constants. The default is that
11503 such warnings are not given.
11504 @end table
11506 @geindex -gnatwK (gcc)
11509 @table @asis
11511 @item @code{-gnatwK}
11513 @emph{Suppress warnings on variables that could be constants.}
11515 This switch disables warnings on variables that could be declared constants.
11516 @end table
11518 @geindex -gnatw.k (gcc)
11521 @table @asis
11523 @item @code{-gnatw.k}
11525 @emph{Activate warnings on redefinition of names in standard.}
11527 This switch activates warnings for declarations that declare a name that
11528 is defined in package Standard. Such declarations can be confusing,
11529 especially since the names in package Standard continue to be directly
11530 visible, meaning that use visibiliy on such redeclared names does not
11531 work as expected. Names of discriminants and components in records are
11532 not included in this check.
11533 @end table
11535 @geindex -gnatwK (gcc)
11538 @table @asis
11540 @item @code{-gnatw.K}
11542 @emph{Suppress warnings on redefinition of names in standard.}
11544 This switch activates warnings for declarations that declare a name that
11545 is defined in package Standard.
11546 @end table
11548 @geindex -gnatwl (gcc)
11551 @table @asis
11553 @item @code{-gnatwl}
11555 @emph{Activate warnings for elaboration pragmas.}
11557 @geindex Elaboration
11558 @geindex warnings
11560 This switch activates warnings for possible elaboration problems,
11561 including suspicious use
11562 of @cite{Elaborate} pragmas, when using the static elaboration model, and
11563 possible situations that may raise @cite{Program_Error} when using the
11564 dynamic elaboration model.
11565 See the section in this guide on elaboration checking for further details.
11566 The default is that such warnings
11567 are not generated.
11568 @end table
11570 @geindex -gnatwL (gcc)
11573 @table @asis
11575 @item @code{-gnatwL}
11577 @emph{Suppress warnings for elaboration pragmas.}
11579 This switch suppresses warnings for possible elaboration problems.
11580 @end table
11582 @geindex -gnatw.l (gcc)
11585 @table @asis
11587 @item @code{-gnatw.l}
11589 @emph{List inherited aspects.}
11591 This switch causes the compiler to list inherited invariants,
11592 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
11593 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
11594 @end table
11596 @geindex -gnatw.L (gcc)
11599 @table @asis
11601 @item @code{-gnatw.L}
11603 @emph{Suppress listing of inherited aspects.}
11605 This switch suppresses listing of inherited aspects.
11606 @end table
11608 @geindex -gnatwm (gcc)
11611 @table @asis
11613 @item @code{-gnatwm}
11615 @emph{Activate warnings on modified but unreferenced variables.}
11617 This switch activates warnings for variables that are assigned (using
11618 an initialization value or with one or more assignment statements) but
11619 whose value is never read. The warning is suppressed for volatile
11620 variables and also for variables that are renamings of other variables
11621 or for which an address clause is given.
11622 The default is that these warnings are not given.
11623 @end table
11625 @geindex -gnatwM (gcc)
11628 @table @asis
11630 @item @code{-gnatwM}
11632 @emph{Disable warnings on modified but unreferenced variables.}
11634 This switch disables warnings for variables that are assigned or
11635 initialized, but never read.
11636 @end table
11638 @geindex -gnatw.m (gcc)
11641 @table @asis
11643 @item @code{-gnatw.m}
11645 @emph{Activate warnings on suspicious modulus values.}
11647 This switch activates warnings for modulus values that seem suspicious.
11648 The cases caught are where the size is the same as the modulus (e.g.
11649 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11650 with no size clause. The guess in both cases is that 2**x was intended
11651 rather than x. In addition expressions of the form 2*x for small x
11652 generate a warning (the almost certainly accurate guess being that
11653 2**x was intended). The default is that these warnings are given.
11654 @end table
11656 @geindex -gnatw.M (gcc)
11659 @table @asis
11661 @item @code{-gnatw.M}
11663 @emph{Disable warnings on suspicious modulus values.}
11665 This switch disables warnings for suspicious modulus values.
11666 @end table
11668 @geindex -gnatwn (gcc)
11671 @table @asis
11673 @item @code{-gnatwn}
11675 @emph{Set normal warnings mode.}
11677 This switch sets normal warning mode, in which enabled warnings are
11678 issued and treated as warnings rather than errors. This is the default
11679 mode. the switch @emph{-gnatwn} can be used to cancel the effect of
11680 an explicit @emph{-gnatws} or
11681 @emph{-gnatwe}. It also cancels the effect of the
11682 implicit @emph{-gnatwe} that is activated by the
11683 use of @emph{-gnatg}.
11684 @end table
11686 @geindex -gnatw.n (gcc)
11688 @geindex Atomic Synchronization
11689 @geindex warnings
11692 @table @asis
11694 @item @code{-gnatw.n}
11696 @emph{Activate warnings on atomic synchronization.}
11698 This switch actives warnings when an access to an atomic variable
11699 requires the generation of atomic synchronization code. These
11700 warnings are off by default.
11701 @end table
11703 @geindex -gnatw.N (gcc)
11706 @table @asis
11708 @item @code{-gnatw.N}
11710 @emph{Suppress warnings on atomic synchronization.}
11712 @geindex Atomic Synchronization
11713 @geindex warnings
11715 This switch suppresses warnings when an access to an atomic variable
11716 requires the generation of atomic synchronization code.
11717 @end table
11719 @geindex -gnatwo (gcc)
11721 @geindex Address Clauses
11722 @geindex warnings
11725 @table @asis
11727 @item @code{-gnatwo}
11729 @emph{Activate warnings on address clause overlays.}
11731 This switch activates warnings for possibly unintended initialization
11732 effects of defining address clauses that cause one variable to overlap
11733 another. The default is that such warnings are generated.
11734 @end table
11736 @geindex -gnatwO (gcc)
11739 @table @asis
11741 @item @code{-gnatwO}
11743 @emph{Suppress warnings on address clause overlays.}
11745 This switch suppresses warnings on possibly unintended initialization
11746 effects of defining address clauses that cause one variable to overlap
11747 another.
11748 @end table
11750 @geindex -gnatw.o (gcc)
11753 @table @asis
11755 @item @code{-gnatw.o}
11757 @emph{Activate warnings on modified but unreferenced out parameters.}
11759 This switch activates warnings for variables that are modified by using
11760 them as actuals for a call to a procedure with an out mode formal, where
11761 the resulting assigned value is never read. It is applicable in the case
11762 where there is more than one out mode formal. If there is only one out
11763 mode formal, the warning is issued by default (controlled by -gnatwu).
11764 The warning is suppressed for volatile
11765 variables and also for variables that are renamings of other variables
11766 or for which an address clause is given.
11767 The default is that these warnings are not given.
11768 @end table
11770 @geindex -gnatw.O (gcc)
11773 @table @asis
11775 @item @code{-gnatw.O}
11777 @emph{Disable warnings on modified but unreferenced out parameters.}
11779 This switch suppresses warnings for variables that are modified by using
11780 them as actuals for a call to a procedure with an out mode formal, where
11781 the resulting assigned value is never read.
11782 @end table
11784 @geindex -gnatwp (gcc)
11786 @geindex Inlining
11787 @geindex warnings
11790 @table @asis
11792 @item @code{-gnatwp}
11794 @emph{Activate warnings on ineffective pragma Inlines.}
11796 This switch activates warnings for failure of front end inlining
11797 (activated by @emph{-gnatN}) to inline a particular call. There are
11798 many reasons for not being able to inline a call, including most
11799 commonly that the call is too complex to inline. The default is
11800 that such warnings are not given.
11801 Warnings on ineffective inlining by the gcc back-end can be activated
11802 separately, using the gcc switch -Winline.
11803 @end table
11805 @geindex -gnatwP (gcc)
11808 @table @asis
11810 @item @code{-gnatwP}
11812 @emph{Suppress warnings on ineffective pragma Inlines.}
11814 This switch suppresses warnings on ineffective pragma Inlines. If the
11815 inlining mechanism cannot inline a call, it will simply ignore the
11816 request silently.
11817 @end table
11819 @geindex -gnatw.p (gcc)
11821 @geindex Parameter order
11822 @geindex warnings
11825 @table @asis
11827 @item @code{-gnatw.p}
11829 @emph{Activate warnings on parameter ordering.}
11831 This switch activates warnings for cases of suspicious parameter
11832 ordering when the list of arguments are all simple identifiers that
11833 match the names of the formals, but are in a different order. The
11834 warning is suppressed if any use of named parameter notation is used,
11835 so this is the appropriate way to suppress a false positive (and
11836 serves to emphasize that the "misordering" is deliberate). The
11837 default is that such warnings are not given.
11838 @end table
11840 @geindex -gnatw.P (gcc)
11843 @table @asis
11845 @item @code{-gnatw.P}
11847 @emph{Suppress warnings on parameter ordering.}
11849 This switch suppresses warnings on cases of suspicious parameter
11850 ordering.
11851 @end table
11853 @geindex -gnatwq (gcc)
11855 @geindex Parentheses
11856 @geindex warnings
11859 @table @asis
11861 @item @code{-gnatwq}
11863 @emph{Activate warnings on questionable missing parentheses.}
11865 This switch activates warnings for cases where parentheses are not used and
11866 the result is potential ambiguity from a readers point of view. For example
11867 (not a > b) when a and b are modular means ((not a) > b) and very likely the
11868 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
11869 quite likely ((-x) mod 5) was intended. In such situations it seems best to
11870 follow the rule of always parenthesizing to make the association clear, and
11871 this warning switch warns if such parentheses are not present. The default
11872 is that these warnings are given.
11873 @end table
11875 @geindex -gnatwQ (gcc)
11878 @table @asis
11880 @item @code{-gnatwQ}
11882 @emph{Suppress warnings on questionable missing parentheses.}
11884 This switch suppresses warnings for cases where the association is not
11885 clear and the use of parentheses is preferred.
11886 @end table
11888 @geindex -gnatwr (gcc)
11891 @table @asis
11893 @item @code{-gnatwr}
11895 @emph{Activate warnings on redundant constructs.}
11897 This switch activates warnings for redundant constructs. The following
11898 is the current list of constructs regarded as redundant:
11901 @itemize *
11903 @item 
11904 Assignment of an item to itself.
11906 @item 
11907 Type conversion that converts an expression to its own type.
11909 @item 
11910 Use of the attribute @cite{Base} where @cite{typ'Base} is the same
11911 as @cite{typ}.
11913 @item 
11914 Use of pragma @cite{Pack} when all components are placed by a record
11915 representation clause.
11917 @item 
11918 Exception handler containing only a reraise statement (raise with no
11919 operand) which has no effect.
11921 @item 
11922 Use of the operator abs on an operand that is known at compile time
11923 to be non-negative
11925 @item 
11926 Comparison of boolean expressions to an explicit True value.
11927 @end itemize
11929 The default is that warnings for redundant constructs are not given.
11930 @end table
11932 @geindex -gnatwR (gcc)
11935 @table @asis
11937 @item @code{-gnatwR}
11939 @emph{Suppress warnings on redundant constructs.}
11941 This switch suppresses warnings for redundant constructs.
11942 @end table
11944 @geindex -gnatw.r (gcc)
11947 @table @asis
11949 @item @code{-gnatw.r}
11951 @emph{Activate warnings for object renaming function.}
11953 This switch activates warnings for an object renaming that renames a
11954 function call, which is equivalent to a constant declaration (as
11955 opposed to renaming the function itself).  The default is that these
11956 warnings are given.
11957 @end table
11959 @geindex -gnatwT (gcc)
11962 @table @asis
11964 @item @code{-gnatw.R}
11966 @emph{Suppress warnings for object renaming function.}
11968 This switch suppresses warnings for object renaming function.
11969 @end table
11971 @geindex -gnatws (gcc)
11974 @table @asis
11976 @item @code{-gnatws}
11978 @emph{Suppress all warnings.}
11980 This switch completely suppresses the
11981 output of all warning messages from the GNAT front end, including
11982 both warnings that can be controlled by switches described in this
11983 section, and those that are normally given unconditionally. The
11984 effect of this suppress action can only be cancelled by a subsequent
11985 use of the switch @emph{-gnatwn}.
11987 Note that switch @emph{-gnatws} does not suppress
11988 warnings from the @emph{gcc} back end.
11989 To suppress these back end warnings as well, use the switch @emph{-w}
11990 in addition to @emph{-gnatws}. Also this switch has no effect on the
11991 handling of style check messages.
11992 @end table
11994 @geindex -gnatw.s (gcc)
11996 @geindex Record Representation (component sizes)
11999 @table @asis
12001 @item @code{-gnatw.s}
12003 @emph{Activate warnings on overridden size clauses.}
12005 This switch activates warnings on component clauses in record
12006 representation clauses where the length given overrides that
12007 specified by an explicit size clause for the component type. A
12008 warning is similarly given in the array case if a specified
12009 component size overrides an explicit size clause for the array
12010 component type.
12011 @end table
12013 @geindex -gnatw.S (gcc)
12016 @table @asis
12018 @item @code{-gnatw.S}
12020 @emph{Suppress warnings on overridden size clauses.}
12022 This switch suppresses warnings on component clauses in record
12023 representation clauses that override size clauses, and similar
12024 warnings when an array component size overrides a size clause.
12025 @end table
12027 @geindex -gnatwt (gcc)
12029 @geindex Deactivated code
12030 @geindex warnings
12032 @geindex Deleted code
12033 @geindex warnings
12036 @table @asis
12038 @item @code{-gnatwt}
12040 @emph{Activate warnings for tracking of deleted conditional code.}
12042 This switch activates warnings for tracking of code in conditionals (IF and
12043 CASE statements) that is detected to be dead code which cannot be executed, and
12044 which is removed by the front end. This warning is off by default. This may be
12045 useful for detecting deactivated code in certified applications.
12046 @end table
12048 @geindex -gnatwT (gcc)
12051 @table @asis
12053 @item @code{-gnatwT}
12055 @emph{Suppress warnings for tracking of deleted conditional code.}
12057 This switch suppresses warnings for tracking of deleted conditional code.
12058 @end table
12060 @geindex -gnatw.t (gcc)
12063 @table @asis
12065 @item @code{-gnatw.t}
12067 @emph{Activate warnings on suspicious contracts.}
12069 This switch activates warnings on suspicious contracts. This includes
12070 warnings on suspicious postconditions (whether a pragma @cite{Postcondition} or a
12071 @cite{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
12072 @cite{Contract_Cases}). A function postcondition or contract case is suspicious
12073 when no postcondition or contract case for this function mentions the result
12074 of the function.  A procedure postcondition or contract case is suspicious
12075 when it only refers to the pre-state of the procedure, because in that case
12076 it should rather be expressed as a precondition. This switch also controls
12077 warnings on suspicious cases of expressions typically found in contracts like
12078 quantified expressions and uses of Update attribute. The default is that such
12079 warnings are generated.
12080 @end table
12082 @geindex -gnatw.T (gcc)
12085 @table @asis
12087 @item @code{-gnatw.T}
12089 @emph{Suppress warnings on suspicious contracts.}
12091 This switch suppresses warnings on suspicious contracts.
12092 @end table
12094 @geindex -gnatwu (gcc)
12097 @table @asis
12099 @item @code{-gnatwu}
12101 @emph{Activate warnings on unused entities.}
12103 This switch activates warnings to be generated for entities that
12104 are declared but not referenced, and for units that are @emph{with}ed
12105 and not
12106 referenced. In the case of packages, a warning is also generated if
12107 no entities in the package are referenced. This means that if a with'ed
12108 package is referenced but the only references are in @cite{use}
12109 clauses or @cite{renames}
12110 declarations, a warning is still generated. A warning is also generated
12111 for a generic package that is @emph{with}ed but never instantiated.
12112 In the case where a package or subprogram body is compiled, and there
12113 is a @emph{with} on the corresponding spec
12114 that is only referenced in the body,
12115 a warning is also generated, noting that the
12116 @emph{with} can be moved to the body. The default is that
12117 such warnings are not generated.
12118 This switch also activates warnings on unreferenced formals
12119 (it includes the effect of @emph{-gnatwf}).
12120 @end table
12122 @geindex -gnatwU (gcc)
12125 @table @asis
12127 @item @code{-gnatwU}
12129 @emph{Suppress warnings on unused entities.}
12131 This switch suppresses warnings for unused entities and packages.
12132 It also turns off warnings on unreferenced formals (and thus includes
12133 the effect of @emph{-gnatwF}).
12134 @end table
12136 @geindex -gnatw.u (gcc)
12139 @table @asis
12141 @item @code{-gnatw.u}
12143 @emph{Activate warnings on unordered enumeration types.}
12145 This switch causes enumeration types to be considered as conceptually
12146 unordered, unless an explicit pragma @cite{Ordered} is given for the type.
12147 The effect is to generate warnings in clients that use explicit comparisons
12148 or subranges, since these constructs both treat objects of the type as
12149 ordered. (A @emph{client} is defined as a unit that is other than the unit in
12150 which the type is declared, or its body or subunits.) Please refer to
12151 the description of pragma @cite{Ordered} in the
12152 @cite{GNAT Reference Manual} for further details.
12153 The default is that such warnings are not generated.
12154 @end table
12156 @geindex -gnatw.U (gcc)
12159 @table @asis
12161 @item @code{-gnatw.U}
12163 @emph{Deactivate warnings on unordered enumeration types.}
12165 This switch causes all enumeration types to be considered as ordered, so
12166 that no warnings are given for comparisons or subranges for any type.
12167 @end table
12169 @geindex -gnatwv (gcc)
12171 @geindex Unassigned variable warnings
12174 @table @asis
12176 @item @code{-gnatwv}
12178 @emph{Activate warnings on unassigned variables.}
12180 This switch activates warnings for access to variables which
12181 may not be properly initialized. The default is that
12182 such warnings are generated.
12183 @end table
12185 @geindex -gnatwV (gcc)
12188 @table @asis
12190 @item @code{-gnatwV}
12192 @emph{Suppress warnings on unassigned variables.}
12194 This switch suppresses warnings for access to variables which
12195 may not be properly initialized.
12196 For variables of a composite type, the warning can also be suppressed in
12197 Ada 2005 by using a default initialization with a box. For example, if
12198 Table is an array of records whose components are only partially uninitialized,
12199 then the following code:
12201 @example
12202 Tab : Table := (others => <>);
12203 @end example
12205 will suppress warnings on subsequent statements that access components
12206 of variable Tab.
12207 @end table
12209 @geindex -gnatw.v (gcc)
12211 @geindex bit order warnings
12214 @table @asis
12216 @item @code{-gnatw.v}
12218 @emph{Activate info messages for non-default bit order.}
12220 This switch activates messages (labeled "info", they are not warnings,
12221 just informational messages) about the effects of non-default bit-order
12222 on records to which a component clause is applied. The effect of specifying
12223 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
12224 these messages, which are given by default, are useful in understanding the
12225 exact consequences of using this feature.
12226 @end table
12228 @geindex -gnatw.V (gcc)
12231 @table @asis
12233 @item @code{-gnatw.V}
12235 @emph{Suppress info messages for non-default bit order.}
12237 This switch suppresses information messages for the effects of specifying
12238 non-default bit order on record components with component clauses.
12239 @end table
12241 @geindex -gnatww (gcc)
12243 @geindex String indexing warnings
12246 @table @asis
12248 @item @code{-gnatww}
12250 @emph{Activate warnings on wrong low bound assumption.}
12252 This switch activates warnings for indexing an unconstrained string parameter
12253 with a literal or S'Length. This is a case where the code is assuming that the
12254 low bound is one, which is in general not true (for example when a slice is
12255 passed). The default is that such warnings are generated.
12256 @end table
12258 @geindex -gnatwW (gcc)
12261 @table @asis
12263 @item @code{-gnatwW}
12265 @emph{Suppress warnings on wrong low bound assumption.}
12267 This switch suppresses warnings for indexing an unconstrained string parameter
12268 with a literal or S'Length. Note that this warning can also be suppressed
12269 in a particular case by adding an assertion that the lower bound is 1,
12270 as shown in the following example:
12272 @example
12273 procedure K (S : String) is
12274    pragma Assert (S'First = 1);
12275    ...
12276 @end example
12277 @end table
12279 @geindex -gnatw.w (gcc)
12281 @geindex Warnings Off control
12284 @table @asis
12286 @item @code{-gnatw.w}
12288 @emph{Activate warnings on Warnings Off pragmas.}
12290 This switch activates warnings for use of @cite{pragma Warnings (Off@comma{} entity)}
12291 where either the pragma is entirely useless (because it suppresses no
12292 warnings), or it could be replaced by @cite{pragma Unreferenced} or
12293 @cite{pragma Unmodified}.
12294 Also activates warnings for the case of
12295 Warnings (Off, String), where either there is no matching
12296 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12297 The default is that these warnings are not given.
12298 @end table
12300 @geindex -gnatw.W (gcc)
12303 @table @asis
12305 @item @code{-gnatw.W}
12307 @emph{Suppress warnings on unnecessary Warnings Off pragmas.}
12309 This switch suppresses warnings for use of @cite{pragma Warnings (Off@comma{} ...)}.
12310 @end table
12312 @geindex -gnatwx (gcc)
12314 @geindex Export/Import pragma warnings
12317 @table @asis
12319 @item @code{-gnatwx}
12321 @emph{Activate warnings on Export/Import pragmas.}
12323 This switch activates warnings on Export/Import pragmas when
12324 the compiler detects a possible conflict between the Ada and
12325 foreign language calling sequences. For example, the use of
12326 default parameters in a convention C procedure is dubious
12327 because the C compiler cannot supply the proper default, so
12328 a warning is issued. The default is that such warnings are
12329 generated.
12330 @end table
12332 @geindex -gnatwX (gcc)
12335 @table @asis
12337 @item @code{-gnatwX}
12339 @emph{Suppress warnings on Export/Import pragmas.}
12341 This switch suppresses warnings on Export/Import pragmas.
12342 The sense of this is that you are telling the compiler that
12343 you know what you are doing in writing the pragma, and it
12344 should not complain at you.
12345 @end table
12347 @geindex -gnatwm (gcc)
12350 @table @asis
12352 @item @code{-gnatw.x}
12354 @emph{Activate warnings for No_Exception_Propagation mode.}
12356 This switch activates warnings for exception usage when pragma Restrictions
12357 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
12358 explicit exception raises which are not covered by a local handler, and for
12359 exception handlers which do not cover a local raise. The default is that these
12360 warnings are not given.
12362 @item @code{-gnatw.X}
12364 @emph{Disable warnings for No_Exception_Propagation mode.}
12366 This switch disables warnings for exception usage when pragma Restrictions
12367 (No_Exception_Propagation) is in effect.
12368 @end table
12370 @geindex -gnatwy (gcc)
12372 @geindex Ada compatibility issues warnings
12375 @table @asis
12377 @item @code{-gnatwy}
12379 @emph{Activate warnings for Ada compatibility issues.}
12381 For the most part, newer versions of Ada are upwards compatible
12382 with older versions. For example, Ada 2005 programs will almost
12383 always work when compiled as Ada 2012.
12384 However there are some exceptions (for example the fact that
12385 @cite{some} is now a reserved word in Ada 2012). This
12386 switch activates several warnings to help in identifying
12387 and correcting such incompatibilities. The default is that
12388 these warnings are generated. Note that at one point Ada 2005
12389 was called Ada 0Y, hence the choice of character.
12390 @end table
12392 @geindex -gnatwY (gcc)
12394 @geindex Ada compatibility issues warnings
12397 @table @asis
12399 @item @code{-gnatwY}
12401 @emph{Disable warnings for Ada compatibility issues.}
12403 This switch suppresses the warnings intended to help in identifying
12404 incompatibilities between Ada language versions.
12405 @end table
12407 @geindex -gnatw.y (gcc)
12409 @geindex Package spec needing body
12412 @table @asis
12414 @item @code{-gnatw.y}
12416 @emph{Activate information messages for why package spec needs body.}
12418 There are a number of cases in which a package spec needs a body.
12419 For example, the use of pragma Elaborate_Body, or the declaration
12420 of a procedure specification requiring a completion. This switch
12421 causes information messages to be output showing why a package
12422 specification requires a body. This can be useful in the case of
12423 a large package specification which is unexpectedly requiring a
12424 body. The default is that such information messages are not output.
12425 @end table
12427 @geindex -gnatw.Y (gcc)
12429 @geindex No information messages for why package spec needs body
12432 @table @asis
12434 @item @code{-gnatw.Y}
12436 @emph{Disable information messages for why package spec needs body.}
12438 This switch suppresses the output of information messages showing why
12439 a package specification needs a body.
12440 @end table
12442 @geindex -gnatwz (gcc)
12444 @geindex Unchecked_Conversion warnings
12447 @table @asis
12449 @item @code{-gnatwz}
12451 @emph{Activate warnings on unchecked conversions.}
12453 This switch activates warnings for unchecked conversions
12454 where the types are known at compile time to have different
12455 sizes. The default is that such warnings are generated. Warnings are also
12456 generated for subprogram pointers with different conventions.
12457 @end table
12459 @geindex -gnatwZ (gcc)
12462 @table @asis
12464 @item @code{-gnatwZ}
12466 @emph{Suppress warnings on unchecked conversions.}
12468 This switch suppresses warnings for unchecked conversions
12469 where the types are known at compile time to have different
12470 sizes or conventions.
12471 @end table
12473 @geindex -gnatw.z (gcc)
12475 @geindex Size/Alignment warnings
12478 @table @asis
12480 @item @code{-gnatw.z}
12482 @emph{Activate warnings for size not a multiple of alignment.}
12484 This switch activates warnings for cases of record types with
12485 specified @cite{Size} and @cite{Alignment} attributes where the
12486 size is not a multiple of the alignment, resulting in an object
12487 size that is greater than the specified size. The default
12488 is that such warnings are generated.
12489 @end table
12491 @geindex -gnatw.Z (gcc)
12493 @geindex Size/Alignment warnings
12496 @table @asis
12498 @item @code{-gnatw.Z}
12500 @emph{Suppress warnings for size not a multiple of alignment.}
12502 This switch suppresses warnings for cases of record types with
12503 specified @cite{Size} and @cite{Alignment} attributes where the
12504 size is not a multiple of the alignment, resulting in an object
12505 size that is greater than the specified size.
12506 The warning can also be
12507 suppressed by giving an explicit @cite{Object_Size} value.
12508 @end table
12510 @geindex -Wunused (gcc)
12513 @table @asis
12515 @item @code{-Wunused}
12517 The warnings controlled by the @emph{-gnatw} switch are generated by
12518 the front end of the compiler. The @emph{GCC} back end can provide
12519 additional warnings and they are controlled by the @emph{-W} switch.
12520 For example, @emph{-Wunused} activates back end
12521 warnings for entities that are declared but not referenced.
12522 @end table
12524 @geindex -Wuninitialized (gcc)
12527 @table @asis
12529 @item @code{-Wuninitialized}
12531 Similarly, @emph{-Wuninitialized} activates
12532 the back end warning for uninitialized variables. This switch must be
12533 used in conjunction with an optimization level greater than zero.
12534 @end table
12536 @geindex -Wstack-usage (gcc)
12539 @table @asis
12541 @item @code{-Wstack-usage=@emph{len}}
12543 Warn if the stack usage of a subprogram might be larger than @cite{len} bytes.
12544 See @ref{f5,,Static Stack Usage Analysis} for details.
12545 @end table
12547 @geindex -Wall (gcc)
12550 @table @asis
12552 @item @code{-Wall}
12554 This switch enables most warnings from the @emph{GCC} back end.
12555 The code generator detects a number of warning situations that are missed
12556 by the @emph{GNAT} front end, and this switch can be used to activate them.
12557 The use of this switch also sets the default front end warning mode to
12558 @emph{-gnatwa}, that is, most front end warnings activated as well.
12559 @end table
12561 @geindex -w (gcc)
12564 @table @asis
12566 @item @code{-w}
12568 Conversely, this switch suppresses warnings from the @emph{GCC} back end.
12569 The use of this switch also sets the default front end warning mode to
12570 @emph{-gnatws}, that is, front end warnings suppressed as well.
12571 @end table
12573 @geindex -Werror (gcc)
12576 @table @asis
12578 @item @code{-Werror}
12580 This switch causes warnings from the @emph{GCC} back end to be treated as
12581 errors.  The warning string still appears, but the warning messages are
12582 counted as errors, and prevent the generation of an object file.
12583 @end table
12585 A string of warning parameters can be used in the same parameter. For example:
12587 @example
12588 -gnatwaGe
12589 @end example
12591 will turn on all optional warnings except for unrecognized pragma warnings,
12592 and also specify that warnings should be treated as errors.
12594 When no switch @emph{-gnatw} is used, this is equivalent to:
12596 @quotation
12599 @itemize *
12601 @item 
12602 @code{-gnatw.a}
12604 @item 
12605 @code{-gnatwB}
12607 @item 
12608 @code{-gnatw.b}
12610 @item 
12611 @code{-gnatwC}
12613 @item 
12614 @code{-gnatw.C}
12616 @item 
12617 @code{-gnatwD}
12619 @item 
12620 @code{-gnatwF}
12622 @item 
12623 @code{-gnatwg}
12625 @item 
12626 @code{-gnatwH}
12628 @item 
12629 @code{-gnatwi}
12631 @item 
12632 @code{-gnatw.I}
12634 @item 
12635 @code{-gnatwJ}
12637 @item 
12638 @code{-gnatwK}
12640 @item 
12641 @code{-gnatwL}
12643 @item 
12644 @code{-gnatw.L}
12646 @item 
12647 @code{-gnatwM}
12649 @item 
12650 @code{-gnatw.m}
12652 @item 
12653 @code{-gnatwn}
12655 @item 
12656 @code{-gnatwo}
12658 @item 
12659 @code{-gnatw.O}
12661 @item 
12662 @code{-gnatwP}
12664 @item 
12665 @code{-gnatw.P}
12667 @item 
12668 @code{-gnatwq}
12670 @item 
12671 @code{-gnatwR}
12673 @item 
12674 @code{-gnatw.R}
12676 @item 
12677 @code{-gnatw.S}
12679 @item 
12680 @code{-gnatwT}
12682 @item 
12683 @code{-gnatw.T}
12685 @item 
12686 @code{-gnatwU}
12688 @item 
12689 @code{-gnatwv}
12691 @item 
12692 @code{-gnatww}
12694 @item 
12695 @code{-gnatw.W}
12697 @item 
12698 @code{-gnatwx}
12700 @item 
12701 @code{-gnatw.X}
12703 @item 
12704 @code{-gnatwy}
12706 @item 
12707 @code{-gnatwz}
12708 @end itemize
12709 @end quotation
12711 @node Debugging and Assertion Control,Validity Checking,Warning Message Control,Compiler Switches
12712 @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}
12713 @subsection Debugging and Assertion Control
12716 @geindex -gnata (gcc)
12719 @table @asis
12721 @item @code{-gnata}
12723 @geindex Assert
12725 @geindex Debug
12727 @geindex Assertions
12729 @geindex Precondition
12731 @geindex Postcondition
12733 @geindex Type invariants
12735 @geindex Subtype predicates
12737 The @cite{-gnata} option is equivalent to the following Assertion_Policy pragma:
12739 @example
12740 pragma Assertion_Policy (Check);
12741 @end example
12743 Which is a shorthand for:
12745 @example
12746 pragma Assertion_Policy
12747   (Assert               => Check,
12748    Static_Predicate     => Check,
12749    Dynamic_Predicate    => Check,
12750    Pre                  => Check,
12751    Pre'Class            => Check,
12752    Post                 => Check,
12753    Post'Class           => Check,
12754    Type_Invariant       => Check,
12755    Type_Invariant'Class => Check);
12756 @end example
12758 The pragmas @cite{Assert} and @cite{Debug} normally have no effect and
12759 are ignored. This switch, where @code{a} stands for assert, causes
12760 pragmas @cite{Assert} and @cite{Debug} to be activated. This switch also
12761 causes preconditions, postconditions, subtype predicates, and
12762 type invariants to be activated.
12764 The pragmas have the form:
12766 @example
12767 pragma Assert (<Boolean-expression> [, <static-string-expression>])
12768 pragma Debug (<procedure call>)
12769 pragma Type_Invariant (<type-local-name>, <Boolean-expression>)
12770 pragma Predicate (<type-local-name>, <Boolean-expression>)
12771 pragma Precondition (<Boolean-expression>, <string-expression>)
12772 pragma Postcondition (<Boolean-expression>, <string-expression>)
12773 @end example
12775 The aspects have the form:
12777 @example
12778 with [Pre|Post|Type_Invariant|Dynamic_Predicate|Static_Predicate]
12779   => <Boolean-expression>;
12780 @end example
12782 The @cite{Assert} pragma causes @cite{Boolean-expression} to be tested.
12783 If the result is @cite{True}, the pragma has no effect (other than
12784 possible side effects from evaluating the expression). If the result is
12785 @cite{False}, the exception @cite{Assert_Failure} declared in the package
12786 @cite{System.Assertions} is raised (passing @cite{static-string-expression}, if
12787 present, as the message associated with the exception). If no string
12788 expression is given, the default is a string containing the file name and
12789 line number of the pragma.
12791 The @cite{Debug} pragma causes @cite{procedure} to be called. Note that
12792 @cite{pragma Debug} may appear within a declaration sequence, allowing
12793 debugging procedures to be called between declarations.
12795 For the aspect specification, the @cite{<Boolean-expression>} is evaluated.
12796 If the result is @cite{True}, the aspect has no effect. If the result
12797 is @cite{False}, the exception @cite{Assert_Failure} is raised.
12798 @end table
12800 @node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
12801 @anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{102}
12802 @subsection Validity Checking
12805 @geindex Validity Checking
12807 The Ada Reference Manual defines the concept of invalid values (see
12808 RM 13.9.1). The primary source of invalid values is uninitialized
12809 variables. A scalar variable that is left uninitialized may contain
12810 an invalid value; the concept of invalid does not apply to access or
12811 composite types.
12813 It is an error to read an invalid value, but the RM does not require
12814 run-time checks to detect such errors, except for some minimal
12815 checking to prevent erroneous execution (i.e. unpredictable
12816 behavior). This corresponds to the @emph{-gnatVd} switch below,
12817 which is the default. For example, by default, if the expression of a
12818 case statement is invalid, it will raise Constraint_Error rather than
12819 causing a wild jump, and if an array index on the left-hand side of an
12820 assignment is invalid, it will raise Constraint_Error rather than
12821 overwriting an arbitrary memory location.
12823 The @emph{-gnatVa} may be used to enable additional validity checks,
12824 which are not required by the RM. These checks are often very
12825 expensive (which is why the RM does not require them). These checks
12826 are useful in tracking down uninitialized variables, but they are
12827 not usually recommended for production builds, and in particular
12828 we do not recommend using these extra validity checking options in
12829 combination with optimization, since this can confuse the optimizer.
12830 If performance is a consideration, leading to the need to optimize,
12831 then the validity checking options should not be used.
12833 The other @emph{-gnatV}@code{x} switches below allow finer-grained
12834 control; you can enable whichever validity checks you desire. However,
12835 for most debugging purposes, @emph{-gnatVa} is sufficient, and the
12836 default @emph{-gnatVd} (i.e. standard Ada behavior) is usually
12837 sufficient for non-debugging use.
12839 The @emph{-gnatB} switch tells the compiler to assume that all
12840 values are valid (that is, within their declared subtype range)
12841 except in the context of a use of the Valid attribute. This means
12842 the compiler can generate more efficient code, since the range
12843 of values is better known at compile time. However, an uninitialized
12844 variable can cause wild jumps and memory corruption in this mode.
12846 The @emph{-gnatV}@code{x} switch allows control over the validity
12847 checking mode as described below.
12848 The @code{x} argument is a string of letters that
12849 indicate validity checks that are performed or not performed in addition
12850 to the default checks required by Ada as described above.
12852 @geindex -gnatVa (gcc)
12855 @table @asis
12857 @item @code{-gnatVa}
12859 @emph{All validity checks.}
12861 All validity checks are turned on.
12862 That is, @emph{-gnatVa} is
12863 equivalent to @emph{gnatVcdfimorst}.
12864 @end table
12866 @geindex -gnatVc (gcc)
12869 @table @asis
12871 @item @code{-gnatVc}
12873 @emph{Validity checks for copies.}
12875 The right hand side of assignments, and the initializing values of
12876 object declarations are validity checked.
12877 @end table
12879 @geindex -gnatVd (gcc)
12882 @table @asis
12884 @item @code{-gnatVd}
12886 @emph{Default (RM) validity checks.}
12888 Some validity checks are done by default following normal Ada semantics
12889 (RM 13.9.1 (9-11)).
12890 A check is done in case statements that the expression is within the range
12891 of the subtype. If it is not, Constraint_Error is raised.
12892 For assignments to array components, a check is done that the expression used
12893 as index is within the range. If it is not, Constraint_Error is raised.
12894 Both these validity checks may be turned off using switch @emph{-gnatVD}.
12895 They are turned on by default. If @emph{-gnatVD} is specified, a subsequent
12896 switch @emph{-gnatVd} will leave the checks turned on.
12897 Switch @emph{-gnatVD} should be used only if you are sure that all such
12898 expressions have valid values. If you use this switch and invalid values
12899 are present, then the program is erroneous, and wild jumps or memory
12900 overwriting may occur.
12901 @end table
12903 @geindex -gnatVe (gcc)
12906 @table @asis
12908 @item @code{-gnatVe}
12910 @emph{Validity checks for elementary components.}
12912 In the absence of this switch, assignments to record or array components are
12913 not validity checked, even if validity checks for assignments generally
12914 (@emph{-gnatVc}) are turned on. In Ada, assignment of composite values do not
12915 require valid data, but assignment of individual components does. So for
12916 example, there is a difference between copying the elements of an array with a
12917 slice assignment, compared to assigning element by element in a loop. This
12918 switch allows you to turn off validity checking for components, even when they
12919 are assigned component by component.
12920 @end table
12922 @geindex -gnatVf (gcc)
12925 @table @asis
12927 @item @code{-gnatVf}
12929 @emph{Validity checks for floating-point values.}
12931 In the absence of this switch, validity checking occurs only for discrete
12932 values. If @emph{-gnatVf} is specified, then validity checking also applies
12933 for floating-point values, and NaNs and infinities are considered invalid,
12934 as well as out of range values for constrained types. Note that this means
12935 that standard IEEE infinity mode is not allowed. The exact contexts
12936 in which floating-point values are checked depends on the setting of other
12937 options. For example, @emph{-gnatVif} or @emph{-gnatVfi}
12938 (the order does not matter) specifies that floating-point parameters of mode
12939 @cite{in} should be validity checked.
12940 @end table
12942 @geindex -gnatVi (gcc)
12945 @table @asis
12947 @item @code{-gnatVi}
12949 @emph{Validity checks for `in` mode parameters.}
12951 Arguments for parameters of mode @cite{in} are validity checked in function
12952 and procedure calls at the point of call.
12953 @end table
12955 @geindex -gnatVm (gcc)
12958 @table @asis
12960 @item @code{-gnatVm}
12962 @emph{Validity checks for `in out` mode parameters.}
12964 Arguments for parameters of mode @cite{in out} are validity checked in
12965 procedure calls at the point of call. The @cite{'m'} here stands for
12966 modify, since this concerns parameters that can be modified by the call.
12967 Note that there is no specific option to test @cite{out} parameters,
12968 but any reference within the subprogram will be tested in the usual
12969 manner, and if an invalid value is copied back, any reference to it
12970 will be subject to validity checking.
12971 @end table
12973 @geindex -gnatVn (gcc)
12976 @table @asis
12978 @item @code{-gnatVn}
12980 @emph{No validity checks.}
12982 This switch turns off all validity checking, including the default checking
12983 for case statements and left hand side subscripts. Note that the use of
12984 the switch @emph{-gnatp} suppresses all run-time checks, including
12985 validity checks, and thus implies @emph{-gnatVn}. When this switch
12986 is used, it cancels any other @emph{-gnatV} previously issued.
12987 @end table
12989 @geindex -gnatVo (gcc)
12992 @table @asis
12994 @item @code{-gnatVo}
12996 @emph{Validity checks for operator and attribute operands.}
12998 Arguments for predefined operators and attributes are validity checked.
12999 This includes all operators in package @cite{Standard},
13000 the shift operators defined as intrinsic in package @cite{Interfaces}
13001 and operands for attributes such as @cite{Pos}. Checks are also made
13002 on individual component values for composite comparisons, and on the
13003 expressions in type conversions and qualified expressions. Checks are
13004 also made on explicit ranges using @code{..} (e.g., slices, loops etc).
13005 @end table
13007 @geindex -gnatVp (gcc)
13010 @table @asis
13012 @item @code{-gnatVp}
13014 @emph{Validity checks for parameters.}
13016 This controls the treatment of parameters within a subprogram (as opposed
13017 to @emph{-gnatVi} and @emph{-gnatVm} which control validity testing
13018 of parameters on a call. If either of these call options is used, then
13019 normally an assumption is made within a subprogram that the input arguments
13020 have been validity checking at the point of call, and do not need checking
13021 again within a subprogram). If @emph{-gnatVp} is set, then this assumption
13022 is not made, and parameters are not assumed to be valid, so their validity
13023 will be checked (or rechecked) within the subprogram.
13024 @end table
13026 @geindex -gnatVr (gcc)
13029 @table @asis
13031 @item @code{-gnatVr}
13033 @emph{Validity checks for function returns.}
13035 The expression in @cite{return} statements in functions is validity
13036 checked.
13037 @end table
13039 @geindex -gnatVs (gcc)
13042 @table @asis
13044 @item @code{-gnatVs}
13046 @emph{Validity checks for subscripts.}
13048 All subscripts expressions are checked for validity, whether they appear
13049 on the right side or left side (in default mode only left side subscripts
13050 are validity checked).
13051 @end table
13053 @geindex -gnatVt (gcc)
13056 @table @asis
13058 @item @code{-gnatVt}
13060 @emph{Validity checks for tests.}
13062 Expressions used as conditions in @cite{if}, @cite{while} or @cite{exit}
13063 statements are checked, as well as guard expressions in entry calls.
13064 @end table
13066 The @emph{-gnatV} switch may be followed by a string of letters
13067 to turn on a series of validity checking options.
13068 For example, @code{-gnatVcr}
13069 specifies that in addition to the default validity checking, copies and
13070 function return expressions are to be validity checked.
13071 In order to make it easier to specify the desired combination of effects,
13072 the upper case letters @cite{CDFIMORST} may
13073 be used to turn off the corresponding lower case option.
13074 Thus @code{-gnatVaM} turns on all validity checking options except for
13075 checking of @cite{**in out**} procedure arguments.
13077 The specification of additional validity checking generates extra code (and
13078 in the case of @emph{-gnatVa} the code expansion can be substantial).
13079 However, these additional checks can be very useful in detecting
13080 uninitialized variables, incorrect use of unchecked conversion, and other
13081 errors leading to invalid values. The use of pragma @cite{Initialize_Scalars}
13082 is useful in conjunction with the extra validity checking, since this
13083 ensures that wherever possible uninitialized variables have invalid values.
13085 See also the pragma @cite{Validity_Checks} which allows modification of
13086 the validity checking mode at the program source level, and also allows for
13087 temporary disabling of validity checks.
13089 @node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
13090 @anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{103}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{fb}
13091 @subsection Style Checking
13094 @geindex Style checking
13096 @geindex -gnaty (gcc)
13098 The @emph{-gnatyx} switch causes the compiler to
13099 enforce specified style rules. A limited set of style rules has been used
13100 in writing the GNAT sources themselves. This switch allows user programs
13101 to activate all or some of these checks. If the source program fails a
13102 specified style check, an appropriate message is given, preceded by
13103 the character sequence '(style)'. This message does not prevent
13104 successful compilation (unless the @emph{-gnatwe} switch is used).
13106 Note that this is by no means intended to be a general facility for
13107 checking arbitrary coding standards. It is simply an embedding of the
13108 style rules we have chosen for the GNAT sources. If you are starting
13109 a project which does not have established style standards, you may
13110 find it useful to adopt the entire set of GNAT coding standards, or
13111 some subset of them.
13114 The string @cite{x} is a sequence of letters or digits
13115 indicating the particular style
13116 checks to be performed. The following checks are defined:
13118 @geindex -gnaty[0-9] (gcc)
13121 @table @asis
13123 @item @code{-gnaty0}
13125 @emph{Specify indentation level.}
13127 If a digit from 1-9 appears
13128 in the string after @emph{-gnaty}
13129 then proper indentation is checked, with the digit indicating the
13130 indentation level required. A value of zero turns off this style check.
13131 The general style of required indentation is as specified by
13132 the examples in the Ada Reference Manual. Full line comments must be
13133 aligned with the @cite{--} starting on a column that is a multiple of
13134 the alignment level, or they may be aligned the same way as the following
13135 non-blank line (this is useful when full line comments appear in the middle
13136 of a statement, or they may be aligned with the source line on the previous
13137 non-blank line.
13138 @end table
13140 @geindex -gnatya (gcc)
13143 @table @asis
13145 @item @code{-gnatya}
13147 @emph{Check attribute casing.}
13149 Attribute names, including the case of keywords such as @cite{digits}
13150 used as attributes names, must be written in mixed case, that is, the
13151 initial letter and any letter following an underscore must be uppercase.
13152 All other letters must be lowercase.
13153 @end table
13155 @geindex -gnatyA (gcc)
13158 @table @asis
13160 @item @code{-gnatyA}
13162 @emph{Use of array index numbers in array attributes.}
13164 When using the array attributes First, Last, Range,
13165 or Length, the index number must be omitted for one-dimensional arrays
13166 and is required for multi-dimensional arrays.
13167 @end table
13169 @geindex -gnatyb (gcc)
13172 @table @asis
13174 @item @code{-gnatyb}
13176 @emph{Blanks not allowed at statement end.}
13178 Trailing blanks are not allowed at the end of statements. The purpose of this
13179 rule, together with h (no horizontal tabs), is to enforce a canonical format
13180 for the use of blanks to separate source tokens.
13181 @end table
13183 @geindex -gnatyB (gcc)
13186 @table @asis
13188 @item @code{-gnatyB}
13190 @emph{Check Boolean operators.}
13192 The use of AND/OR operators is not permitted except in the cases of modular
13193 operands, array operands, and simple stand-alone boolean variables or
13194 boolean constants. In all other cases @cite{and then}/@cite{or else} are
13195 required.
13196 @end table
13198 @geindex -gnatyc (gcc)
13201 @table @asis
13203 @item @code{-gnatyc}
13205 @emph{Check comments, double space.}
13207 Comments must meet the following set of rules:
13210 @itemize *
13212 @item 
13213 The '@cite{--}' that starts the column must either start in column one,
13214 or else at least one blank must precede this sequence.
13216 @item 
13217 Comments that follow other tokens on a line must have at least one blank
13218 following the '@cite{--}' at the start of the comment.
13220 @item 
13221 Full line comments must have at least two blanks following the
13222 '@cite{--}' that starts the comment, with the following exceptions.
13224 @item 
13225 A line consisting only of the '@cite{--}' characters, possibly preceded
13226 by blanks is permitted.
13228 @item 
13229 A comment starting with '@cite{--x}' where @cite{x} is a special character
13230 is permitted.
13231 This allows proper processing of the output generated by specialized tools
13232 including @emph{gnatprep} (where '@cite{--!}' is used) and the SPARK
13233 annotation
13234 language (where '@cite{--#}' is used). For the purposes of this rule, a
13235 special character is defined as being in one of the ASCII ranges
13236 @cite{16#21#...16#2F#} or @cite{16#3A#...16#3F#}.
13237 Note that this usage is not permitted
13238 in GNAT implementation units (i.e., when @emph{-gnatg} is used).
13240 @item 
13241 A line consisting entirely of minus signs, possibly preceded by blanks, is
13242 permitted. This allows the construction of box comments where lines of minus
13243 signs are used to form the top and bottom of the box.
13245 @item 
13246 A comment that starts and ends with '@cite{--}' is permitted as long as at
13247 least one blank follows the initial '@cite{--}'. Together with the preceding
13248 rule, this allows the construction of box comments, as shown in the following
13249 example:
13251 @example
13252 ---------------------------
13253 -- This is a box comment --
13254 -- with two text lines.  --
13255 ---------------------------
13256 @end example
13257 @end itemize
13258 @end table
13260 @geindex -gnatyC (gcc)
13263 @table @asis
13265 @item @code{-gnatyC}
13267 @emph{Check comments, single space.}
13269 This is identical to @cite{c} except that only one space
13270 is required following the @cite{--} of a comment instead of two.
13271 @end table
13273 @geindex -gnatyd (gcc)
13276 @table @asis
13278 @item @code{-gnatyd}
13280 @emph{Check no DOS line terminators present.}
13282 All lines must be terminated by a single ASCII.LF
13283 character (in particular the DOS line terminator sequence CR/LF is not
13284 allowed).
13285 @end table
13287 @geindex -gnatye (gcc)
13290 @table @asis
13292 @item @code{-gnatye}
13294 @emph{Check end/exit labels.}
13296 Optional labels on @cite{end} statements ending subprograms and on
13297 @cite{exit} statements exiting named loops, are required to be present.
13298 @end table
13300 @geindex -gnatyf (gcc)
13303 @table @asis
13305 @item @code{-gnatyf}
13307 @emph{No form feeds or vertical tabs.}
13309 Neither form feeds nor vertical tab characters are permitted
13310 in the source text.
13311 @end table
13313 @geindex -gnatyg (gcc)
13316 @table @asis
13318 @item @code{-gnatyg}
13320 @emph{GNAT style mode.}
13322 The set of style check switches is set to match that used by the GNAT sources.
13323 This may be useful when developing code that is eventually intended to be
13324 incorporated into GNAT. Currently this is equivalent to @emph{-gnatwydISux})
13325 but additional style switches may be added to this set in the future without
13326 advance notice.
13327 @end table
13329 @geindex -gnatyh (gcc)
13332 @table @asis
13334 @item @code{-gnatyh}
13336 @emph{No horizontal tabs.}
13338 Horizontal tab characters are not permitted in the source text.
13339 Together with the b (no blanks at end of line) check, this
13340 enforces a canonical form for the use of blanks to separate
13341 source tokens.
13342 @end table
13344 @geindex -gnatyi (gcc)
13347 @table @asis
13349 @item @code{-gnatyi}
13351 @emph{Check if-then layout.}
13353 The keyword @cite{then} must appear either on the same
13354 line as corresponding @cite{if}, or on a line on its own, lined
13355 up under the @cite{if}.
13356 @end table
13358 @geindex -gnatyI (gcc)
13361 @table @asis
13363 @item @code{-gnatyI}
13365 @emph{check mode IN keywords.}
13367 Mode @cite{in} (the default mode) is not
13368 allowed to be given explicitly. @cite{in out} is fine,
13369 but not @cite{in} on its own.
13370 @end table
13372 @geindex -gnatyk (gcc)
13375 @table @asis
13377 @item @code{-gnatyk}
13379 @emph{Check keyword casing.}
13381 All keywords must be in lower case (with the exception of keywords
13382 such as @cite{digits} used as attribute names to which this check
13383 does not apply).
13384 @end table
13386 @geindex -gnatyl (gcc)
13389 @table @asis
13391 @item @code{-gnatyl}
13393 @emph{Check layout.}
13395 Layout of statement and declaration constructs must follow the
13396 recommendations in the Ada Reference Manual, as indicated by the
13397 form of the syntax rules. For example an @cite{else} keyword must
13398 be lined up with the corresponding @cite{if} keyword.
13400 There are two respects in which the style rule enforced by this check
13401 option are more liberal than those in the Ada Reference Manual. First
13402 in the case of record declarations, it is permissible to put the
13403 @cite{record} keyword on the same line as the @cite{type} keyword, and
13404 then the @cite{end} in @cite{end record} must line up under @cite{type}.
13405 This is also permitted when the type declaration is split on two lines.
13406 For example, any of the following three layouts is acceptable:
13408 @example
13409 type q is record
13410    a : integer;
13411    b : integer;
13412 end record;
13414 type q is
13415    record
13416       a : integer;
13417       b : integer;
13418    end record;
13420 type q is
13421    record
13422       a : integer;
13423       b : integer;
13424 end record;
13425 @end example
13427 Second, in the case of a block statement, a permitted alternative
13428 is to put the block label on the same line as the @cite{declare} or
13429 @cite{begin} keyword, and then line the @cite{end} keyword up under
13430 the block label. For example both the following are permitted:
13432 @example
13433 Block : declare
13434    A : Integer := 3;
13435 begin
13436    Proc (A, A);
13437 end Block;
13439 Block :
13440    declare
13441       A : Integer := 3;
13442    begin
13443       Proc (A, A);
13444    end Block;
13445 @end example
13447 The same alternative format is allowed for loops. For example, both of
13448 the following are permitted:
13450 @example
13451 Clear : while J < 10 loop
13452    A (J) := 0;
13453 end loop Clear;
13455 Clear :
13456    while J < 10 loop
13457       A (J) := 0;
13458    end loop Clear;
13459 @end example
13460 @end table
13462 @geindex -gnatyLnnn (gcc)
13465 @table @asis
13467 @item @code{-gnatyL}
13469 @emph{Set maximum nesting level.}
13471 The maximum level of nesting of constructs (including subprograms, loops,
13472 blocks, packages, and conditionals) may not exceed the given value
13473 @emph{nnn}. A value of zero disconnects this style check.
13474 @end table
13476 @geindex -gnatym (gcc)
13479 @table @asis
13481 @item @code{-gnatym}
13483 @emph{Check maximum line length.}
13485 The length of source lines must not exceed 79 characters, including
13486 any trailing blanks. The value of 79 allows convenient display on an
13487 80 character wide device or window, allowing for possible special
13488 treatment of 80 character lines. Note that this count is of
13489 characters in the source text. This means that a tab character counts
13490 as one character in this count and a wide character sequence counts as
13491 a single character (however many bytes are needed in the encoding).
13492 @end table
13494 @geindex -gnatyMnnn (gcc)
13497 @table @asis
13499 @item @code{-gnatyM}
13501 @emph{Set maximum line length.}
13503 The length of lines must not exceed the
13504 given value @emph{nnn}. The maximum value that can be specified is 32767.
13505 If neither style option for setting the line length is used, then the
13506 default is 255. This also controls the maximum length of lexical elements,
13507 where the only restriction is that they must fit on a single line.
13508 @end table
13510 @geindex -gnatyn (gcc)
13513 @table @asis
13515 @item @code{-gnatyn}
13517 @emph{Check casing of entities in Standard.}
13519 Any identifier from Standard must be cased
13520 to match the presentation in the Ada Reference Manual (for example,
13521 @cite{Integer} and @cite{ASCII.NUL}).
13522 @end table
13524 @geindex -gnatyN (gcc)
13527 @table @asis
13529 @item @code{-gnatyN}
13531 @emph{Turn off all style checks.}
13533 All style check options are turned off.
13534 @end table
13536 @geindex -gnatyo (gcc)
13539 @table @asis
13541 @item @code{-gnatyo}
13543 @emph{Check order of subprogram bodies.}
13545 All subprogram bodies in a given scope
13546 (e.g., a package body) must be in alphabetical order. The ordering
13547 rule uses normal Ada rules for comparing strings, ignoring casing
13548 of letters, except that if there is a trailing numeric suffix, then
13549 the value of this suffix is used in the ordering (e.g., Junk2 comes
13550 before Junk10).
13551 @end table
13553 @geindex -gnatyO (gcc)
13556 @table @asis
13558 @item @code{-gnatyO}
13560 @emph{Check that overriding subprograms are explicitly marked as such.}
13562 This applies to all subprograms of a derived type that override a primitive
13563 operation of the type, for both tagged and untagged types. In particular,
13564 the declaration of a primitive operation of a type extension that overrides
13565 an inherited operation must carry an overriding indicator. Another case is
13566 the declaration of a function that overrides a predefined operator (such
13567 as an equality operator).
13568 @end table
13570 @geindex -gnatyp (gcc)
13573 @table @asis
13575 @item @code{-gnatyp}
13577 @emph{Check pragma casing.}
13579 Pragma names must be written in mixed case, that is, the
13580 initial letter and any letter following an underscore must be uppercase.
13581 All other letters must be lowercase. An exception is that SPARK_Mode is
13582 allowed as an alternative for Spark_Mode.
13583 @end table
13585 @geindex -gnatyr (gcc)
13588 @table @asis
13590 @item @code{-gnatyr}
13592 @emph{Check references.}
13594 All identifier references must be cased in the same way as the
13595 corresponding declaration. No specific casing style is imposed on
13596 identifiers. The only requirement is for consistency of references
13597 with declarations.
13598 @end table
13600 @geindex -gnatys (gcc)
13603 @table @asis
13605 @item @code{-gnatys}
13607 @emph{Check separate specs.}
13609 Separate declarations ('specs') are required for subprograms (a
13610 body is not allowed to serve as its own declaration). The only
13611 exception is that parameterless library level procedures are
13612 not required to have a separate declaration. This exception covers
13613 the most frequent form of main program procedures.
13614 @end table
13616 @geindex -gnatyS (gcc)
13619 @table @asis
13621 @item @code{-gnatyS}
13623 @emph{Check no statements after then/else.}
13625 No statements are allowed
13626 on the same line as a @cite{then} or @cite{else} keyword following the
13627 keyword in an @cite{if} statement. @cite{or else} and @cite{and then} are not
13628 affected, and a special exception allows a pragma to appear after @cite{else}.
13629 @end table
13631 @geindex -gnatyt (gcc)
13634 @table @asis
13636 @item @code{-gnatyt}
13638 @emph{Check token spacing.}
13640 The following token spacing rules are enforced:
13643 @itemize *
13645 @item 
13646 The keywords @cite{abs} and @cite{not} must be followed by a space.
13648 @item 
13649 The token @cite{=>} must be surrounded by spaces.
13651 @item 
13652 The token @cite{<>} must be preceded by a space or a left parenthesis.
13654 @item 
13655 Binary operators other than @cite{**} must be surrounded by spaces.
13656 There is no restriction on the layout of the @cite{**} binary operator.
13658 @item 
13659 Colon must be surrounded by spaces.
13661 @item 
13662 Colon-equal (assignment, initialization) must be surrounded by spaces.
13664 @item 
13665 Comma must be the first non-blank character on the line, or be
13666 immediately preceded by a non-blank character, and must be followed
13667 by a space.
13669 @item 
13670 If the token preceding a left parenthesis ends with a letter or digit, then
13671 a space must separate the two tokens.
13673 @item 
13674 If the token following a right parenthesis starts with a letter or digit, then
13675 a space must separate the two tokens.
13677 @item 
13678 A right parenthesis must either be the first non-blank character on
13679 a line, or it must be preceded by a non-blank character.
13681 @item 
13682 A semicolon must not be preceded by a space, and must not be followed by
13683 a non-blank character.
13685 @item 
13686 A unary plus or minus may not be followed by a space.
13688 @item 
13689 A vertical bar must be surrounded by spaces.
13690 @end itemize
13692 Exactly one blank (and no other white space) must appear between
13693 a @cite{not} token and a following @cite{in} token.
13694 @end table
13696 @geindex -gnatyu (gcc)
13699 @table @asis
13701 @item @code{-gnatyu}
13703 @emph{Check unnecessary blank lines.}
13705 Unnecessary blank lines are not allowed. A blank line is considered
13706 unnecessary if it appears at the end of the file, or if more than
13707 one blank line occurs in sequence.
13708 @end table
13710 @geindex -gnatyx (gcc)
13713 @table @asis
13715 @item @code{-gnatyx}
13717 @emph{Check extra parentheses.}
13719 Unnecessary extra level of parentheses (C-style) are not allowed
13720 around conditions in @cite{if} statements, @cite{while} statements and
13721 @cite{exit} statements.
13722 @end table
13724 @geindex -gnatyy (gcc)
13727 @table @asis
13729 @item @code{-gnatyy}
13731 @emph{Set all standard style check options.}
13733 This is equivalent to @cite{gnaty3aAbcefhiklmnprst}, that is all checking
13734 options enabled with the exception of @emph{-gnatyB}, @emph{-gnatyd},
13735 @emph{-gnatyI}, @emph{-gnatyLnnn}, @emph{-gnatyo}, @emph{-gnatyO},
13736 @emph{-gnatyS}, @emph{-gnatyu}, and @emph{-gnatyx}.
13737 @end table
13739 @geindex -gnaty- (gcc)
13742 @table @asis
13744 @item @code{-gnaty-}
13746 @emph{Remove style check options.}
13748 This causes any subsequent options in the string to act as canceling the
13749 corresponding style check option. To cancel maximum nesting level control,
13750 use @emph{L} parameter witout any integer value after that, because any
13751 digit following @emph{-} in the parameter string of the @emph{-gnaty}
13752 option will be threated as canceling indentation check. The same is true
13753 for @emph{M} parameter. @emph{y} and @emph{N} parameters are not
13754 allowed after @emph{-}.
13755 @end table
13757 @geindex -gnaty+ (gcc)
13760 @table @asis
13762 @item @code{-gnaty+}
13764 @emph{Enable style check options.}
13766 This causes any subsequent options in the string to enable the corresponding
13767 style check option. That is, it cancels the effect of a previous -,
13768 if any.
13769 @end table
13771 @c end of switch description (leave this comment to ease automatic parsing for
13773 @c GPS
13775 In the above rules, appearing in column one is always permitted, that is,
13776 counts as meeting either a requirement for a required preceding space,
13777 or as meeting a requirement for no preceding space.
13779 Appearing at the end of a line is also always permitted, that is, counts
13780 as meeting either a requirement for a following space, or as meeting
13781 a requirement for no following space.
13783 If any of these style rules is violated, a message is generated giving
13784 details on the violation. The initial characters of such messages are
13785 always '@cite{(style)}'. Note that these messages are treated as warning
13786 messages, so they normally do not prevent the generation of an object
13787 file. The @emph{-gnatwe} switch can be used to treat warning messages,
13788 including style messages, as fatal errors.
13790 The switch @code{-gnaty} on its own (that is not
13791 followed by any letters or digits) is equivalent
13792 to the use of @emph{-gnatyy} as described above, that is all
13793 built-in standard style check options are enabled.
13795 The switch @code{-gnatyN} clears any previously set style checks.
13797 @node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
13798 @anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{f9}@anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{104}
13799 @subsection Run-Time Checks
13802 @geindex Division by zero
13804 @geindex Access before elaboration
13806 @geindex Checks
13807 @geindex division by zero
13809 @geindex Checks
13810 @geindex access before elaboration
13812 @geindex Checks
13813 @geindex stack overflow checking
13815 By default, the following checks are suppressed: stack overflow
13816 checks, and checks for access before elaboration on subprogram
13817 calls. All other checks, including overflow checks, range checks and
13818 array bounds checks, are turned on by default. The following @emph{gcc}
13819 switches refine this default behavior.
13821 @geindex -gnatp (gcc)
13824 @table @asis
13826 @item @code{-gnatp}
13828 @geindex Suppressing checks
13830 @geindex Checks
13831 @geindex suppressing
13833 This switch causes the unit to be compiled
13834 as though @cite{pragma Suppress (All_checks)}
13835 had been present in the source. Validity checks are also eliminated (in
13836 other words @emph{-gnatp} also implies @emph{-gnatVn}.
13837 Use this switch to improve the performance
13838 of the code at the expense of safety in the presence of invalid data or
13839 program bugs.
13841 Note that when checks are suppressed, the compiler is allowed, but not
13842 required, to omit the checking code. If the run-time cost of the
13843 checking code is zero or near-zero, the compiler will generate it even
13844 if checks are suppressed. In particular, if the compiler can prove
13845 that a certain check will necessarily fail, it will generate code to
13846 do an unconditional 'raise', even if checks are suppressed. The
13847 compiler warns in this case. Another case in which checks may not be
13848 eliminated is when they are embedded in certain run time routines such
13849 as math library routines.
13851 Of course, run-time checks are omitted whenever the compiler can prove
13852 that they will not fail, whether or not checks are suppressed.
13854 Note that if you suppress a check that would have failed, program
13855 execution is erroneous, which means the behavior is totally
13856 unpredictable. The program might crash, or print wrong answers, or
13857 do anything else. It might even do exactly what you wanted it to do
13858 (and then it might start failing mysteriously next week or next
13859 year). The compiler will generate code based on the assumption that
13860 the condition being checked is true, which can result in erroneous
13861 execution if that assumption is wrong.
13863 The checks subject to suppression include all the checks defined by the Ada
13864 standard, the additional implementation defined checks @cite{Alignment_Check},
13865 @cite{Duplicated_Tag_Check}, @cite{Predicate_Check}, Container_Checks, Tampering_Check,
13866 and @cite{Validity_Check}, as well as any checks introduced using @cite{pragma Check_Name}. Note that @cite{Atomic_Synchronization} is not automatically
13867 suppressed by use of this option.
13869 If the code depends on certain checks being active, you can use
13870 pragma @cite{Unsuppress} either as a configuration pragma or as
13871 a local pragma to make sure that a specified check is performed
13872 even if @emph{gnatp} is specified.
13874 The @emph{-gnatp} switch has no effect if a subsequent
13875 @emph{-gnat-p} switch appears.
13876 @end table
13878 @geindex -gnat-p (gcc)
13880 @geindex Suppressing checks
13882 @geindex Checks
13883 @geindex suppressing
13885 @geindex Suppress
13888 @table @asis
13890 @item @code{-gnat-p}
13892 This switch cancels the effect of a previous @emph{gnatp} switch.
13893 @end table
13895 @geindex -gnato?? (gcc)
13897 @geindex Overflow checks
13899 @geindex Overflow mode
13901 @geindex Check
13902 @geindex overflow
13905 @table @asis
13907 @item @code{-gnato??}
13909 This switch controls the mode used for computing intermediate
13910 arithmetic integer operations, and also enables overflow checking.
13911 For a full description of overflow mode and checking control, see
13912 the 'Overflow Check Handling in GNAT' appendix in this
13913 User's Guide.
13915 Overflow checks are always enabled by this switch. The argument
13916 controls the mode, using the codes
13919 @table @asis
13921 @item @emph{1 = STRICT}
13923 In STRICT mode, intermediate operations are always done using the
13924 base type, and overflow checking ensures that the result is within
13925 the base type range.
13927 @item @emph{2 = MINIMIZED}
13929 In MINIMIZED mode, overflows in intermediate operations are avoided
13930 where possible by using a larger integer type for the computation
13931 (typically @cite{Long_Long_Integer}). Overflow checking ensures that
13932 the result fits in this larger integer type.
13934 @item @emph{3 = ELIMINATED}
13936 In ELIMINATED mode, overflows in intermediate operations are avoided
13937 by using multi-precision arithmetic. In this case, overflow checking
13938 has no effect on intermediate operations (since overflow is impossible).
13939 @end table
13941 If two digits are present after @emph{-gnato} then the first digit
13942 sets the mode for expressions outside assertions, and the second digit
13943 sets the mode for expressions within assertions. Here assertions is used
13944 in the technical sense (which includes for example precondition and
13945 postcondition expressions).
13947 If one digit is present, the corresponding mode is applicable to both
13948 expressions within and outside assertion expressions.
13950 If no digits are present, the default is to enable overflow checks
13951 and set STRICT mode for both kinds of expressions. This is compatible
13952 with the use of @emph{-gnato} in previous versions of GNAT.
13954 @geindex Machine_Overflows
13956 Note that the @emph{-gnato??} switch does not affect the code generated
13957 for any floating-point operations; it applies only to integer semantics.
13958 For floating-point, GNAT has the @cite{Machine_Overflows}
13959 attribute set to @cite{False} and the normal mode of operation is to
13960 generate IEEE NaN and infinite values on overflow or invalid operations
13961 (such as dividing 0.0 by 0.0).
13963 The reason that we distinguish overflow checking from other kinds of
13964 range constraint checking is that a failure of an overflow check, unlike
13965 for example the failure of a range check, can result in an incorrect
13966 value, but cannot cause random memory destruction (like an out of range
13967 subscript), or a wild jump (from an out of range case value). Overflow
13968 checking is also quite expensive in time and space, since in general it
13969 requires the use of double length arithmetic.
13971 Note again that the default is @emph{-gnato11} (equivalent to @emph{-gnato1}),
13972 so overflow checking is performed in STRICT mode by default.
13973 @end table
13975 @geindex -gnatE (gcc)
13977 @geindex Elaboration checks
13979 @geindex Check
13980 @geindex elaboration
13983 @table @asis
13985 @item @code{-gnatE}
13987 Enables dynamic checks for access-before-elaboration
13988 on subprogram calls and generic instantiations.
13989 Note that @emph{-gnatE} is not necessary for safety, because in the
13990 default mode, GNAT ensures statically that the checks would not fail.
13991 For full details of the effect and use of this switch,
13992 @ref{1c,,Compiling with gcc}.
13993 @end table
13995 @geindex -fstack-check (gcc)
13997 @geindex Stack Overflow Checking
13999 @geindex Checks
14000 @geindex stack overflow checking
14003 @table @asis
14005 @item @code{-fstack-check}
14007 Activates stack overflow checking. For full details of the effect and use of
14008 this switch see @ref{f4,,Stack Overflow Checking}.
14009 @end table
14011 @geindex Unsuppress
14013 The setting of these switches only controls the default setting of the
14014 checks. You may modify them using either @cite{Suppress} (to remove
14015 checks) or @cite{Unsuppress} (to add back suppressed checks) pragmas in
14016 the program source.
14018 @node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
14019 @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}
14020 @subsection Using @emph{gcc} for Syntax Checking
14023 @geindex -gnats (gcc)
14026 @table @asis
14028 @item @code{-gnats}
14030 The @cite{s} stands for 'syntax'.
14032 Run GNAT in syntax checking only mode. For
14033 example, the command
14035 @example
14036 $ gcc -c -gnats x.adb
14037 @end example
14039 compiles file @code{x.adb} in syntax-check-only mode. You can check a
14040 series of files in a single command
14041 , and can use wild cards to specify such a group of files.
14042 Note that you must specify the @emph{-c} (compile
14043 only) flag in addition to the @emph{-gnats} flag.
14045 You may use other switches in conjunction with @emph{-gnats}. In
14046 particular, @emph{-gnatl} and @emph{-gnatv} are useful to control the
14047 format of any generated error messages.
14049 When the source file is empty or contains only empty lines and/or comments,
14050 the output is a warning:
14052 @example
14053 $ gcc -c -gnats -x ada toto.txt
14054 toto.txt:1:01: warning: empty file, contains no compilation units
14056 @end example
14058 Otherwise, the output is simply the error messages, if any. No object file or
14059 ALI file is generated by a syntax-only compilation. Also, no units other
14060 than the one specified are accessed. For example, if a unit @cite{X}
14061 @emph{with}s a unit @cite{Y}, compiling unit @cite{X} in syntax
14062 check only mode does not access the source file containing unit
14063 @cite{Y}.
14065 @geindex Multiple units
14066 @geindex syntax checking
14068 Normally, GNAT allows only a single unit in a source file. However, this
14069 restriction does not apply in syntax-check-only mode, and it is possible
14070 to check a file containing multiple compilation units concatenated
14071 together. This is primarily used by the @cite{gnatchop} utility
14072 (@ref{36,,Renaming Files with gnatchop}).
14073 @end table
14075 @node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
14076 @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}
14077 @subsection Using @emph{gcc} for Semantic Checking
14080 @geindex -gnatc (gcc)
14083 @table @asis
14085 @item @code{-gnatc}
14087 The @cite{c} stands for 'check'.
14088 Causes the compiler to operate in semantic check mode,
14089 with full checking for all illegalities specified in the
14090 Ada Reference Manual, but without generation of any object code
14091 (no object file is generated).
14093 Because dependent files must be accessed, you must follow the GNAT
14094 semantic restrictions on file structuring to operate in this mode:
14097 @itemize *
14099 @item 
14100 The needed source files must be accessible
14101 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
14103 @item 
14104 Each file must contain only one compilation unit.
14106 @item 
14107 The file name and unit name must match (@ref{52,,File Naming Rules}).
14108 @end itemize
14110 The output consists of error messages as appropriate. No object file is
14111 generated. An @code{ALI} file is generated for use in the context of
14112 cross-reference tools, but this file is marked as not being suitable
14113 for binding (since no object file is generated).
14114 The checking corresponds exactly to the notion of
14115 legality in the Ada Reference Manual.
14117 Any unit can be compiled in semantics-checking-only mode, including
14118 units that would not normally be compiled (subunits,
14119 and specifications where a separate body is present).
14120 @end table
14122 @node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
14123 @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}
14124 @subsection Compiling Different Versions of Ada
14127 The switches described in this section allow you to explicitly specify
14128 the version of the Ada language that your programs are written in.
14129 The default mode is Ada 2012,
14130 but you can also specify Ada 95, Ada 2005 mode, or
14131 indicate Ada 83 compatibility mode.
14133 @geindex Compatibility with Ada 83
14135 @geindex -gnat83 (gcc)
14137 @geindex ACVC
14138 @geindex Ada 83 tests
14140 @geindex Ada 83 mode
14143 @table @asis
14145 @item @code{-gnat83} (Ada 83 Compatibility Mode)
14147 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
14148 specifies that the program is to be compiled in Ada 83 mode. With
14149 @emph{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
14150 semantics where this can be done easily.
14151 It is not possible to guarantee this switch does a perfect
14152 job; some subtle tests, such as are
14153 found in earlier ACVC tests (and that have been removed from the ACATS suite
14154 for Ada 95), might not compile correctly.
14155 Nevertheless, this switch may be useful in some circumstances, for example
14156 where, due to contractual reasons, existing code needs to be maintained
14157 using only Ada 83 features.
14159 With few exceptions (most notably the need to use @cite{<>} on
14160 unconstrained 
14161 @geindex Generic formal parameters
14162 generic formal parameters,
14163 the use of the new Ada 95 / Ada 2005
14164 reserved words, and the use of packages
14165 with optional bodies), it is not necessary to specify the
14166 @emph{-gnat83} switch when compiling Ada 83 programs, because, with rare
14167 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
14168 a correct Ada 83 program is usually also a correct program
14169 in these later versions of the language standard. For further information
14170 please refer to the @cite{Compatibility_and_Porting_Guide} chapter in the
14171 @cite{GNAT Reference Manual}.
14172 @end table
14174 @geindex -gnat95 (gcc)
14176 @geindex Ada 95 mode
14179 @table @asis
14181 @item @code{-gnat95} (Ada 95 mode)
14183 This switch directs the compiler to implement the Ada 95 version of the
14184 language.
14185 Since Ada 95 is almost completely upwards
14186 compatible with Ada 83, Ada 83 programs may generally be compiled using
14187 this switch (see the description of the @emph{-gnat83} switch for further
14188 information about Ada 83 mode).
14189 If an Ada 2005 program is compiled in Ada 95 mode,
14190 uses of the new Ada 2005 features will cause error
14191 messages or warnings.
14193 This switch also can be used to cancel the effect of a previous
14194 @emph{-gnat83}, @emph{-gnat05/2005}, or @emph{-gnat12/2012}
14195 switch earlier in the command line.
14196 @end table
14198 @geindex -gnat05 (gcc)
14200 @geindex -gnat2005 (gcc)
14202 @geindex Ada 2005 mode
14205 @table @asis
14207 @item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
14209 This switch directs the compiler to implement the Ada 2005 version of the
14210 language, as documented in the official Ada standards document.
14211 Since Ada 2005 is almost completely upwards
14212 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
14213 may generally be compiled using this switch (see the description of the
14214 @emph{-gnat83} and @emph{-gnat95} switches for further
14215 information).
14216 @end table
14218 @geindex -gnat12 (gcc)
14220 @geindex -gnat2012 (gcc)
14222 @geindex Ada 2012 mode
14225 @table @asis
14227 @item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
14229 This switch directs the compiler to implement the Ada 2012 version of the
14230 language (also the default).
14231 Since Ada 2012 is almost completely upwards
14232 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
14233 Ada 83 and Ada 95 programs
14234 may generally be compiled using this switch (see the description of the
14235 @emph{-gnat83}, @emph{-gnat95}, and @emph{-gnat05/2005} switches
14236 for further information).
14237 @end table
14239 @geindex -gnatX (gcc)
14241 @geindex Ada language extensions
14243 @geindex GNAT extensions
14246 @table @asis
14248 @item @code{-gnatX} (Enable GNAT Extensions)
14250 This switch directs the compiler to implement the latest version of the
14251 language (currently Ada 2012) and also to enable certain GNAT implementation
14252 extensions that are not part of any Ada standard. For a full list of these
14253 extensions, see the GNAT reference manual.
14254 @end table
14256 @node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14257 @anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{10a}@anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{48}
14258 @subsection Character Set Control
14261 @geindex -gnati (gcc)
14264 @table @asis
14266 @item @code{-gnati@emph{c}}
14268 Normally GNAT recognizes the Latin-1 character set in source program
14269 identifiers, as described in the Ada Reference Manual.
14270 This switch causes
14271 GNAT to recognize alternate character sets in identifiers. @cite{c} is a
14272 single character  indicating the character set, as follows:
14275 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14276 @item
14278 @emph{1}
14280 @tab
14282 ISO 8859-1 (Latin-1) identifiers
14284 @item
14286 @emph{2}
14288 @tab
14290 ISO 8859-2 (Latin-2) letters allowed in identifiers
14292 @item
14294 @emph{3}
14296 @tab
14298 ISO 8859-3 (Latin-3) letters allowed in identifiers
14300 @item
14302 @emph{4}
14304 @tab
14306 ISO 8859-4 (Latin-4) letters allowed in identifiers
14308 @item
14310 @emph{5}
14312 @tab
14314 ISO 8859-5 (Cyrillic) letters allowed in identifiers
14316 @item
14318 @emph{9}
14320 @tab
14322 ISO 8859-15 (Latin-9) letters allowed in identifiers
14324 @item
14326 @emph{p}
14328 @tab
14330 IBM PC letters (code page 437) allowed in identifiers
14332 @item
14334 @emph{8}
14336 @tab
14338 IBM PC letters (code page 850) allowed in identifiers
14340 @item
14342 @emph{f}
14344 @tab
14346 Full upper-half codes allowed in identifiers
14348 @item
14350 @emph{n}
14352 @tab
14354 No upper-half codes allowed in identifiers
14356 @item
14358 @emph{w}
14360 @tab
14362 Wide-character codes (that is, codes greater than 255)
14363 allowed in identifiers
14365 @end multitable
14368 See @ref{3e,,Foreign Language Representation} for full details on the
14369 implementation of these character sets.
14370 @end table
14372 @geindex -gnatW (gcc)
14375 @table @asis
14377 @item @code{-gnatW@emph{e}}
14379 Specify the method of encoding for wide characters.
14380 @cite{e} is one of the following:
14383 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14384 @item
14386 @emph{h}
14388 @tab
14390 Hex encoding (brackets coding also recognized)
14392 @item
14394 @emph{u}
14396 @tab
14398 Upper half encoding (brackets encoding also recognized)
14400 @item
14402 @emph{s}
14404 @tab
14406 Shift/JIS encoding (brackets encoding also recognized)
14408 @item
14410 @emph{e}
14412 @tab
14414 EUC encoding (brackets encoding also recognized)
14416 @item
14418 @emph{8}
14420 @tab
14422 UTF-8 encoding (brackets encoding also recognized)
14424 @item
14426 @emph{b}
14428 @tab
14430 Brackets encoding only (default value)
14432 @end multitable
14435 For full details on these encoding
14436 methods see @ref{4e,,Wide_Character Encodings}.
14437 Note that brackets coding is always accepted, even if one of the other
14438 options is specified, so for example @emph{-gnatW8} specifies that both
14439 brackets and UTF-8 encodings will be recognized. The units that are
14440 with'ed directly or indirectly will be scanned using the specified
14441 representation scheme, and so if one of the non-brackets scheme is
14442 used, it must be used consistently throughout the program. However,
14443 since brackets encoding is always recognized, it may be conveniently
14444 used in standard libraries, allowing these libraries to be used with
14445 any of the available coding schemes.
14447 Note that brackets encoding only applies to program text. Within comments,
14448 brackets are considered to be normal graphic characters, and bracket sequences
14449 are never recognized as wide characters.
14451 If no @emph{-gnatW?} parameter is present, then the default
14452 representation is normally Brackets encoding only. However, if the
14453 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14454 byte order mark or BOM for UTF-8), then these three characters are
14455 skipped and the default representation for the file is set to UTF-8.
14457 Note that the wide character representation that is specified (explicitly
14458 or by default) for the main program also acts as the default encoding used
14459 for Wide_Text_IO files if not specifically overridden by a WCEM form
14460 parameter.
14461 @end table
14463 When no @emph{-gnatW?} is specified, then characters (other than wide
14464 characters represented using brackets notation) are treated as 8-bit
14465 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14466 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14467 characters in the range 16#00#..16#1F# are not accepted in program text
14468 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14469 in program text, but allowed and ignored in comments. Note in particular
14470 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14471 as an end of line in this default mode. If your source program contains
14472 instances of the NEL character used as a line terminator,
14473 you must use UTF-8 encoding for the whole
14474 source program. In default mode, all lines must be ended by a standard
14475 end of line sequence (CR, CR/LF, or LF).
14477 Note that the convention of simply accepting all upper half characters in
14478 comments means that programs that use standard ASCII for program text, but
14479 UTF-8 encoding for comments are accepted in default mode, providing that the
14480 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14481 This is a common mode for many programs with foreign language comments.
14483 @node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14484 @anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{10b}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{10c}
14485 @subsection File Naming Control
14488 @geindex -gnatk (gcc)
14491 @table @asis
14493 @item @code{-gnatk@emph{n}}
14495 Activates file name 'krunching'. @cite{n}, a decimal integer in the range
14496 1-999, indicates the maximum allowable length of a file name (not
14497 including the @code{.ads} or @code{.adb} extension). The default is not
14498 to enable file name krunching.
14500 For the source file naming rules, @ref{52,,File Naming Rules}.
14501 @end table
14503 @node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14504 @anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{10d}@anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{10e}
14505 @subsection Subprogram Inlining Control
14508 @geindex -gnatn (gcc)
14511 @table @asis
14513 @item @code{-gnatn[12]}
14515 The @cite{n} here is intended to suggest the first syllable of the word 'inline'.
14516 GNAT recognizes and processes @cite{Inline} pragmas. However, for inlining to
14517 actually occur, optimization must be enabled and, by default, inlining of
14518 subprograms across modules is not performed. If you want to additionally
14519 enable inlining of subprograms specified by pragma @cite{Inline} across modules,
14520 you must also specify this switch.
14522 In the absence of this switch, GNAT does not attempt inlining across modules
14523 and does not access the bodies of subprograms for which @cite{pragma Inline} is
14524 specified if they are not in the current unit.
14526 You can optionally specify the inlining level: 1 for moderate inlining across
14527 modules, which is a good compromise between compilation times and performances
14528 at run time, or 2 for full inlining across modules, which may bring about
14529 longer compilation times. If no inlining level is specified, the compiler will
14530 pick it based on the optimization level: 1 for @emph{-O1}, @emph{-O2} or
14531 @emph{-Os} and 2 for @emph{-O3}.
14533 If you specify this switch the compiler will access these bodies,
14534 creating an extra source dependency for the resulting object file, and
14535 where possible, the call will be inlined.
14536 For further details on when inlining is possible
14537 see @ref{10f,,Inlining of Subprograms}.
14538 @end table
14540 @geindex -gnatN (gcc)
14543 @table @asis
14545 @item @code{-gnatN}
14547 This switch activates front-end inlining which also
14548 generates additional dependencies.
14550 When using a gcc-based back end (in practice this means using any version
14551 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
14552 @emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
14553 Historically front end inlining was more extensive than the gcc back end
14554 inlining, but that is no longer the case.
14555 @end table
14557 @node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14558 @anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{110}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{111}
14559 @subsection Auxiliary Output Control
14562 @geindex -gnatt (gcc)
14564 @geindex Writing internal trees
14566 @geindex Internal trees
14567 @geindex writing to file
14570 @table @asis
14572 @item @code{-gnatt}
14574 Causes GNAT to write the internal tree for a unit to a file (with the
14575 extension @code{.adt}.
14576 This not normally required, but is used by separate analysis tools.
14577 Typically
14578 these tools do the necessary compilations automatically, so you should
14579 not have to specify this switch in normal operation.
14580 Note that the combination of switches @emph{-gnatct}
14581 generates a tree in the form required by ASIS applications.
14582 @end table
14584 @geindex -gnatu (gcc)
14587 @table @asis
14589 @item @code{-gnatu}
14591 Print a list of units required by this compilation on @code{stdout}.
14592 The listing includes all units on which the unit being compiled depends
14593 either directly or indirectly.
14594 @end table
14596 @geindex -pass-exit-codes (gcc)
14599 @table @asis
14601 @item @code{-pass-exit-codes}
14603 If this switch is not used, the exit code returned by @emph{gcc} when
14604 compiling multiple files indicates whether all source files have
14605 been successfully used to generate object files or not.
14607 When @emph{-pass-exit-codes} is used, @emph{gcc} exits with an extended
14608 exit status and allows an integrated development environment to better
14609 react to a compilation failure. Those exit status are:
14612 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14613 @item
14615 @emph{5}
14617 @tab
14619 There was an error in at least one source file.
14621 @item
14623 @emph{3}
14625 @tab
14627 At least one source file did not generate an object file.
14629 @item
14631 @emph{2}
14633 @tab
14635 The compiler died unexpectedly (internal error for example).
14637 @item
14639 @emph{0}
14641 @tab
14643 An object file has been generated for every source file.
14645 @end multitable
14647 @end table
14649 @node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
14650 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{112}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{113}
14651 @subsection Debugging Control
14654 @quotation
14656 @geindex Debugging options
14657 @end quotation
14659 @geindex -gnatd (gcc)
14662 @table @asis
14664 @item @code{-gnatd@emph{x}}
14666 Activate internal debugging switches. @cite{x} is a letter or digit, or
14667 string of letters or digits, which specifies the type of debugging
14668 outputs desired. Normally these are used only for internal development
14669 or system debugging purposes. You can find full documentation for these
14670 switches in the body of the @cite{Debug} unit in the compiler source
14671 file @code{debug.adb}.
14672 @end table
14674 @geindex -gnatG (gcc)
14677 @table @asis
14679 @item @code{-gnatG[=@emph{nn}]}
14681 This switch causes the compiler to generate auxiliary output containing
14682 a pseudo-source listing of the generated expanded code. Like most Ada
14683 compilers, GNAT works by first transforming the high level Ada code into
14684 lower level constructs. For example, tasking operations are transformed
14685 into calls to the tasking run-time routines. A unique capability of GNAT
14686 is to list this expanded code in a form very close to normal Ada source.
14687 This is very useful in understanding the implications of various Ada
14688 usage on the efficiency of the generated code. There are many cases in
14689 Ada (e.g., the use of controlled types), where simple Ada statements can
14690 generate a lot of run-time code. By using @emph{-gnatG} you can identify
14691 these cases, and consider whether it may be desirable to modify the coding
14692 approach to improve efficiency.
14694 The optional parameter @cite{nn} if present after -gnatG specifies an
14695 alternative maximum line length that overrides the normal default of 72.
14696 This value is in the range 40-999999, values less than 40 being silently
14697 reset to 40. The equal sign is optional.
14699 The format of the output is very similar to standard Ada source, and is
14700 easily understood by an Ada programmer. The following special syntactic
14701 additions correspond to low level features used in the generated code that
14702 do not have any exact analogies in pure Ada source form. The following
14703 is a partial list of these special constructions. See the spec
14704 of package @cite{Sprint} in file @code{sprint.ads} for a full list.
14706 @geindex -gnatL (gcc)
14708 If the switch @emph{-gnatL} is used in conjunction with
14709 @emph{-gnatG}, then the original source lines are interspersed
14710 in the expanded source (as comment lines with the original line number).
14713 @table @asis
14715 @item @code{new @emph{xxx} [storage_pool = @emph{yyy}]}
14717 Shows the storage pool being used for an allocator.
14719 @item @code{at end @emph{procedure-name};}
14721 Shows the finalization (cleanup) procedure for a scope.
14723 @item @code{(if @emph{expr} then @emph{expr} else @emph{expr})}
14725 Conditional expression equivalent to the @cite{x?y:z} construction in C.
14727 @item @code{@emph{target}^(@emph{source})}
14729 A conversion with floating-point truncation instead of rounding.
14731 @item @code{@emph{target}?(@emph{source})}
14733 A conversion that bypasses normal Ada semantic checking. In particular
14734 enumeration types and fixed-point types are treated simply as integers.
14736 @item @code{@emph{target}?^(@emph{source})}
14738 Combines the above two cases.
14739 @end table
14741 @code{@emph{x} #/ @emph{y}}
14743 @code{@emph{x} #mod @emph{y}}
14745 @code{@emph{x} # @emph{y}}
14748 @table @asis
14750 @item @code{@emph{x} #rem @emph{y}}
14752 A division or multiplication of fixed-point values which are treated as
14753 integers without any kind of scaling.
14755 @item @code{free @emph{expr} [storage_pool = @emph{xxx}]}
14757 Shows the storage pool associated with a @cite{free} statement.
14759 @item @code{[subtype or type declaration]}
14761 Used to list an equivalent declaration for an internally generated
14762 type that is referenced elsewhere in the listing.
14764 @item @code{freeze @emph{type-name} [@emph{actions}]}
14766 Shows the point at which @cite{type-name} is frozen, with possible
14767 associated actions to be performed at the freeze point.
14769 @item @code{reference @emph{itype}}
14771 Reference (and hence definition) to internal type @cite{itype}.
14773 @item @code{@emph{function-name}! (@emph{arg}, @emph{arg}, @emph{arg})}
14775 Intrinsic function call.
14777 @item @code{@emph{label-name} : label}
14779 Declaration of label @cite{labelname}.
14781 @item @code{#$ @emph{subprogram-name}}
14783 An implicit call to a run-time support routine
14784 (to meet the requirement of H.3.1(9) in a
14785 convenient manner).
14787 @item @code{@emph{expr} && @emph{expr} && @emph{expr} ... && @emph{expr}}
14789 A multiple concatenation (same effect as @cite{expr} & @cite{expr} &
14790 @cite{expr}, but handled more efficiently).
14792 @item @code{[constraint_error]}
14794 Raise the @cite{Constraint_Error} exception.
14796 @item @code{@emph{expression}'reference}
14798 A pointer to the result of evaluating @{expression@}.
14800 @item @code{@emph{target-type}!(@emph{source-expression})}
14802 An unchecked conversion of @cite{source-expression} to @cite{target-type}.
14804 @item @code{[@emph{numerator}/@emph{denominator}]}
14806 Used to represent internal real literals (that) have no exact
14807 representation in base 2-16 (for example, the result of compile time
14808 evaluation of the expression 1.0/27.0).
14809 @end table
14810 @end table
14812 @geindex -gnatD (gcc)
14815 @table @asis
14817 @item @code{-gnatD[=nn]}
14819 When used in conjunction with @emph{-gnatG}, this switch causes
14820 the expanded source, as described above for
14821 @emph{-gnatG} to be written to files with names
14822 @code{xxx.dg}, where @code{xxx} is the normal file name,
14823 instead of to the standard output file. For
14824 example, if the source file name is @code{hello.adb}, then a file
14825 @code{hello.adb.dg} will be written.  The debugging
14826 information generated by the @emph{gcc} @emph{-g} switch
14827 will refer to the generated @code{xxx.dg} file. This allows
14828 you to do source level debugging using the generated code which is
14829 sometimes useful for complex code, for example to find out exactly
14830 which part of a complex construction raised an exception. This switch
14831 also suppresses generation of cross-reference information (see
14832 @emph{-gnatx}) since otherwise the cross-reference information
14833 would refer to the @code{.dg} file, which would cause
14834 confusion since this is not the original source file.
14836 Note that @emph{-gnatD} actually implies @emph{-gnatG}
14837 automatically, so it is not necessary to give both options.
14838 In other words @emph{-gnatD} is equivalent to @emph{-gnatDG}).
14840 @geindex -gnatL (gcc)
14842 If the switch @emph{-gnatL} is used in conjunction with
14843 @emph{-gnatDG}, then the original source lines are interspersed
14844 in the expanded source (as comment lines with the original line number).
14846 The optional parameter @cite{nn} if present after -gnatD specifies an
14847 alternative maximum line length that overrides the normal default of 72.
14848 This value is in the range 40-999999, values less than 40 being silently
14849 reset to 40. The equal sign is optional.
14850 @end table
14852 @geindex -gnatr (gcc)
14854 @geindex pragma Restrictions
14857 @table @asis
14859 @item @code{-gnatr}
14861 This switch causes pragma Restrictions to be treated as Restriction_Warnings
14862 so that violation of restrictions causes warnings rather than illegalities.
14863 This is useful during the development process when new restrictions are added
14864 or investigated. The switch also causes pragma Profile to be treated as
14865 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
14866 restriction warnings rather than restrictions.
14867 @end table
14869 @geindex -gnatR (gcc)
14872 @table @asis
14874 @item @code{-gnatR[0|1|2|3[s]]}
14876 This switch controls output from the compiler of a listing showing
14877 representation information for declared types and objects. For
14878 @emph{-gnatR0}, no information is output (equivalent to omitting
14879 the @emph{-gnatR} switch). For @emph{-gnatR1} (which is the default,
14880 so @emph{-gnatR} with no parameter has the same effect), size and alignment
14881 information is listed for declared array and record types. For
14882 @emph{-gnatR2}, size and alignment information is listed for all
14883 declared types and objects. The @cite{Linker_Section} is also listed for any
14884 entity for which the @cite{Linker_Section} is set explicitly or implicitly (the
14885 latter case occurs for objects of a type for which a @cite{Linker_Section}
14886 is set).
14888 Finally @emph{-gnatR3} includes symbolic
14889 expressions for values that are computed at run time for
14890 variant records. These symbolic expressions have a mostly obvious
14891 format with #n being used to represent the value of the n'th
14892 discriminant. See source files @code{repinfo.ads/adb} in the
14893 @cite{GNAT} sources for full details on the format of @emph{-gnatR3}
14894 output. If the switch is followed by an s (e.g., @emph{-gnatR2s}), then
14895 the output is to a file with the name @code{file.rep} where
14896 file is the name of the corresponding source file.
14898 @item @code{-gnatRm[s]}
14900 This form of the switch controls output of subprogram conventions
14901 and parameter passing mechanisms for all subprograms. A following
14902 @cite{s} means output to a file as described above.
14904 Note that it is possible for record components to have zero size. In
14905 this case, the component clause uses an obvious extension of permitted
14906 Ada syntax, for example @cite{at 0 range 0 .. -1}.
14907 @end table
14909 @geindex -gnatS (gcc)
14912 @table @asis
14914 @item @code{-gnatS}
14916 The use of the switch @emph{-gnatS} for an
14917 Ada compilation will cause the compiler to output a
14918 representation of package Standard in a form very
14919 close to standard Ada. It is not quite possible to
14920 do this entirely in standard Ada (since new
14921 numeric base types cannot be created in standard
14922 Ada), but the output is easily
14923 readable to any Ada programmer, and is useful to
14924 determine the characteristics of target dependent
14925 types in package Standard.
14926 @end table
14928 @geindex -gnatx (gcc)
14931 @table @asis
14933 @item @code{-gnatx}
14935 Normally the compiler generates full cross-referencing information in
14936 the @code{ALI} file. This information is used by a number of tools,
14937 including @cite{gnatfind} and @cite{gnatxref}. The @emph{-gnatx} switch
14938 suppresses this information. This saves some space and may slightly
14939 speed up compilation, but means that these tools cannot be used.
14940 @end table
14942 @node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
14943 @anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{114}@anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{115}
14944 @subsection Exception Handling Control
14947 GNAT uses two methods for handling exceptions at run-time. The
14948 @cite{setjmp/longjmp} method saves the context when entering
14949 a frame with an exception handler. Then when an exception is
14950 raised, the context can be restored immediately, without the
14951 need for tracing stack frames. This method provides very fast
14952 exception propagation, but introduces significant overhead for
14953 the use of exception handlers, even if no exception is raised.
14955 The other approach is called 'zero cost' exception handling.
14956 With this method, the compiler builds static tables to describe
14957 the exception ranges. No dynamic code is required when entering
14958 a frame containing an exception handler. When an exception is
14959 raised, the tables are used to control a back trace of the
14960 subprogram invocation stack to locate the required exception
14961 handler. This method has considerably poorer performance for
14962 the propagation of exceptions, but there is no overhead for
14963 exception handlers if no exception is raised. Note that in this
14964 mode and in the context of mixed Ada and C/C++ programming,
14965 to propagate an exception through a C/C++ code, the C/C++ code
14966 must be compiled with the @emph{-funwind-tables} GCC's
14967 option.
14969 The following switches may be used to control which of the
14970 two exception handling methods is used.
14972 @geindex --RTS=sjlj (gnatmake)
14975 @table @asis
14977 @item @code{--RTS=sjlj}
14979 This switch causes the setjmp/longjmp run-time (when available) to be used
14980 for exception handling. If the default
14981 mechanism for the target is zero cost exceptions, then
14982 this switch can be used to modify this default, and must be
14983 used for all units in the partition.
14984 This option is rarely used. One case in which it may be
14985 advantageous is if you have an application where exception
14986 raising is common and the overall performance of the
14987 application is improved by favoring exception propagation.
14988 @end table
14990 @geindex --RTS=zcx (gnatmake)
14992 @geindex Zero Cost Exceptions
14995 @table @asis
14997 @item @code{--RTS=zcx}
14999 This switch causes the zero cost approach to be used
15000 for exception handling. If this is the default mechanism for the
15001 target (see below), then this switch is unneeded. If the default
15002 mechanism for the target is setjmp/longjmp exceptions, then
15003 this switch can be used to modify this default, and must be
15004 used for all units in the partition.
15005 This option can only be used if the zero cost approach
15006 is available for the target in use, otherwise it will generate an error.
15007 @end table
15009 The same option @emph{--RTS} must be used both for @emph{gcc}
15010 and @emph{gnatbind}. Passing this option to @emph{gnatmake}
15011 (@ref{dc,,Switches for gnatmake}) will ensure the required consistency
15012 through the compilation and binding steps.
15014 @node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
15015 @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}
15016 @subsection Units to Sources Mapping Files
15019 @geindex -gnatem (gcc)
15022 @table @asis
15024 @item @code{-gnatem=@emph{path}}
15026 A mapping file is a way to communicate to the compiler two mappings:
15027 from unit names to file names (without any directory information) and from
15028 file names to path names (with full directory information). These mappings
15029 are used by the compiler to short-circuit the path search.
15031 The use of mapping files is not required for correct operation of the
15032 compiler, but mapping files can improve efficiency, particularly when
15033 sources are read over a slow network connection. In normal operation,
15034 you need not be concerned with the format or use of mapping files,
15035 and the @emph{-gnatem} switch is not a switch that you would use
15036 explicitly. It is intended primarily for use by automatic tools such as
15037 @emph{gnatmake} running under the project file facility. The
15038 description here of the format of mapping files is provided
15039 for completeness and for possible use by other tools.
15041 A mapping file is a sequence of sets of three lines. In each set, the
15042 first line is the unit name, in lower case, with @cite{%s} appended
15043 for specs and @cite{%b} appended for bodies; the second line is the
15044 file name; and the third line is the path name.
15046 Example:
15048 @example
15049 main%b
15050 main.2.ada
15051 /gnat/project1/sources/main.2.ada
15052 @end example
15054 When the switch @emph{-gnatem} is specified, the compiler will
15055 create in memory the two mappings from the specified file. If there is
15056 any problem (nonexistent file, truncated file or duplicate entries),
15057 no mapping will be created.
15059 Several @emph{-gnatem} switches may be specified; however, only the
15060 last one on the command line will be taken into account.
15062 When using a project file, @emph{gnatmake} creates a temporary
15063 mapping file and communicates it to the compiler using this switch.
15064 @end table
15066 @node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
15067 @anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{117}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{118}
15068 @subsection Code Generation Control
15071 The GCC technology provides a wide range of target dependent
15072 @code{-m} switches for controlling
15073 details of code generation with respect to different versions of
15074 architectures. This includes variations in instruction sets (e.g.,
15075 different members of the power pc family), and different requirements
15076 for optimal arrangement of instructions (e.g., different members of
15077 the x86 family). The list of available @emph{-m} switches may be
15078 found in the GCC documentation.
15080 Use of these @emph{-m} switches may in some cases result in improved
15081 code performance.
15083 The GNAT technology is tested and qualified without any
15084 @code{-m} switches,
15085 so generally the most reliable approach is to avoid the use of these
15086 switches. However, we generally expect most of these switches to work
15087 successfully with GNAT, and many customers have reported successful
15088 use of these options.
15090 Our general advice is to avoid the use of @emph{-m} switches unless
15091 special needs lead to requirements in this area. In particular,
15092 there is no point in using @emph{-m} switches to improve performance
15093 unless you actually see a performance improvement.
15095 @node Linker Switches,Binding with gnatbind,Compiler Switches,Building Executable Programs with GNAT
15096 @anchor{gnat_ugn/building_executable_programs_with_gnat linker-switches}@anchor{119}@anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{11a}
15097 @section Linker Switches
15100 Linker switches can be specified after @code{-largs} builder switch.
15102 @geindex -fuse-ld=name
15105 @table @asis
15107 @item @code{-fuse-ld=@emph{name}}
15109 Linker to be used. The default is @code{bfd} for @code{ld.bfd},
15110 the alternative being @code{gold} for @code{ld.gold}. The later is
15111 a more recent and faster linker, but only available on GNU/Linux
15112 platforms.
15113 @end table
15115 @node Binding with gnatbind,Linking with gnatlink,Linker Switches,Building Executable Programs with GNAT
15116 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{1d}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{11b}
15117 @section Binding with @cite{gnatbind}
15120 @geindex gnatbind
15122 This chapter describes the GNAT binder, @cite{gnatbind}, which is used
15123 to bind compiled GNAT objects.
15125 Note: to invoke @cite{gnatbind} with a project file, use the @cite{gnat}
15126 driver (see The_GNAT_Driver_and_Project_Files).
15128 The @cite{gnatbind} program performs four separate functions:
15131 @itemize *
15133 @item 
15134 Checks that a program is consistent, in accordance with the rules in
15135 Chapter 10 of the Ada Reference Manual. In particular, error
15136 messages are generated if a program uses inconsistent versions of a
15137 given unit.
15139 @item 
15140 Checks that an acceptable order of elaboration exists for the program
15141 and issues an error message if it cannot find an order of elaboration
15142 that satisfies the rules in Chapter 10 of the Ada Language Manual.
15144 @item 
15145 Generates a main program incorporating the given elaboration order.
15146 This program is a small Ada package (body and spec) that
15147 must be subsequently compiled
15148 using the GNAT compiler. The necessary compilation step is usually
15149 performed automatically by @emph{gnatlink}. The two most important
15150 functions of this program
15151 are to call the elaboration routines of units in an appropriate order
15152 and to call the main program.
15154 @item 
15155 Determines the set of object files required by the given main program.
15156 This information is output in the forms of comments in the generated program,
15157 to be read by the @emph{gnatlink} utility used to link the Ada application.
15158 @end itemize
15160 @menu
15161 * Running gnatbind:: 
15162 * Switches for gnatbind:: 
15163 * Command-Line Access:: 
15164 * Search Paths for gnatbind:: 
15165 * Examples of gnatbind Usage:: 
15167 @end menu
15169 @node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
15170 @anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{11c}@anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{11d}
15171 @subsection Running @cite{gnatbind}
15174 The form of the @cite{gnatbind} command is
15176 @example
15177 $ gnatbind [`switches`] `mainprog`[.ali] [`switches`]
15178 @end example
15180 where @code{mainprog.adb} is the Ada file containing the main program
15181 unit body. @cite{gnatbind} constructs an Ada
15182 package in two files whose names are
15183 @code{b~mainprog.ads}, and @code{b~mainprog.adb}.
15184 For example, if given the
15185 parameter @code{hello.ali}, for a main program contained in file
15186 @code{hello.adb}, the binder output files would be @code{b~hello.ads}
15187 and @code{b~hello.adb}.
15189 When doing consistency checking, the binder takes into consideration
15190 any source files it can locate. For example, if the binder determines
15191 that the given main program requires the package @cite{Pack}, whose
15192 @code{.ALI}
15193 file is @code{pack.ali} and whose corresponding source spec file is
15194 @code{pack.ads}, it attempts to locate the source file @code{pack.ads}
15195 (using the same search path conventions as previously described for the
15196 @emph{gcc} command). If it can locate this source file, it checks that
15197 the time stamps
15198 or source checksums of the source and its references to in @code{ALI} files
15199 match. In other words, any @code{ALI} files that mentions this spec must have
15200 resulted from compiling this version of the source file (or in the case
15201 where the source checksums match, a version close enough that the
15202 difference does not matter).
15204 @geindex Source files
15205 @geindex use by binder
15207 The effect of this consistency checking, which includes source files, is
15208 that the binder ensures that the program is consistent with the latest
15209 version of the source files that can be located at bind time. Editing a
15210 source file without compiling files that depend on the source file cause
15211 error messages to be generated by the binder.
15213 For example, suppose you have a main program @code{hello.adb} and a
15214 package @cite{P}, from file @code{p.ads} and you perform the following
15215 steps:
15218 @itemize *
15220 @item 
15221 Enter @cite{gcc -c hello.adb} to compile the main program.
15223 @item 
15224 Enter @cite{gcc -c p.ads} to compile package @cite{P}.
15226 @item 
15227 Edit file @code{p.ads}.
15229 @item 
15230 Enter @cite{gnatbind hello}.
15231 @end itemize
15233 At this point, the file @code{p.ali} contains an out-of-date time stamp
15234 because the file @code{p.ads} has been edited. The attempt at binding
15235 fails, and the binder generates the following error messages:
15237 @example
15238 error: "hello.adb" must be recompiled ("p.ads" has been modified)
15239 error: "p.ads" has been modified and must be recompiled
15240 @end example
15242 Now both files must be recompiled as indicated, and then the bind can
15243 succeed, generating a main program. You need not normally be concerned
15244 with the contents of this file, but for reference purposes a sample
15245 binder output file is given in @ref{e,,Example of Binder Output File}.
15247 In most normal usage, the default mode of @emph{gnatbind} which is to
15248 generate the main package in Ada, as described in the previous section.
15249 In particular, this means that any Ada programmer can read and understand
15250 the generated main program. It can also be debugged just like any other
15251 Ada code provided the @emph{-g} switch is used for
15252 @emph{gnatbind} and @emph{gnatlink}.
15254 @node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
15255 @anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{11e}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{11f}
15256 @subsection Switches for @emph{gnatbind}
15259 The following switches are available with @cite{gnatbind}; details will
15260 be presented in subsequent sections.
15262 @geindex --version (gnatbind)
15265 @table @asis
15267 @item @code{--version}
15269 Display Copyright and version, then exit disregarding all other options.
15270 @end table
15272 @geindex --help (gnatbind)
15275 @table @asis
15277 @item @code{--help}
15279 If @emph{--version} was not used, display usage, then exit disregarding
15280 all other options.
15281 @end table
15283 @geindex -a (gnatbind)
15286 @table @asis
15288 @item @code{-a}
15290 Indicates that, if supported by the platform, the adainit procedure should
15291 be treated as an initialisation routine by the linker (a constructor). This
15292 is intended to be used by the Project Manager to automatically initialize
15293 shared Stand-Alone Libraries.
15294 @end table
15296 @geindex -aO (gnatbind)
15299 @table @asis
15301 @item @code{-aO}
15303 Specify directory to be searched for ALI files.
15304 @end table
15306 @geindex -aI (gnatbind)
15309 @table @asis
15311 @item @code{-aI}
15313 Specify directory to be searched for source file.
15314 @end table
15316 @geindex -A (gnatbind)
15319 @table @asis
15321 @item @code{-A[=@emph{filename}]}
15323 Output ALI list (to standard output or to the named file).
15324 @end table
15326 @geindex -b (gnatbind)
15329 @table @asis
15331 @item @code{-b}
15333 Generate brief messages to @code{stderr} even if verbose mode set.
15334 @end table
15336 @geindex -c (gnatbind)
15339 @table @asis
15341 @item @code{-c}
15343 Check only, no generation of binder output file.
15344 @end table
15346 @geindex -dnn[k|m] (gnatbind)
15349 @table @asis
15351 @item @code{-d@emph{nn}[k|m]}
15353 This switch can be used to change the default task stack size value
15354 to a specified size @cite{nn}, which is expressed in bytes by default, or
15355 in kilobytes when suffixed with @cite{k} or in megabytes when suffixed
15356 with @cite{m}.
15357 In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15358 in effect, to completing all task specs with
15360 @example
15361 pragma Storage_Size (nn);
15362 @end example
15364 When they do not already have such a pragma.
15365 @end table
15367 @geindex -D (gnatbind)
15370 @table @asis
15372 @item @code{-D@emph{nn}[k|m]}
15374 This switch can be used to change the default secondary stack size value
15375 to a specified size @cite{nn}, which is expressed in bytes by default, or
15376 in kilobytes when suffixed with @cite{k} or in megabytes when suffixed
15377 with @cite{m}.
15379 The secondary stack is used to deal with functions that return a variable
15380 sized result, for example a function returning an unconstrained
15381 String. There are two ways in which this secondary stack is allocated.
15383 For most targets, the secondary stack grows on demand and is allocated
15384 as a chain of blocks in the heap. The -D option is not very
15385 relevant. It only give some control over the size of the allocated
15386 blocks (whose size is the minimum of the default secondary stack size value,
15387 and the actual size needed for the current allocation request).
15389 For certain targets, notably VxWorks 653 and bare board targets,
15390 the secondary stack is allocated by carving off a chunk of the primary task
15391 stack. By default this is a fixed percentage of the primary task stack as
15392 defined by System.Parameter.Sec_Stack_Percentage. This can be overridden per
15393 task using the Secondary_Stack_Size pragma/aspect. The -D option is used to
15394 define the size of the environment task's secondary stack.
15395 @end table
15397 @geindex -e (gnatbind)
15400 @table @asis
15402 @item @code{-e}
15404 Output complete list of elaboration-order dependencies.
15405 @end table
15407 @geindex -Ea (gnatbind)
15410 @table @asis
15412 @item @code{-Ea}
15414 Store tracebacks in exception occurrences when the target supports it.
15415 The "a" is for "address"; tracebacks will contain hexadecimal addresses,
15416 unless symbolic tracebacks are enabled.
15418 See also the packages @cite{GNAT.Traceback} and
15419 @cite{GNAT.Traceback.Symbolic} for more information.
15420 Note that on x86 ports, you must not use @emph{-fomit-frame-pointer}
15421 @emph{gcc} option.
15422 @end table
15424 @geindex -Es (gnatbind)
15427 @table @asis
15429 @item @code{-Es}
15431 Store tracebacks in exception occurrences when the target supports it.
15432 The "s" is for "symbolic"; symbolic tracebacks are enabled.
15433 @end table
15435 @geindex -E (gnatbind)
15438 @table @asis
15440 @item @code{-E}
15442 Currently the same as @cite{-Ea}.
15443 @end table
15445 @geindex -f (gnatbind)
15448 @table @asis
15450 @item @code{-f@emph{elab-order}}
15452 Force elaboration order.
15453 @end table
15455 @geindex -F (gnatbind)
15458 @table @asis
15460 @item @code{-F}
15462 Force the checks of elaboration flags. @emph{gnatbind} does not normally
15463 generate checks of elaboration flags for the main executable, except when
15464 a Stand-Alone Library is used. However, there are cases when this cannot be
15465 detected by gnatbind. An example is importing an interface of a Stand-Alone
15466 Library through a pragma Import and only specifying through a linker switch
15467 this Stand-Alone Library. This switch is used to guarantee that elaboration
15468 flag checks are generated.
15469 @end table
15471 @geindex -h (gnatbind)
15474 @table @asis
15476 @item @code{-h}
15478 Output usage (help) information.
15480 @geindex -H32 (gnatbind)
15482 @item @code{-H32}
15484 Use 32-bit allocations for @cite{__gnat_malloc} (and thus for access types).
15485 For further details see @ref{120,,Dynamic Allocation Control}.
15487 @geindex -H64 (gnatbind)
15489 @geindex __gnat_malloc
15491 @item @code{-H64}
15493 Use 64-bit allocations for @cite{__gnat_malloc} (and thus for access types).
15494 For further details see @ref{120,,Dynamic Allocation Control}.
15496 @geindex -I (gnatbind)
15498 @item @code{-I}
15500 Specify directory to be searched for source and ALI files.
15502 @geindex -I- (gnatbind)
15504 @item @code{-I-}
15506 Do not look for sources in the current directory where @cite{gnatbind} was
15507 invoked, and do not look for ALI files in the directory containing the
15508 ALI file named in the @cite{gnatbind} command line.
15510 @geindex -l (gnatbind)
15512 @item @code{-l}
15514 Output chosen elaboration order.
15516 @geindex -L (gnatbind)
15518 @item @code{-L@emph{xxx}}
15520 Bind the units for library building. In this case the adainit and
15521 adafinal procedures (@ref{b4,,Binding with Non-Ada Main Programs})
15522 are renamed to @cite{xxx`init and `xxx`final. Implies -n. (:ref:`GNAT_and_Libraries}, for more details.)
15524 @geindex -M (gnatbind)
15526 @item @code{-M@emph{xyz}}
15528 Rename generated main program from main to xyz. This option is
15529 supported on cross environments only.
15531 @geindex -m (gnatbind)
15533 @item @code{-m@emph{n}}
15535 Limit number of detected errors or warnings to @cite{n}, where @cite{n} is
15536 in the range 1..999999. The default value if no switch is
15537 given is 9999. If the number of warnings reaches this limit, then a
15538 message is output and further warnings are suppressed, the bind
15539 continues in this case. If the number of errors reaches this
15540 limit, then a message is output and the bind is abandoned.
15541 A value of zero means that no limit is enforced. The equal
15542 sign is optional.
15544 @geindex -n (gnatbind)
15546 @item @code{-n}
15548 No main program.
15550 @geindex -nostdinc (gnatbind)
15552 @item @code{-nostdinc}
15554 Do not look for sources in the system default directory.
15556 @geindex -nostdlib (gnatbind)
15558 @item @code{-nostdlib}
15560 Do not look for library files in the system default directory.
15562 @geindex --RTS (gnatbind)
15564 @item @code{--RTS=@emph{rts-path}}
15566 Specifies the default location of the runtime library. Same meaning as the
15567 equivalent @emph{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
15569 @geindex -o (gnatbind)
15571 @item @code{-o @emph{file}}
15573 Name the output file @cite{file} (default is @code{b~`xxx}.adb`).
15574 Note that if this option is used, then linking must be done manually,
15575 gnatlink cannot be used.
15577 @geindex -O (gnatbind)
15579 @item @code{-O[=@emph{filename}]}
15581 Output object list (to standard output or to the named file).
15583 @geindex -p (gnatbind)
15585 @item @code{-p}
15587 Pessimistic (worst-case) elaboration order.
15589 @geindex -P (gnatbind)
15591 @item @code{-P}
15593 Generate binder file suitable for CodePeer.
15595 @geindex -R (gnatbind)
15597 @item @code{-R}
15599 Output closure source list, which includes all non-run-time units that are
15600 included in the bind.
15602 @geindex -Ra (gnatbind)
15604 @item @code{-Ra}
15606 Like @emph{-R} but the list includes run-time units.
15608 @geindex -s (gnatbind)
15610 @item @code{-s}
15612 Require all source files to be present.
15614 @geindex -S (gnatbind)
15616 @item @code{-S@emph{xxx}}
15618 Specifies the value to be used when detecting uninitialized scalar
15619 objects with pragma Initialize_Scalars.
15620 The @cite{xxx} string specified with the switch is one of:
15623 @itemize *
15625 @item 
15626 @code{in} for an invalid value.
15628 If zero is invalid for the discrete type in question,
15629 then the scalar value is set to all zero bits.
15630 For signed discrete types, the largest possible negative value of
15631 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15632 For unsigned discrete types, the underlying scalar value is set to all
15633 one bits. For floating-point types, a NaN value is set
15634 (see body of package System.Scalar_Values for exact values).
15636 @item 
15637 @code{lo} for low value.
15639 If zero is invalid for the discrete type in question,
15640 then the scalar value is set to all zero bits.
15641 For signed discrete types, the largest possible negative value of
15642 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15643 For unsigned discrete types, the underlying scalar value is set to all
15644 zero bits. For floating-point, a small value is set
15645 (see body of package System.Scalar_Values for exact values).
15647 @item 
15648 @code{hi} for high value.
15650 If zero is invalid for the discrete type in question,
15651 then the scalar value is set to all one bits.
15652 For signed discrete types, the largest possible positive value of
15653 the underlying scalar is set (i.e. a zero bit followed by all one bits).
15654 For unsigned discrete types, the underlying scalar value is set to all
15655 one bits. For floating-point, a large value is set
15656 (see body of package System.Scalar_Values for exact values).
15658 @item 
15659 @cite{xx} for hex value (two hex digits).
15661 The underlying scalar is set to a value consisting of repeated bytes, whose
15662 value corresponds to the given value. For example if @code{BF} is given,
15663 then a 32-bit scalar value will be set to the bit patterm @code{16#BFBFBFBF#}.
15664 @end itemize
15666 @geindex GNAT_INIT_SCALARS
15668 In addition, you can specify @emph{-Sev} to indicate that the value is
15669 to be set at run time. In this case, the program will look for an environment
15670 variable of the form @code{GNAT_INIT_SCALARS=@emph{yy}}, where @cite{yy} is one
15671 of @emph{in/lo/hi/`xx*` with the same meanings as above.
15672 If no environment variable is found, or if it does not have a valid value,
15673 then the default is *in} (invalid values).
15674 @end table
15676 @geindex -static (gnatbind)
15679 @table @asis
15681 @item @code{-static}
15683 Link against a static GNAT run time.
15685 @geindex -shared (gnatbind)
15687 @item @code{-shared}
15689 Link against a shared GNAT run time when available.
15691 @geindex -t (gnatbind)
15693 @item @code{-t}
15695 Tolerate time stamp and other consistency errors.
15697 @geindex -T (gnatbind)
15699 @item @code{-T@emph{n}}
15701 Set the time slice value to @cite{n} milliseconds. If the system supports
15702 the specification of a specific time slice value, then the indicated value
15703 is used. If the system does not support specific time slice values, but
15704 does support some general notion of round-robin scheduling, then any
15705 nonzero value will activate round-robin scheduling.
15707 A value of zero is treated specially. It turns off time
15708 slicing, and in addition, indicates to the tasking run time that the
15709 semantics should match as closely as possible the Annex D
15710 requirements of the Ada RM, and in particular sets the default
15711 scheduling policy to @cite{FIFO_Within_Priorities}.
15713 @geindex -u (gnatbind)
15715 @item @code{-u@emph{n}}
15717 Enable dynamic stack usage, with @cite{n} results stored and displayed
15718 at program termination. A result is generated when a task
15719 terminates. Results that can't be stored are displayed on the fly, at
15720 task termination. This option is currently not supported on Itanium
15721 platforms. (See @ref{121,,Dynamic Stack Usage Analysis} for details.)
15723 @geindex -v (gnatbind)
15725 @item @code{-v}
15727 Verbose mode. Write error messages, header, summary output to
15728 @code{stdout}.
15730 @geindex -V (gnatbind)
15732 @item @code{-V@emph{key}=@emph{value}}
15734 Store the given association of @cite{key} to @cite{value} in the bind environment.
15735 Values stored this way can be retrieved at run time using
15736 @cite{GNAT.Bind_Environment}.
15738 @geindex -w (gnatbind)
15740 @item @code{-w@emph{x}}
15742 Warning mode; @cite{x} = s/e for suppress/treat as error.
15744 @geindex -Wx (gnatbind)
15746 @item @code{-Wx@emph{e}}
15748 Override default wide character encoding for standard Text_IO files.
15750 @geindex -x (gnatbind)
15752 @item @code{-x}
15754 Exclude source files (check object consistency only).
15756 @geindex -Xnnn (gnatbind)
15758 @item @code{-X@emph{nnn}}
15760 Set default exit status value, normally 0 for POSIX compliance.
15762 @geindex -y (gnatbind)
15764 @item @code{-y}
15766 Enable leap seconds support in @cite{Ada.Calendar} and its children.
15768 @geindex -z (gnatbind)
15770 @item @code{-z}
15772 No main subprogram.
15773 @end table
15775 You may obtain this listing of switches by running @cite{gnatbind} with
15776 no arguments.
15778 @menu
15779 * Consistency-Checking Modes:: 
15780 * Binder Error Message Control:: 
15781 * Elaboration Control:: 
15782 * Output Control:: 
15783 * Dynamic Allocation Control:: 
15784 * Binding with Non-Ada Main Programs:: 
15785 * Binding Programs with No Main Subprogram:: 
15787 @end menu
15789 @node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
15790 @anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{122}@anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{123}
15791 @subsubsection Consistency-Checking Modes
15794 As described earlier, by default @cite{gnatbind} checks
15795 that object files are consistent with one another and are consistent
15796 with any source files it can locate. The following switches control binder
15797 access to sources.
15799 @quotation
15801 @geindex -s (gnatbind)
15802 @end quotation
15805 @table @asis
15807 @item @code{-s}
15809 Require source files to be present. In this mode, the binder must be
15810 able to locate all source files that are referenced, in order to check
15811 their consistency. In normal mode, if a source file cannot be located it
15812 is simply ignored. If you specify this switch, a missing source
15813 file is an error.
15815 @geindex -Wx (gnatbind)
15817 @item @code{-Wx@emph{e}}
15819 Override default wide character encoding for standard Text_IO files.
15820 Normally the default wide character encoding method used for standard
15821 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
15822 the main source input (see description of switch
15823 @emph{-gnatWx} for the compiler). The
15824 use of this switch for the binder (which has the same set of
15825 possible arguments) overrides this default as specified.
15827 @geindex -x (gnatbind)
15829 @item @code{-x}
15831 Exclude source files. In this mode, the binder only checks that ALI
15832 files are consistent with one another. Source files are not accessed.
15833 The binder runs faster in this mode, and there is still a guarantee that
15834 the resulting program is self-consistent.
15835 If a source file has been edited since it was last compiled, and you
15836 specify this switch, the binder will not detect that the object
15837 file is out of date with respect to the source file. Note that this is the
15838 mode that is automatically used by @emph{gnatmake} because in this
15839 case the checking against sources has already been performed by
15840 @emph{gnatmake} in the course of compilation (i.e., before binding).
15841 @end table
15843 @node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
15844 @anchor{gnat_ugn/building_executable_programs_with_gnat id36}@anchor{124}@anchor{gnat_ugn/building_executable_programs_with_gnat binder-error-message-control}@anchor{125}
15845 @subsubsection Binder Error Message Control
15848 The following switches provide control over the generation of error
15849 messages from the binder:
15851 @quotation
15853 @geindex -v (gnatbind)
15854 @end quotation
15857 @table @asis
15859 @item @code{-v}
15861 Verbose mode. In the normal mode, brief error messages are generated to
15862 @code{stderr}. If this switch is present, a header is written
15863 to @code{stdout} and any error messages are directed to @code{stdout}.
15864 All that is written to @code{stderr} is a brief summary message.
15866 @geindex -b (gnatbind)
15868 @item @code{-b}
15870 Generate brief error messages to @code{stderr} even if verbose mode is
15871 specified. This is relevant only when used with the
15872 @emph{-v} switch.
15874 @geindex -m (gnatbind)
15876 @item @code{-m@emph{n}}
15878 Limits the number of error messages to @cite{n}, a decimal integer in the
15879 range 1-999. The binder terminates immediately if this limit is reached.
15881 @geindex -M (gnatbind)
15883 @item @code{-M@emph{xxx}}
15885 Renames the generated main program from @cite{main} to @cite{xxx}.
15886 This is useful in the case of some cross-building environments, where
15887 the actual main program is separate from the one generated
15888 by @cite{gnatbind}.
15890 @geindex -ws (gnatbind)
15892 @geindex Warnings
15894 @item @code{-ws}
15896 Suppress all warning messages.
15898 @geindex -we (gnatbind)
15900 @item @code{-we}
15902 Treat any warning messages as fatal errors.
15904 @geindex -t (gnatbind)
15906 @geindex Time stamp checks
15907 @geindex in binder
15909 @geindex Binder consistency checks
15911 @geindex Consistency checks
15912 @geindex in binder
15914 @item @code{-t}
15916 The binder performs a number of consistency checks including:
15919 @itemize *
15921 @item 
15922 Check that time stamps of a given source unit are consistent
15924 @item 
15925 Check that checksums of a given source unit are consistent
15927 @item 
15928 Check that consistent versions of @cite{GNAT} were used for compilation
15930 @item 
15931 Check consistency of configuration pragmas as required
15932 @end itemize
15934 Normally failure of such checks, in accordance with the consistency
15935 requirements of the Ada Reference Manual, causes error messages to be
15936 generated which abort the binder and prevent the output of a binder
15937 file and subsequent link to obtain an executable.
15939 The @emph{-t} switch converts these error messages
15940 into warnings, so that
15941 binding and linking can continue to completion even in the presence of such
15942 errors. The result may be a failed link (due to missing symbols), or a
15943 non-functional executable which has undefined semantics.
15945 @cartouche
15946 @quotation Note 
15947 This means that @emph{-t} should be used only in unusual situations,
15948 with extreme care.
15949 @end quotation
15950 @end cartouche
15951 @end table
15953 @node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
15954 @anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{126}@anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{127}
15955 @subsubsection Elaboration Control
15958 The following switches provide additional control over the elaboration
15959 order. For full details see @ref{f,,Elaboration Order Handling in GNAT}.
15961 @geindex -f (gnatbind)
15964 @table @asis
15966 @item @code{-f@emph{elab-order}}
15968 Force elaboration order.
15970 @cite{elab-order} should be the name of a "forced elaboration order file", that
15971 is, a text file containing library item names, one per line. A name of the
15972 form "some.unit%s" or "some.unit (spec)" denotes the spec of Some.Unit. A
15973 name of the form "some.unit%b" or "some.unit (body)" denotes the body of
15974 Some.Unit. Each pair of lines is taken to mean that there is an elaboration
15975 dependence of the second line on the first. For example, if the file
15976 contains:
15978 @example
15979 this (spec)
15980 this (body)
15981 that (spec)
15982 that (body)
15983 @end example
15985 then the spec of This will be elaborated before the body of This, and the
15986 body of This will be elaborated before the spec of That, and the spec of That
15987 will be elaborated before the body of That. The first and last of these three
15988 dependences are already required by Ada rules, so this file is really just
15989 forcing the body of This to be elaborated before the spec of That.
15991 The given order must be consistent with Ada rules, or else @cite{gnatbind} will
15992 give elaboration cycle errors. For example, if you say x (body) should be
15993 elaborated before x (spec), there will be a cycle, because Ada rules require
15994 x (spec) to be elaborated before x (body); you can't have the spec and body
15995 both elaborated before each other.
15997 If you later add "with That;" to the body of This, there will be a cycle, in
15998 which case you should erase either "this (body)" or "that (spec)" from the
15999 above forced elaboration order file.
16001 Blank lines and Ada-style comments are ignored. Unit names that do not exist
16002 in the program are ignored. Units in the GNAT predefined library are also
16003 ignored.
16005 @geindex -p (gnatbind)
16007 @item @code{-p}
16009 Normally the binder attempts to choose an elaboration order that is
16010 likely to minimize the likelihood of an elaboration order error resulting
16011 in raising a @cite{Program_Error} exception. This switch reverses the
16012 action of the binder, and requests that it deliberately choose an order
16013 that is likely to maximize the likelihood of an elaboration error.
16014 This is useful in ensuring portability and avoiding dependence on
16015 accidental fortuitous elaboration ordering.
16017 Normally it only makes sense to use the @emph{-p}
16018 switch if dynamic
16019 elaboration checking is used (@emph{-gnatE} switch used for compilation).
16020 This is because in the default static elaboration mode, all necessary
16021 @cite{Elaborate} and @cite{Elaborate_All} pragmas are implicitly inserted.
16022 These implicit pragmas are still respected by the binder in
16023 @emph{-p} mode, so a
16024 safe elaboration order is assured.
16026 Note that @emph{-p} is not intended for
16027 production use; it is more for debugging/experimental use.
16028 @end table
16030 @node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
16031 @anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{128}@anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{129}
16032 @subsubsection Output Control
16035 The following switches allow additional control over the output
16036 generated by the binder.
16038 @quotation
16040 @geindex -c (gnatbind)
16041 @end quotation
16044 @table @asis
16046 @item @code{-c}
16048 Check only. Do not generate the binder output file. In this mode the
16049 binder performs all error checks but does not generate an output file.
16051 @geindex -e (gnatbind)
16053 @item @code{-e}
16055 Output complete list of elaboration-order dependencies, showing the
16056 reason for each dependency. This output can be rather extensive but may
16057 be useful in diagnosing problems with elaboration order. The output is
16058 written to @code{stdout}.
16060 @geindex -h (gnatbind)
16062 @item @code{-h}
16064 Output usage information. The output is written to @code{stdout}.
16066 @geindex -K (gnatbind)
16068 @item @code{-K}
16070 Output linker options to @code{stdout}. Includes library search paths,
16071 contents of pragmas Ident and Linker_Options, and libraries added
16072 by @cite{gnatbind}.
16074 @geindex -l (gnatbind)
16076 @item @code{-l}
16078 Output chosen elaboration order. The output is written to @code{stdout}.
16080 @geindex -O (gnatbind)
16082 @item @code{-O}
16084 Output full names of all the object files that must be linked to provide
16085 the Ada component of the program. The output is written to @code{stdout}.
16086 This list includes the files explicitly supplied and referenced by the user
16087 as well as implicitly referenced run-time unit files. The latter are
16088 omitted if the corresponding units reside in shared libraries. The
16089 directory names for the run-time units depend on the system configuration.
16091 @geindex -o (gnatbind)
16093 @item @code{-o @emph{file}}
16095 Set name of output file to @cite{file} instead of the normal
16096 @code{b~`mainprog}.adb` default. Note that @cite{file} denote the Ada
16097 binder generated body filename.
16098 Note that if this option is used, then linking must be done manually.
16099 It is not possible to use gnatlink in this case, since it cannot locate
16100 the binder file.
16102 @geindex -r (gnatbind)
16104 @item @code{-r}
16106 Generate list of @cite{pragma Restrictions} that could be applied to
16107 the current unit. This is useful for code audit purposes, and also may
16108 be used to improve code generation in some cases.
16109 @end table
16111 @node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
16112 @anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{120}@anchor{gnat_ugn/building_executable_programs_with_gnat id39}@anchor{12a}
16113 @subsubsection Dynamic Allocation Control
16116 The heap control switches -- @emph{-H32} and @emph{-H64} --
16117 determine whether dynamic allocation uses 32-bit or 64-bit memory.
16118 They only affect compiler-generated allocations via @cite{__gnat_malloc};
16119 explicit calls to @cite{malloc} and related functions from the C
16120 run-time library are unaffected.
16123 @table @asis
16125 @item @code{-H32}
16127 Allocate memory on 32-bit heap
16129 @item @code{-H64}
16131 Allocate memory on 64-bit heap.  This is the default
16132 unless explicitly overridden by a @cite{'Size} clause on the access type.
16133 @end table
16135 These switches are only effective on VMS platforms.
16137 @node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
16138 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-non-ada-main-programs}@anchor{b4}@anchor{gnat_ugn/building_executable_programs_with_gnat id40}@anchor{12b}
16139 @subsubsection Binding with Non-Ada Main Programs
16142 The description so far has assumed that the main
16143 program is in Ada, and that the task of the binder is to generate a
16144 corresponding function @cite{main} that invokes this Ada main
16145 program. GNAT also supports the building of executable programs where
16146 the main program is not in Ada, but some of the called routines are
16147 written in Ada and compiled using GNAT (@ref{44,,Mixed Language Programming}).
16148 The following switch is used in this situation:
16150 @quotation
16152 @geindex -n (gnatbind)
16153 @end quotation
16156 @table @asis
16158 @item @code{-n}
16160 No main program. The main program is not in Ada.
16161 @end table
16163 In this case, most of the functions of the binder are still required,
16164 but instead of generating a main program, the binder generates a file
16165 containing the following callable routines:
16167 @quotation
16169 @geindex adainit
16172 @table @asis
16174 @item @emph{adainit}
16176 You must call this routine to initialize the Ada part of the program by
16177 calling the necessary elaboration routines. A call to @cite{adainit} is
16178 required before the first call to an Ada subprogram.
16180 Note that it is assumed that the basic execution environment must be setup
16181 to be appropriate for Ada execution at the point where the first Ada
16182 subprogram is called. In particular, if the Ada code will do any
16183 floating-point operations, then the FPU must be setup in an appropriate
16184 manner. For the case of the x86, for example, full precision mode is
16185 required. The procedure GNAT.Float_Control.Reset may be used to ensure
16186 that the FPU is in the right state.
16187 @end table
16189 @geindex adafinal
16192 @table @asis
16194 @item @emph{adafinal}
16196 You must call this routine to perform any library-level finalization
16197 required by the Ada subprograms. A call to @cite{adafinal} is required
16198 after the last call to an Ada subprogram, and before the program
16199 terminates.
16200 @end table
16201 @end quotation
16203 @geindex -n (gnatbind)
16205 @geindex Binder
16206 @geindex multiple input files
16208 If the @emph{-n} switch
16209 is given, more than one ALI file may appear on
16210 the command line for @cite{gnatbind}. The normal @emph{closure}
16211 calculation is performed for each of the specified units. Calculating
16212 the closure means finding out the set of units involved by tracing
16213 @emph{with} references. The reason it is necessary to be able to
16214 specify more than one ALI file is that a given program may invoke two or
16215 more quite separate groups of Ada units.
16217 The binder takes the name of its output file from the last specified ALI
16218 file, unless overridden by the use of the @emph{-o file}.
16220 @geindex -o (gnatbind)
16222 The output is an Ada unit in source form that can be compiled with GNAT.
16223 This compilation occurs automatically as part of the @emph{gnatlink}
16224 processing.
16226 Currently the GNAT run time requires a FPU using 80 bits mode
16227 precision. Under targets where this is not the default it is required to
16228 call GNAT.Float_Control.Reset before using floating point numbers (this
16229 include float computation, float input and output) in the Ada code. A
16230 side effect is that this could be the wrong mode for the foreign code
16231 where floating point computation could be broken after this call.
16233 @node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
16234 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-programs-with-no-main-subprogram}@anchor{12c}@anchor{gnat_ugn/building_executable_programs_with_gnat id41}@anchor{12d}
16235 @subsubsection Binding Programs with No Main Subprogram
16238 It is possible to have an Ada program which does not have a main
16239 subprogram. This program will call the elaboration routines of all the
16240 packages, then the finalization routines.
16242 The following switch is used to bind programs organized in this manner:
16244 @quotation
16246 @geindex -z (gnatbind)
16247 @end quotation
16250 @table @asis
16252 @item @code{-z}
16254 Normally the binder checks that the unit name given on the command line
16255 corresponds to a suitable main subprogram. When this switch is used,
16256 a list of ALI files can be given, and the execution of the program
16257 consists of elaboration of these units in an appropriate order. Note
16258 that the default wide character encoding method for standard Text_IO
16259 files is always set to Brackets if this switch is set (you can use
16260 the binder switch
16261 @emph{-Wx} to override this default).
16262 @end table
16264 @node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
16265 @anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{12e}@anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{12f}
16266 @subsection Command-Line Access
16269 The package @cite{Ada.Command_Line} provides access to the command-line
16270 arguments and program name. In order for this interface to operate
16271 correctly, the two variables
16273 @example
16274 int gnat_argc;
16275 char **gnat_argv;
16276 @end example
16278 @geindex gnat_argv
16280 @geindex gnat_argc
16282 are declared in one of the GNAT library routines. These variables must
16283 be set from the actual @cite{argc} and @cite{argv} values passed to the
16284 main program. With no @emph{n} present, @cite{gnatbind}
16285 generates the C main program to automatically set these variables.
16286 If the @emph{n} switch is used, there is no automatic way to
16287 set these variables. If they are not set, the procedures in
16288 @cite{Ada.Command_Line} will not be available, and any attempt to use
16289 them will raise @cite{Constraint_Error}. If command line access is
16290 required, your main program must set @cite{gnat_argc} and
16291 @cite{gnat_argv} from the @cite{argc} and @cite{argv} values passed to
16294 @node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
16295 @anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-for-gnatbind}@anchor{8c}@anchor{gnat_ugn/building_executable_programs_with_gnat id43}@anchor{130}
16296 @subsection Search Paths for @cite{gnatbind}
16299 The binder takes the name of an ALI file as its argument and needs to
16300 locate source files as well as other ALI files to verify object consistency.
16302 For source files, it follows exactly the same search rules as @emph{gcc}
16303 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
16304 directories searched are:
16307 @itemize *
16309 @item 
16310 The directory containing the ALI file named in the command line, unless
16311 the switch @emph{-I-} is specified.
16313 @item 
16314 All directories specified by @emph{-I}
16315 switches on the @cite{gnatbind}
16316 command line, in the order given.
16318 @geindex ADA_PRJ_OBJECTS_FILE
16320 @item 
16321 Each of the directories listed in the text file whose name is given
16322 by the 
16323 @geindex ADA_PRJ_OBJECTS_FILE
16324 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16325 @code{ADA_PRJ_OBJECTS_FILE} environment variable.
16327 @geindex ADA_PRJ_OBJECTS_FILE
16328 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16329 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
16330 driver when project files are used. It should not normally be set
16331 by other means.
16333 @geindex ADA_OBJECTS_PATH
16335 @item 
16336 Each of the directories listed in the value of the
16337 @geindex ADA_OBJECTS_PATH
16338 @geindex environment variable; ADA_OBJECTS_PATH
16339 @code{ADA_OBJECTS_PATH} environment variable.
16340 Construct this value
16341 exactly as the 
16342 @geindex PATH
16343 @geindex environment variable; PATH
16344 @code{PATH} environment variable: a list of directory
16345 names separated by colons (semicolons when working with the NT version
16346 of GNAT).
16348 @item 
16349 The content of the @code{ada_object_path} file which is part of the GNAT
16350 installation tree and is used to store standard libraries such as the
16351 GNAT Run Time Library (RTL) unless the switch @emph{-nostdlib} is
16352 specified. See @ref{87,,Installing a library}
16353 @end itemize
16355 @geindex -I (gnatbind)
16357 @geindex -aI (gnatbind)
16359 @geindex -aO (gnatbind)
16361 In the binder the switch @emph{-I}
16362 is used to specify both source and
16363 library file paths. Use @emph{-aI}
16364 instead if you want to specify
16365 source paths only, and @emph{-aO}
16366 if you want to specify library paths
16367 only. This means that for the binder
16368 @code{-I@emph{dir}} is equivalent to
16369 @code{-aI@emph{dir}}
16370 @code{-aO`@emph{dir}}.
16371 The binder generates the bind file (a C language source file) in the
16372 current working directory.
16374 @geindex Ada
16376 @geindex System
16378 @geindex Interfaces
16380 @geindex GNAT
16382 The packages @cite{Ada}, @cite{System}, and @cite{Interfaces} and their
16383 children make up the GNAT Run-Time Library, together with the package
16384 GNAT and its children, which contain a set of useful additional
16385 library functions provided by GNAT. The sources for these units are
16386 needed by the compiler and are kept together in one directory. The ALI
16387 files and object files generated by compiling the RTL are needed by the
16388 binder and the linker and are kept together in one directory, typically
16389 different from the directory containing the sources. In a normal
16390 installation, you need not specify these directory names when compiling
16391 or binding. Either the environment variables or the built-in defaults
16392 cause these files to be found.
16394 Besides simplifying access to the RTL, a major use of search paths is
16395 in compiling sources from multiple directories. This can make
16396 development environments much more flexible.
16398 @node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16399 @anchor{gnat_ugn/building_executable_programs_with_gnat id44}@anchor{131}@anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatbind-usage}@anchor{132}
16400 @subsection Examples of @cite{gnatbind} Usage
16403 Here are some examples of @cite{gnatbind} invovations:
16405 @quotation
16407 @example
16408 gnatbind hello
16409 @end example
16411 The main program @cite{Hello} (source program in @code{hello.adb}) is
16412 bound using the standard switch settings. The generated main program is
16413 @code{b~hello.adb}. This is the normal, default use of the binder.
16415 @example
16416 gnatbind hello -o mainprog.adb
16417 @end example
16419 The main program @cite{Hello} (source program in @code{hello.adb}) is
16420 bound using the standard switch settings. The generated main program is
16421 @code{mainprog.adb} with the associated spec in
16422 @code{mainprog.ads}. Note that you must specify the body here not the
16423 spec. Note that if this option is used, then linking must be done manually,
16424 since gnatlink will not be able to find the generated file.
16425 @end quotation
16427 @node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16428 @anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{133}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{1e}
16429 @section Linking with @emph{gnatlink}
16432 @geindex gnatlink
16434 This chapter discusses @emph{gnatlink}, a tool that links
16435 an Ada program and builds an executable file. This utility
16436 invokes the system linker (via the @emph{gcc} command)
16437 with a correct list of object files and library references.
16438 @emph{gnatlink} automatically determines the list of files and
16439 references for the Ada part of a program. It uses the binder file
16440 generated by the @emph{gnatbind} to determine this list.
16442 Note: to invoke @cite{gnatlink} with a project file, use the @cite{gnat}
16443 driver (see The_GNAT_Driver_and_Project_Files).
16445 @menu
16446 * Running gnatlink:: 
16447 * Switches for gnatlink:: 
16449 @end menu
16451 @node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16452 @anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{134}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{135}
16453 @subsection Running @emph{gnatlink}
16456 The form of the @emph{gnatlink} command is
16458 @example
16459 $ gnatlink [`switches`] `mainprog`[.ali]
16460            [`non-Ada objects`] [`linker options`]
16461 @end example
16463 The arguments of @emph{gnatlink} (switches, main @code{ALI} file,
16464 non-Ada objects
16465 or linker options) may be in any order, provided that no non-Ada object may
16466 be mistaken for a main @code{ALI} file.
16467 Any file name @code{F} without the @code{.ali}
16468 extension will be taken as the main @code{ALI} file if a file exists
16469 whose name is the concatenation of @code{F} and @code{.ali}.
16471 @code{mainprog.ali} references the ALI file of the main program.
16472 The @code{.ali} extension of this file can be omitted. From this
16473 reference, @emph{gnatlink} locates the corresponding binder file
16474 @code{b~mainprog.adb} and, using the information in this file along
16475 with the list of non-Ada objects and linker options, constructs a
16476 linker command file to create the executable.
16478 The arguments other than the @emph{gnatlink} switches and the main
16479 @code{ALI} file are passed to the linker uninterpreted.
16480 They typically include the names of
16481 object files for units written in other languages than Ada and any library
16482 references required to resolve references in any of these foreign language
16483 units, or in @cite{Import} pragmas in any Ada units.
16485 @cite{linker options} is an optional list of linker specific
16486 switches.
16487 The default linker called by gnatlink is @emph{gcc} which in
16488 turn calls the appropriate system linker.
16490 One useful option for the linker is @emph{-s}: it reduces the size of the
16491 executable by removing all symbol table and relocation information from the
16492 executable.
16494 Standard options for the linker such as @emph{-lmy_lib} or
16495 @emph{-Ldir} can be added as is.
16496 For options that are not recognized by
16497 @emph{gcc} as linker options, use the @emph{gcc} switches
16498 @emph{-Xlinker} or @emph{-Wl,}.
16500 Refer to the GCC documentation for
16501 details.
16503 Here is an example showing how to generate a linker map:
16505 @example
16506 $ gnatlink my_prog -Wl,-Map,MAPFILE
16507 @end example
16509 Using @cite{linker options} it is possible to set the program stack and
16510 heap size.
16511 See @ref{136,,Setting Stack Size from gnatlink} and
16512 @ref{137,,Setting Heap Size from gnatlink}.
16514 @emph{gnatlink} determines the list of objects required by the Ada
16515 program and prepends them to the list of objects passed to the linker.
16516 @emph{gnatlink} also gathers any arguments set by the use of
16517 @cite{pragma Linker_Options} and adds them to the list of arguments
16518 presented to the linker.
16520 @node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
16521 @anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{138}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{139}
16522 @subsection Switches for @emph{gnatlink}
16525 The following switches are available with the @emph{gnatlink} utility:
16527 @geindex --version (gnatlink)
16530 @table @asis
16532 @item @code{--version}
16534 Display Copyright and version, then exit disregarding all other options.
16535 @end table
16537 @geindex --help (gnatlink)
16540 @table @asis
16542 @item @code{--help}
16544 If @emph{--version} was not used, display usage, then exit disregarding
16545 all other options.
16546 @end table
16548 @geindex Command line length
16550 @geindex -f (gnatlink)
16553 @table @asis
16555 @item @code{-f}
16557 On some targets, the command line length is limited, and @emph{gnatlink}
16558 will generate a separate file for the linker if the list of object files
16559 is too long.
16560 The @emph{-f} switch forces this file
16561 to be generated even if
16562 the limit is not exceeded. This is useful in some cases to deal with
16563 special situations where the command line length is exceeded.
16564 @end table
16566 @geindex Debugging information
16567 @geindex including
16569 @geindex -g (gnatlink)
16572 @table @asis
16574 @item @code{-g}
16576 The option to include debugging information causes the Ada bind file (in
16577 other words, @code{b~mainprog.adb}) to be compiled with @emph{-g}.
16578 In addition, the binder does not delete the @code{b~mainprog.adb},
16579 @code{b~mainprog.o} and @code{b~mainprog.ali} files.
16580 Without @emph{-g}, the binder removes these files by default.
16581 @end table
16583 @geindex -n (gnatlink)
16586 @table @asis
16588 @item @code{-n}
16590 Do not compile the file generated by the binder. This may be used when
16591 a link is rerun with different options, but there is no need to recompile
16592 the binder file.
16593 @end table
16595 @geindex -v (gnatlink)
16598 @table @asis
16600 @item @code{-v}
16602 Verbose mode. Causes additional information to be output, including a full
16603 list of the included object files.
16604 This switch option is most useful when you want
16605 to see what set of object files are being used in the link step.
16606 @end table
16608 @geindex -v -v (gnatlink)
16611 @table @asis
16613 @item @code{-v -v}
16615 Very verbose mode. Requests that the compiler operate in verbose mode when
16616 it compiles the binder file, and that the system linker run in verbose mode.
16617 @end table
16619 @geindex -o (gnatlink)
16622 @table @asis
16624 @item @code{-o @emph{exec-name}}
16626 @cite{exec-name} specifies an alternate name for the generated
16627 executable program. If this switch is omitted, the executable has the same
16628 name as the main unit. For example, @cite{gnatlink try.ali} creates
16629 an executable called @code{try}.
16630 @end table
16632 @geindex -b (gnatlink)
16635 @table @asis
16637 @item @code{-b @emph{target}}
16639 Compile your program to run on @cite{target}, which is the name of a
16640 system configuration. You must have a GNAT cross-compiler built if
16641 @cite{target} is not the same as your host system.
16642 @end table
16644 @geindex -B (gnatlink)
16647 @table @asis
16649 @item @code{-B@emph{dir}}
16651 Load compiler executables (for example, @cite{gnat1}, the Ada compiler)
16652 from @cite{dir} instead of the default location. Only use this switch
16653 when multiple versions of the GNAT compiler are available.
16654 See the @cite{Directory Options} section in @cite{The_GNU_Compiler_Collection}
16655 for further details. You would normally use the @emph{-b} or
16656 @emph{-V} switch instead.
16657 @end table
16659 @geindex -M (gnatlink)
16662 @table @asis
16664 @item @code{-M}
16666 When linking an executable, create a map file. The name of the map file
16667 has the same name as the executable with extension ".map".
16668 @end table
16670 @geindex -M= (gnatlink)
16673 @table @asis
16675 @item @code{-M=@emph{mapfile}}
16677 When linking an executable, create a map file. The name of the map file is
16678 @cite{mapfile}.
16679 @end table
16681 @geindex --GCC=compiler_name (gnatlink)
16684 @table @asis
16686 @item @code{--GCC=@emph{compiler_name}}
16688 Program used for compiling the binder file. The default is
16689 @code{gcc}. You need to use quotes around @cite{compiler_name} if
16690 @cite{compiler_name} contains spaces or other separator characters.
16691 As an example @code{--GCC="foo -x -y"} will instruct @emph{gnatlink} to
16692 use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
16693 inserted after your command name. Thus in the above example the compiler
16694 command that will be used by @emph{gnatlink} will be @code{foo -c -x -y}.
16695 A limitation of this syntax is that the name and path name of the executable
16696 itself must not include any embedded spaces. If the compiler executable is
16697 different from the default one (gcc or <prefix>-gcc), then the back-end
16698 switches in the ALI file are not used to compile the binder generated source.
16699 For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
16700 switches will be used for @code{--GCC="gcc -gnatv"}. If several
16701 @code{--GCC=compiler_name} are used, only the last @cite{compiler_name}
16702 is taken into account. However, all the additional switches are also taken
16703 into account. Thus,
16704 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
16705 @code{--GCC="bar -x -y -z -t"}.
16706 @end table
16708 @geindex --LINK= (gnatlink)
16711 @table @asis
16713 @item @code{--LINK=@emph{name}}
16715 @cite{name} is the name of the linker to be invoked. This is especially
16716 useful in mixed language programs since languages such as C++ require
16717 their own linker to be used. When this switch is omitted, the default
16718 name for the linker is @emph{gcc}. When this switch is used, the
16719 specified linker is called instead of @emph{gcc} with exactly the same
16720 parameters that would have been passed to @emph{gcc} so if the desired
16721 linker requires different parameters it is necessary to use a wrapper
16722 script that massages the parameters before invoking the real linker. It
16723 may be useful to control the exact invocation by using the verbose
16724 switch.
16725 @end table
16727 @node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
16728 @anchor{gnat_ugn/building_executable_programs_with_gnat using-the-gnu-make-utility}@anchor{1f}@anchor{gnat_ugn/building_executable_programs_with_gnat id48}@anchor{13a}
16729 @section Using the GNU @cite{make} Utility
16732 @geindex make (GNU)
16733 @geindex GNU make
16735 This chapter offers some examples of makefiles that solve specific
16736 problems. It does not explain how to write a makefile, nor does it try to replace the
16737 @emph{gnatmake} utility (@ref{1b,,Building with gnatmake}).
16739 All the examples in this section are specific to the GNU version of
16740 make. Although @emph{make} is a standard utility, and the basic language
16741 is the same, these examples use some advanced features found only in
16742 @cite{GNU make}.
16744 @menu
16745 * Using gnatmake in a Makefile:: 
16746 * Automatically Creating a List of Directories:: 
16747 * Generating the Command Line Switches:: 
16748 * Overcoming Command Line Length Limits:: 
16750 @end menu
16752 @node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
16753 @anchor{gnat_ugn/building_executable_programs_with_gnat using-gnatmake-in-a-makefile}@anchor{13b}@anchor{gnat_ugn/building_executable_programs_with_gnat id49}@anchor{13c}
16754 @subsection Using gnatmake in a Makefile
16757 @c index makefile (GNU make)
16759 Complex project organizations can be handled in a very powerful way by
16760 using GNU make combined with gnatmake. For instance, here is a Makefile
16761 which allows you to build each subsystem of a big project into a separate
16762 shared library. Such a makefile allows you to significantly reduce the link
16763 time of very big applications while maintaining full coherence at
16764 each step of the build process.
16766 The list of dependencies are handled automatically by
16767 @emph{gnatmake}. The Makefile is simply used to call gnatmake in each of
16768 the appropriate directories.
16770 Note that you should also read the example on how to automatically
16771 create the list of directories
16772 (@ref{13d,,Automatically Creating a List of Directories})
16773 which might help you in case your project has a lot of subdirectories.
16775 @example
16776 ## This Makefile is intended to be used with the following directory
16777 ## configuration:
16778 ##  - The sources are split into a series of csc (computer software components)
16779 ##    Each of these csc is put in its own directory.
16780 ##    Their name are referenced by the directory names.
16781 ##    They will be compiled into shared library (although this would also work
16782 ##    with static libraries
16783 ##  - The main program (and possibly other packages that do not belong to any
16784 ##    csc is put in the top level directory (where the Makefile is).
16785 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16786 ##                    \\_ second_csc (sources) __ lib (will contain the library)
16787 ##                    \\_ ...
16788 ## Although this Makefile is build for shared library, it is easy to modify
16789 ## to build partial link objects instead (modify the lines with -shared and
16790 ## gnatlink below)
16792 ## With this makefile, you can change any file in the system or add any new
16793 ## file, and everything will be recompiled correctly (only the relevant shared
16794 ## objects will be recompiled, and the main program will be re-linked).
16796 # The list of computer software component for your project. This might be
16797 # generated automatically.
16798 CSC_LIST=aa bb cc
16800 # Name of the main program (no extension)
16801 MAIN=main
16803 # If we need to build objects with -fPIC, uncomment the following line
16804 #NEED_FPIC=-fPIC
16806 # The following variable should give the directory containing libgnat.so
16807 # You can get this directory through 'gnatls -v'. This is usually the last
16808 # directory in the Object_Path.
16809 GLIB=...
16811 # The directories for the libraries
16812 # (This macro expands the list of CSC to the list of shared libraries, you
16813 # could simply use the expanded form:
16814 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16815 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16817 $@{MAIN@}: objects $@{LIB_DIR@}
16818     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16819     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16821 objects::
16822     # recompile the sources
16823     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16825 # Note: In a future version of GNAT, the following commands will be simplified
16826 # by a new tool, gnatmlib
16827 $@{LIB_DIR@}:
16828     mkdir -p $@{dir $@@ @}
16829     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16830     cd $@{dir $@@ @} && cp -f ../*.ali .
16832 # The dependencies for the modules
16833 # Note that we have to force the expansion of *.o, since in some cases
16834 # make won't be able to do it itself.
16835 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16836 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16837 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16839 # Make sure all of the shared libraries are in the path before starting the
16840 # program
16841 run::
16842     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16844 clean::
16845     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16846     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16847     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16848     $@{RM@} *.o *.ali $@{MAIN@}
16849 @end example
16851 @node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
16852 @anchor{gnat_ugn/building_executable_programs_with_gnat id50}@anchor{13e}@anchor{gnat_ugn/building_executable_programs_with_gnat automatically-creating-a-list-of-directories}@anchor{13d}
16853 @subsection Automatically Creating a List of Directories
16856 In most makefiles, you will have to specify a list of directories, and
16857 store it in a variable. For small projects, it is often easier to
16858 specify each of them by hand, since you then have full control over what
16859 is the proper order for these directories, which ones should be
16860 included.
16862 However, in larger projects, which might involve hundreds of
16863 subdirectories, it might be more convenient to generate this list
16864 automatically.
16866 The example below presents two methods. The first one, although less
16867 general, gives you more control over the list. It involves wildcard
16868 characters, that are automatically expanded by @emph{make}. Its
16869 shortcoming is that you need to explicitly specify some of the
16870 organization of your project, such as for instance the directory tree
16871 depth, whether some directories are found in a separate tree, etc.
16873 The second method is the most general one. It requires an external
16874 program, called @emph{find}, which is standard on all Unix systems. All
16875 the directories found under a given root directory will be added to the
16876 list.
16878 @example
16879 # The examples below are based on the following directory hierarchy:
16880 # All the directories can contain any number of files
16881 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16882 #                       ->  ab
16883 #                       ->  ac
16884 #                ->  b  ->  ba  ->  baa
16885 #                       ->  bb
16886 #                       ->  bc
16887 # This Makefile creates a variable called DIRS, that can be reused any time
16888 # you need this list (see the other examples in this section)
16890 # The root of your project's directory hierarchy
16891 ROOT_DIRECTORY=.
16893 ####
16894 # First method: specify explicitly the list of directories
16895 # This allows you to specify any subset of all the directories you need.
16896 ####
16898 DIRS := a/aa/ a/ab/ b/ba/
16900 ####
16901 # Second method: use wildcards
16902 # Note that the argument(s) to wildcard below should end with a '/'.
16903 # Since wildcards also return file names, we have to filter them out
16904 # to avoid duplicate directory names.
16905 # We thus use make's `dir` and `sort` functions.
16906 # It sets DIRs to the following value (note that the directories aaa and baa
16907 # are not given, unless you change the arguments to wildcard).
16908 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16909 ####
16911 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16912                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16914 ####
16915 # Third method: use an external program
16916 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16917 # This is the most complete command: it sets DIRs to the following value:
16918 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16919 ####
16921 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16922 @end example
16924 @node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
16925 @anchor{gnat_ugn/building_executable_programs_with_gnat id51}@anchor{13f}@anchor{gnat_ugn/building_executable_programs_with_gnat generating-the-command-line-switches}@anchor{140}
16926 @subsection Generating the Command Line Switches
16929 Once you have created the list of directories as explained in the
16930 previous section (@ref{13d,,Automatically Creating a List of Directories}),
16931 you can easily generate the command line arguments to pass to gnatmake.
16933 For the sake of completeness, this example assumes that the source path
16934 is not the same as the object path, and that you have two separate lists
16935 of directories.
16937 @example
16938 # see "Automatically creating a list of directories" to create
16939 # these variables
16940 SOURCE_DIRS=
16941 OBJECT_DIRS=
16943 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16944 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16946 all:
16947         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16948 @end example
16950 @node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
16951 @anchor{gnat_ugn/building_executable_programs_with_gnat overcoming-command-line-length-limits}@anchor{141}@anchor{gnat_ugn/building_executable_programs_with_gnat id52}@anchor{142}
16952 @subsection Overcoming Command Line Length Limits
16955 One problem that might be encountered on big projects is that many
16956 operating systems limit the length of the command line. It is thus hard to give
16957 gnatmake the list of source and object directories.
16959 This example shows how you can set up environment variables, which will
16960 make @emph{gnatmake} behave exactly as if the directories had been
16961 specified on the command line, but have a much higher length limit (or
16962 even none on most systems).
16964 It assumes that you have created a list of directories in your Makefile,
16965 using one of the methods presented in
16966 @ref{13d,,Automatically Creating a List of Directories}.
16967 For the sake of completeness, we assume that the object
16968 path (where the ALI files are found) is different from the sources patch.
16970 Note a small trick in the Makefile below: for efficiency reasons, we
16971 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16972 expanded immediately by @cite{make}. This way we overcome the standard
16973 make behavior which is to expand the variables only when they are
16974 actually used.
16976 On Windows, if you are using the standard Windows command shell, you must
16977 replace colons with semicolons in the assignments to these variables.
16979 @example
16980 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
16981 # This is the same thing as putting the -I arguments on the command line.
16982 # (the equivalent of using -aI on the command line would be to define
16983 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
16984 # You can of course have different values for these variables.
16986 # Note also that we need to keep the previous values of these variables, since
16987 # they might have been set before running 'make' to specify where the GNAT
16988 # library is installed.
16990 # see "Automatically creating a list of directories" to create these
16991 # variables
16992 SOURCE_DIRS=
16993 OBJECT_DIRS=
16995 empty:=
16996 space:=$@{empty@} $@{empty@}
16997 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16998 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16999 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17000 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17001 export ADA_INCLUDE_PATH
17002 export ADA_OBJECTS_PATH
17004 all:
17005         gnatmake main_unit
17006 @end example
17008 @node GNAT Utility Programs,GNAT and Program Execution,Building Executable Programs with GNAT,Top
17009 @anchor{gnat_ugn/gnat_utility_programs doc}@anchor{143}@anchor{gnat_ugn/gnat_utility_programs gnat-utility-programs}@anchor{b}@anchor{gnat_ugn/gnat_utility_programs id1}@anchor{144}
17010 @chapter GNAT Utility Programs
17013 This chapter describes a number of utility programs:
17017 @itemize *
17019 @item 
17020 @ref{20,,The File Cleanup Utility gnatclean}
17022 @item 
17023 @ref{21,,The GNAT Library Browser gnatls}
17025 @item 
17026 @ref{22,,The Cross-Referencing Tools gnatxref and gnatfind}
17028 @item 
17029 @ref{23,,The Ada to HTML Converter gnathtml}
17030 @end itemize
17032 Other GNAT utilities are described elsewhere in this manual:
17035 @itemize *
17037 @item 
17038 @ref{59,,Handling Arbitrary File Naming Conventions with gnatname}
17040 @item 
17041 @ref{63,,File Name Krunching with gnatkr}
17043 @item 
17044 @ref{36,,Renaming Files with gnatchop}
17046 @item 
17047 @ref{17,,Preprocessing with gnatprep}
17048 @end itemize
17050 @menu
17051 * The File Cleanup Utility gnatclean:: 
17052 * The GNAT Library Browser gnatls:: 
17053 * The Cross-Referencing Tools gnatxref and gnatfind:: 
17054 * The Ada to HTML Converter gnathtml:: 
17056 @end menu
17058 @node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
17059 @anchor{gnat_ugn/gnat_utility_programs id2}@anchor{145}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{20}
17060 @section The File Cleanup Utility @emph{gnatclean}
17063 @geindex File cleanup tool
17065 @geindex gnatclean
17067 @cite{gnatclean} is a tool that allows the deletion of files produced by the
17068 compiler, binder and linker, including ALI files, object files, tree files,
17069 expanded source files, library files, interface copy source files, binder
17070 generated files and executable files.
17072 @menu
17073 * Running gnatclean:: 
17074 * Switches for gnatclean:: 
17076 @end menu
17078 @node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
17079 @anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{146}@anchor{gnat_ugn/gnat_utility_programs id3}@anchor{147}
17080 @subsection Running @cite{gnatclean}
17083 The @cite{gnatclean} command has the form:
17085 @quotation
17087 @example
17088 $ gnatclean switches `names`
17089 @end example
17090 @end quotation
17092 where @cite{names} is a list of source file names. Suffixes @code{.ads} and
17093 @code{adb} may be omitted. If a project file is specified using switch
17094 @code{-P}, then @cite{names} may be completely omitted.
17096 In normal mode, @cite{gnatclean} delete the files produced by the compiler and,
17097 if switch @cite{-c} is not specified, by the binder and
17098 the linker. In informative-only mode, specified by switch
17099 @cite{-n}, the list of files that would have been deleted in
17100 normal mode is listed, but no file is actually deleted.
17102 @node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
17103 @anchor{gnat_ugn/gnat_utility_programs id4}@anchor{148}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{149}
17104 @subsection Switches for @cite{gnatclean}
17107 @cite{gnatclean} recognizes the following switches:
17109 @geindex --version (gnatclean)
17112 @table @asis
17114 @item @code{--version}
17116 Display Copyright and version, then exit disregarding all other options.
17117 @end table
17119 @geindex --help (gnatclean)
17122 @table @asis
17124 @item @code{--help}
17126 If @emph{--version} was not used, display usage, then exit disregarding
17127 all other options.
17129 @item @code{--subdirs=@emph{subdir}}
17131 Actual object directory of each project file is the subdirectory subdir of the
17132 object directory specified or defaulted in the project file.
17134 @item @code{--unchecked-shared-lib-imports}
17136 By default, shared library projects are not allowed to import static library
17137 projects. When this switch is used on the command line, this restriction is
17138 relaxed.
17139 @end table
17141 @geindex -c (gnatclean)
17144 @table @asis
17146 @item @code{-c}
17148 Only attempt to delete the files produced by the compiler, not those produced
17149 by the binder or the linker. The files that are not to be deleted are library
17150 files, interface copy files, binder generated files and executable files.
17151 @end table
17153 @geindex -D (gnatclean)
17156 @table @asis
17158 @item @code{-D @emph{dir}}
17160 Indicate that ALI and object files should normally be found in directory @cite{dir}.
17161 @end table
17163 @geindex -F (gnatclean)
17166 @table @asis
17168 @item @code{-F}
17170 When using project files, if some errors or warnings are detected during
17171 parsing and verbose mode is not in effect (no use of switch
17172 -v), then error lines start with the full path name of the project
17173 file, rather than its simple file name.
17174 @end table
17176 @geindex -h (gnatclean)
17179 @table @asis
17181 @item @code{-h}
17183 Output a message explaining the usage of @cite{gnatclean}.
17184 @end table
17186 @geindex -n (gnatclean)
17189 @table @asis
17191 @item @code{-n}
17193 Informative-only mode. Do not delete any files. Output the list of the files
17194 that would have been deleted if this switch was not specified.
17195 @end table
17197 @geindex -P (gnatclean)
17200 @table @asis
17202 @item @code{-P@emph{project}}
17204 Use project file @cite{project}. Only one such switch can be used.
17205 When cleaning a project file, the files produced by the compilation of the
17206 immediate sources or inherited sources of the project files are to be
17207 deleted. This is not depending on the presence or not of executable names
17208 on the command line.
17209 @end table
17211 @geindex -q (gnatclean)
17214 @table @asis
17216 @item @code{-q}
17218 Quiet output. If there are no errors, do not output anything, except in
17219 verbose mode (switch -v) or in informative-only mode
17220 (switch -n).
17221 @end table
17223 @geindex -r (gnatclean)
17226 @table @asis
17228 @item @code{-r}
17230 When a project file is specified (using switch -P),
17231 clean all imported and extended project files, recursively. If this switch
17232 is not specified, only the files related to the main project file are to be
17233 deleted. This switch has no effect if no project file is specified.
17234 @end table
17236 @geindex -v (gnatclean)
17239 @table @asis
17241 @item @code{-v}
17243 Verbose mode.
17244 @end table
17246 @geindex -vP (gnatclean)
17249 @table @asis
17251 @item @code{-vP@emph{x}}
17253 Indicates the verbosity of the parsing of GNAT project files.
17254 @ref{de,,Switches Related to Project Files}.
17255 @end table
17257 @geindex -X (gnatclean)
17260 @table @asis
17262 @item @code{-X@emph{name}=@emph{value}}
17264 Indicates that external variable @cite{name} has the value @cite{value}.
17265 The Project Manager will use this value for occurrences of
17266 @cite{external(name)} when parsing the project file.
17267 @ref{de,,Switches Related to Project Files}.
17268 @end table
17270 @geindex -aO (gnatclean)
17273 @table @asis
17275 @item @code{-aO@emph{dir}}
17277 When searching for ALI and object files, look in directory @cite{dir}.
17278 @end table
17280 @geindex -I (gnatclean)
17283 @table @asis
17285 @item @code{-I@emph{dir}}
17287 Equivalent to @code{-aO@emph{dir}}.
17288 @end table
17290 @geindex -I- (gnatclean)
17292 @geindex Source files
17293 @geindex suppressing search
17296 @table @asis
17298 @item @code{-I-}
17300 Do not look for ALI or object files in the directory
17301 where @cite{gnatclean} was invoked.
17302 @end table
17304 @node The GNAT Library Browser gnatls,The Cross-Referencing Tools gnatxref and gnatfind,The File Cleanup Utility gnatclean,GNAT Utility Programs
17305 @anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{21}@anchor{gnat_ugn/gnat_utility_programs id5}@anchor{14a}
17306 @section The GNAT Library Browser @cite{gnatls}
17309 @geindex Library browser
17311 @geindex gnatls
17313 @cite{gnatls} is a tool that outputs information about compiled
17314 units. It gives the relationship between objects, unit names and source
17315 files. It can also be used to check the source dependencies of a unit
17316 as well as various characteristics.
17318 Note: to invoke @cite{gnatls} with a project file, use the @cite{gnat}
17319 driver (see The_GNAT_Driver_and_Project_Files).
17321 @menu
17322 * Running gnatls:: 
17323 * Switches for gnatls:: 
17324 * Example of gnatls Usage:: 
17326 @end menu
17328 @node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
17329 @anchor{gnat_ugn/gnat_utility_programs id6}@anchor{14b}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{14c}
17330 @subsection Running @cite{gnatls}
17333 The @cite{gnatls} command has the form
17335 @quotation
17337 @example
17338 $ gnatls switches `object_or_ali_file`
17339 @end example
17340 @end quotation
17342 The main argument is the list of object or @code{ali} files
17343 (see @ref{42,,The Ada Library Information Files})
17344 for which information is requested.
17346 In normal mode, without additional option, @cite{gnatls} produces a
17347 four-column listing. Each line represents information for a specific
17348 object. The first column gives the full path of the object, the second
17349 column gives the name of the principal unit in this object, the third
17350 column gives the status of the source and the fourth column gives the
17351 full path of the source representing this unit.
17352 Here is a simple example of use:
17354 @quotation
17356 @example
17357 $ gnatls *.o
17358 ./demo1.o            demo1            DIF demo1.adb
17359 ./demo2.o            demo2             OK demo2.adb
17360 ./hello.o            h1                OK hello.adb
17361 ./instr-child.o      instr.child      MOK instr-child.adb
17362 ./instr.o            instr             OK instr.adb
17363 ./tef.o              tef              DIF tef.adb
17364 ./text_io_example.o  text_io_example   OK text_io_example.adb
17365 ./tgef.o             tgef             DIF tgef.adb
17366 @end example
17367 @end quotation
17369 The first line can be interpreted as follows: the main unit which is
17370 contained in
17371 object file @code{demo1.o} is demo1, whose main source is in
17372 @code{demo1.adb}. Furthermore, the version of the source used for the
17373 compilation of demo1 has been modified (DIF). Each source file has a status
17374 qualifier which can be:
17377 @table @asis
17379 @item @emph{OK (unchanged)}
17381 The version of the source file used for the compilation of the
17382 specified unit corresponds exactly to the actual source file.
17384 @item @emph{MOK (slightly modified)}
17386 The version of the source file used for the compilation of the
17387 specified unit differs from the actual source file but not enough to
17388 require recompilation. If you use gnatmake with the qualifier
17389 @emph{-m (minimal recompilation)}, a file marked
17390 MOK will not be recompiled.
17392 @item @emph{DIF (modified)}
17394 No version of the source found on the path corresponds to the source
17395 used to build this object.
17397 @item @emph{??? (file not found)}
17399 No source file was found for this unit.
17401 @item @emph{HID (hidden,  unchanged version not first on PATH)}
17403 The version of the source that corresponds exactly to the source used
17404 for compilation has been found on the path but it is hidden by another
17405 version of the same source that has been modified.
17406 @end table
17408 @node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
17409 @anchor{gnat_ugn/gnat_utility_programs id7}@anchor{14d}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{14e}
17410 @subsection Switches for @cite{gnatls}
17413 @cite{gnatls} recognizes the following switches:
17415 @geindex --version (gnatls)
17418 @table @asis
17420 @item @code{--version}
17422 Display Copyright and version, then exit disregarding all other options.
17423 @end table
17425 @geindex --help (gnatls)
17428 @table @asis
17430 @item @code{*--help}
17432 If @emph{--version} was not used, display usage, then exit disregarding
17433 all other options.
17434 @end table
17436 @geindex -a (gnatls)
17439 @table @asis
17441 @item @code{-a}
17443 Consider all units, including those of the predefined Ada library.
17444 Especially useful with @emph{-d}.
17445 @end table
17447 @geindex -d (gnatls)
17450 @table @asis
17452 @item @code{-d}
17454 List sources from which specified units depend on.
17455 @end table
17457 @geindex -h (gnatls)
17460 @table @asis
17462 @item @code{-h}
17464 Output the list of options.
17465 @end table
17467 @geindex -o (gnatls)
17470 @table @asis
17472 @item @code{-o}
17474 Only output information about object files.
17475 @end table
17477 @geindex -s (gnatls)
17480 @table @asis
17482 @item @code{-s}
17484 Only output information about source files.
17485 @end table
17487 @geindex -u (gnatls)
17490 @table @asis
17492 @item @code{-u}
17494 Only output information about compilation units.
17495 @end table
17497 @geindex -files (gnatls)
17500 @table @asis
17502 @item @code{-files=@emph{file}}
17504 Take as arguments the files listed in text file @cite{file}.
17505 Text file @cite{file} may contain empty lines that are ignored.
17506 Each nonempty line should contain the name of an existing file.
17507 Several such switches may be specified simultaneously.
17508 @end table
17510 @geindex -aO (gnatls)
17512 @geindex -aI (gnatls)
17514 @geindex -I (gnatls)
17516 @geindex -I- (gnatls)
17519 @table @asis
17521 @item @code{-aO@emph{dir}}, @code{-aI@emph{dir}}, @code{-I@emph{dir}}, @code{-I-}, @code{-nostdinc}
17523 Source path manipulation. Same meaning as the equivalent @emph{gnatmake}
17524 flags (@ref{dc,,Switches for gnatmake}).
17525 @end table
17527 @geindex -aP (gnatls)
17530 @table @asis
17532 @item @code{-aP@emph{dir}}
17534 Add @cite{dir} at the beginning of the project search dir.
17535 @end table
17537 @geindex --RTS (gnatls)
17540 @table @asis
17542 @item @code{--RTS=@emph{rts-path}`}
17544 Specifies the default location of the runtime library. Same meaning as the
17545 equivalent @emph{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
17546 @end table
17548 @geindex -v (gnatls)
17551 @table @asis
17553 @item @code{-v}
17555 Verbose mode. Output the complete source, object and project paths. Do not use
17556 the default column layout but instead use long format giving as much as
17557 information possible on each requested units, including special
17558 characteristics such as:
17561 @itemize *
17563 @item 
17564 @emph{Preelaborable}: The unit is preelaborable in the Ada sense.
17566 @item 
17567 @emph{No_Elab_Code}:  No elaboration code has been produced by the compiler for this unit.
17569 @item 
17570 @emph{Pure}: The unit is pure in the Ada sense.
17572 @item 
17573 @emph{Elaborate_Body}: The unit contains a pragma Elaborate_Body.
17575 @item 
17576 @emph{Remote_Types}: The unit contains a pragma Remote_Types.
17578 @item 
17579 @emph{Shared_Passive}: The unit contains a pragma Shared_Passive.
17581 @item 
17582 @emph{Predefined}: This unit is part of the predefined environment and cannot be modified
17583 by the user.
17585 @item 
17586 @emph{Remote_Call_Interface}: The unit contains a pragma Remote_Call_Interface.
17587 @end itemize
17588 @end table
17590 @node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
17591 @anchor{gnat_ugn/gnat_utility_programs id8}@anchor{14f}@anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{150}
17592 @subsection Example of @cite{gnatls} Usage
17595 Example of using the verbose switch. Note how the source and
17596 object paths are affected by the -I switch.
17598 @quotation
17600 @example
17601 $ gnatls -v -I.. demo1.o
17603 GNATLS 5.03w (20041123-34)
17604 Copyright 1997-2004 Free Software Foundation, Inc.
17606 Source Search Path:
17607    <Current_Directory>
17608    ../
17609    /home/comar/local/adainclude/
17611 Object Search Path:
17612    <Current_Directory>
17613    ../
17614    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17616 Project Search Path:
17617    <Current_Directory>
17618    /home/comar/local/lib/gnat/
17620 ./demo1.o
17621    Unit =>
17622      Name   => demo1
17623      Kind   => subprogram body
17624      Flags  => No_Elab_Code
17625      Source => demo1.adb    modified
17626 @end example
17627 @end quotation
17629 The following is an example of use of the dependency list.
17630 Note the use of the -s switch
17631 which gives a straight list of source files. This can be useful for
17632 building specialized scripts.
17634 @quotation
17636 @example
17637 $ gnatls -d demo2.o
17638 ./demo2.o   demo2        OK demo2.adb
17639                          OK gen_list.ads
17640                          OK gen_list.adb
17641                          OK instr.ads
17642                          OK instr-child.ads
17644 $ gnatls -d -s -a demo1.o
17645 demo1.adb
17646 /home/comar/local/adainclude/ada.ads
17647 /home/comar/local/adainclude/a-finali.ads
17648 /home/comar/local/adainclude/a-filico.ads
17649 /home/comar/local/adainclude/a-stream.ads
17650 /home/comar/local/adainclude/a-tags.ads
17651 gen_list.ads
17652 gen_list.adb
17653 /home/comar/local/adainclude/gnat.ads
17654 /home/comar/local/adainclude/g-io.ads
17655 instr.ads
17656 /home/comar/local/adainclude/system.ads
17657 /home/comar/local/adainclude/s-exctab.ads
17658 /home/comar/local/adainclude/s-finimp.ads
17659 /home/comar/local/adainclude/s-finroo.ads
17660 /home/comar/local/adainclude/s-secsta.ads
17661 /home/comar/local/adainclude/s-stalib.ads
17662 /home/comar/local/adainclude/s-stoele.ads
17663 /home/comar/local/adainclude/s-stratt.ads
17664 /home/comar/local/adainclude/s-tasoli.ads
17665 /home/comar/local/adainclude/s-unstyp.ads
17666 /home/comar/local/adainclude/unchconv.ads
17667 @end example
17668 @end quotation
17670 @node The Cross-Referencing Tools gnatxref and gnatfind,The Ada to HTML Converter gnathtml,The GNAT Library Browser gnatls,GNAT Utility Programs
17671 @anchor{gnat_ugn/gnat_utility_programs the-cross-referencing-tools-gnatxref-and-gnatfind}@anchor{22}@anchor{gnat_ugn/gnat_utility_programs id9}@anchor{151}
17672 @section The Cross-Referencing Tools @cite{gnatxref} and @cite{gnatfind}
17675 @geindex gnatxref
17677 @geindex gnatfind
17679 The compiler generates cross-referencing information (unless
17680 you set the @code{-gnatx} switch), which are saved in the @code{.ali} files.
17681 This information indicates where in the source each entity is declared and
17682 referenced. Note that entities in package Standard are not included, but
17683 entities in all other predefined units are included in the output.
17685 Before using any of these two tools, you need to compile successfully your
17686 application, so that GNAT gets a chance to generate the cross-referencing
17687 information.
17689 The two tools @cite{gnatxref} and @cite{gnatfind} take advantage of this
17690 information to provide the user with the capability to easily locate the
17691 declaration and references to an entity. These tools are quite similar,
17692 the difference being that @cite{gnatfind} is intended for locating
17693 definitions and/or references to a specified entity or entities, whereas
17694 @cite{gnatxref} is oriented to generating a full report of all
17695 cross-references.
17697 To use these tools, you must not compile your application using the
17698 @emph{-gnatx} switch on the @emph{gnatmake} command line
17699 (see @ref{1b,,Building with gnatmake}). Otherwise, cross-referencing
17700 information will not be generated.
17702 Note: to invoke @cite{gnatxref} or @cite{gnatfind} with a project file,
17703 use the @cite{gnat} driver (see The_GNAT_Driver_and_Project_Files).
17705 @menu
17706 * gnatxref Switches:: 
17707 * gnatfind Switches:: 
17708 * Configuration Files for gnatxref and gnatfind:: 
17709 * Regular Expressions in gnatfind and gnatxref:: 
17710 * Examples of gnatxref Usage:: 
17711 * Examples of gnatfind Usage:: 
17713 @end menu
17715 @node gnatxref Switches,gnatfind Switches,,The Cross-Referencing Tools gnatxref and gnatfind
17716 @anchor{gnat_ugn/gnat_utility_programs id10}@anchor{152}@anchor{gnat_ugn/gnat_utility_programs gnatxref-switches}@anchor{153}
17717 @subsection @cite{gnatxref} Switches
17720 The command invocation for @cite{gnatxref} is:
17722 @quotation
17724 @example
17725 $ gnatxref [`switches`] `sourcefile1` [`sourcefile2` ...]
17726 @end example
17727 @end quotation
17729 where
17732 @table @asis
17734 @item @emph{sourcefile1} [, @emph{sourcefile2} ...]
17736 identify the source files for which a report is to be generated. The
17737 'with'ed units will be processed too. You must provide at least one file.
17739 These file names are considered to be regular expressions, so for instance
17740 specifying @code{source*.adb} is the same as giving every file in the current
17741 directory whose name starts with @code{source} and whose extension is
17742 @code{adb}.
17744 You shouldn't specify any directory name, just base names. @emph{gnatxref}
17745 and @emph{gnatfind} will be able to locate these files by themselves using
17746 the source path. If you specify directories, no result is produced.
17747 @end table
17749 The following switches are available for @emph{gnatxref}:
17751 @geindex --version (gnatxref)
17754 @table @asis
17756 @item @code{--version}
17758 Display Copyright and version, then exit disregarding all other options.
17759 @end table
17761 @geindex --help (gnatxref)
17764 @table @asis
17766 @item @code{--help}
17768 If @emph{--version} was not used, display usage, then exit disregarding
17769 all other options.
17770 @end table
17772 @geindex -a (gnatxref)
17775 @table @asis
17777 @item @code{-a}
17779 If this switch is present, @cite{gnatfind} and @cite{gnatxref} will parse
17780 the read-only files found in the library search path. Otherwise, these files
17781 will be ignored. This option can be used to protect Gnat sources or your own
17782 libraries from being parsed, thus making @cite{gnatfind} and @cite{gnatxref}
17783 much faster, and their output much smaller. Read-only here refers to access
17784 or permissions status in the file system for the current user.
17785 @end table
17787 @geindex -aIDIR (gnatxref)
17790 @table @asis
17792 @item @code{-aI@emph{DIR}}
17794 When looking for source files also look in directory DIR. The order in which
17795 source file search is undertaken is the same as for @emph{gnatmake}.
17796 @end table
17798 @geindex -aODIR (gnatxref)
17801 @table @asis
17803 @item @code{aO@emph{DIR}}
17805 When -searching for library and object files, look in directory
17806 DIR. The order in which library files are searched is the same as for
17807 @emph{gnatmake}.
17808 @end table
17810 @geindex -nostdinc (gnatxref)
17813 @table @asis
17815 @item @code{-nostdinc}
17817 Do not look for sources in the system default directory.
17818 @end table
17820 @geindex -nostdlib (gnatxref)
17823 @table @asis
17825 @item @code{-nostdlib}
17827 Do not look for library files in the system default directory.
17828 @end table
17830 @geindex --ext (gnatxref)
17833 @table @asis
17835 @item @code{--ext=@emph{extension}}
17837 Specify an alternate ali file extension. The default is @cite{ali} and other
17838 extensions (e.g. @cite{gli} for C/C++ sources when using @emph{-fdump-xref})
17839 may be specified via this switch. Note that if this switch overrides the
17840 default, which means that only the new extension will be considered.
17841 @end table
17843 @geindex --RTS (gnatxref)
17846 @table @asis
17848 @item @code{--RTS=@emph{rts-path}}
17850 Specifies the default location of the runtime library. Same meaning as the
17851 equivalent @emph{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
17852 @end table
17854 @geindex -d (gnatxref)
17857 @table @asis
17859 @item @code{-d}
17861 If this switch is set @cite{gnatxref} will output the parent type
17862 reference for each matching derived types.
17863 @end table
17865 @geindex -f (gnatxref)
17868 @table @asis
17870 @item @code{-f}
17872 If this switch is set, the output file names will be preceded by their
17873 directory (if the file was found in the search path). If this switch is
17874 not set, the directory will not be printed.
17875 @end table
17877 @geindex -g (gnatxref)
17880 @table @asis
17882 @item @code{-g}
17884 If this switch is set, information is output only for library-level
17885 entities, ignoring local entities. The use of this switch may accelerate
17886 @cite{gnatfind} and @cite{gnatxref}.
17887 @end table
17889 @geindex -IDIR (gnatxref)
17892 @table @asis
17894 @item @code{-I@emph{DIR}}
17896 Equivalent to @code{-aODIR -aIDIR}.
17897 @end table
17899 @geindex -pFILE (gnatxref)
17902 @table @asis
17904 @item @code{-p@emph{FILE}}
17906 Specify a configuration file to use to list the source and object directories.
17908 If a file is specified, then the content of the source directory and object
17909 directory lines are added as if they had been specified respectively
17910 by @code{-aI} and @code{-aO}.
17912 See @ref{154,,Configuration Files for gnatxref and gnatfind} for the syntax
17913 of this configuration file.
17915 @item @code{-u}
17917 Output only unused symbols. This may be really useful if you give your
17918 main compilation unit on the command line, as @cite{gnatxref} will then
17919 display every unused entity and 'with'ed package.
17921 @item @code{-v}
17923 Instead of producing the default output, @cite{gnatxref} will generate a
17924 @code{tags} file that can be used by vi. For examples how to use this
17925 feature, see @ref{155,,Examples of gnatxref Usage}. The tags file is output
17926 to the standard output, thus you will have to redirect it to a file.
17927 @end table
17929 All these switches may be in any order on the command line, and may even
17930 appear after the file names. They need not be separated by spaces, thus
17931 you can say @code{gnatxref -ag} instead of @code{gnatxref -a -g}.
17933 @node gnatfind Switches,Configuration Files for gnatxref and gnatfind,gnatxref Switches,The Cross-Referencing Tools gnatxref and gnatfind
17934 @anchor{gnat_ugn/gnat_utility_programs id11}@anchor{156}@anchor{gnat_ugn/gnat_utility_programs gnatfind-switches}@anchor{157}
17935 @subsection @cite{gnatfind} Switches
17938 The command invocation for @cite{gnatfind} is:
17940 @quotation
17942 @example
17943 $ gnatfind [`switches`] `pattern`[:`sourcefile`[:`line`[:`column`]]]
17944       [`file1` `file2` ...]
17945 @end example
17946 @end quotation
17948 with the following iterpretation of the command arguments:
17951 @table @asis
17953 @item @emph{pattern}
17955 An entity will be output only if it matches the regular expression found
17956 in @cite{pattern}, see @ref{158,,Regular Expressions in gnatfind and gnatxref}.
17958 Omitting the pattern is equivalent to specifying @code{*}, which
17959 will match any entity. Note that if you do not provide a pattern, you
17960 have to provide both a sourcefile and a line.
17962 Entity names are given in Latin-1, with uppercase/lowercase equivalence
17963 for matching purposes. At the current time there is no support for
17964 8-bit codes other than Latin-1, or for wide characters in identifiers.
17966 @item @emph{sourcefile}
17968 @cite{gnatfind} will look for references, bodies or declarations
17969 of symbols referenced in @code{sourcefile}, at line @cite{line}
17970 and column @cite{column}. See @ref{159,,Examples of gnatfind Usage}
17971 for syntax examples.
17973 @item @emph{line}
17975 A decimal integer identifying the line number containing
17976 the reference to the entity (or entities) to be located.
17978 @item @emph{column}
17980 A decimal integer identifying the exact location on the
17981 line of the first character of the identifier for the
17982 entity reference. Columns are numbered from 1.
17984 @item @emph{file1 file2 ...}
17986 The search will be restricted to these source files. If none are given, then
17987 the search will be conducted for every library file in the search path.
17988 These files must appear only after the pattern or sourcefile.
17990 These file names are considered to be regular expressions, so for instance
17991 specifying @code{source*.adb} is the same as giving every file in the current
17992 directory whose name starts with @code{source} and whose extension is
17993 @code{adb}.
17995 The location of the spec of the entity will always be displayed, even if it
17996 isn't in one of @code{file1}, @code{file2}, ... The
17997 occurrences of the entity in the separate units of the ones given on the
17998 command line will also be displayed.
18000 Note that if you specify at least one file in this part, @cite{gnatfind} may
18001 sometimes not be able to find the body of the subprograms.
18002 @end table
18004 At least one of 'sourcefile' or 'pattern' has to be present on
18005 the command line.
18007 The following switches are available:
18009 @geindex --version (gnatfind)
18012 @table @asis
18014 @item @code{--version}
18016 Display Copyright and version, then exit disregarding all other options.
18017 @end table
18019 @geindex --help (gnatfind)
18022 @table @asis
18024 @item @code{--help}
18026 If @emph{--version} was not used, display usage, then exit disregarding
18027 all other options.
18028 @end table
18030 @geindex -a (gnatfind)
18033 @table @asis
18035 @item @code{-a}
18037 If this switch is present, @cite{gnatfind} and @cite{gnatxref} will parse
18038 the read-only files found in the library search path. Otherwise, these files
18039 will be ignored. This option can be used to protect Gnat sources or your own
18040 libraries from being parsed, thus making @cite{gnatfind} and @cite{gnatxref}
18041 much faster, and their output much smaller. Read-only here refers to access
18042 or permission status in the file system for the current user.
18043 @end table
18045 @geindex -aIDIR (gnatfind)
18048 @table @asis
18050 @item @code{-aI@emph{DIR}}
18052 When looking for source files also look in directory DIR. The order in which
18053 source file search is undertaken is the same as for @emph{gnatmake}.
18054 @end table
18056 @geindex -aODIR (gnatfind)
18059 @table @asis
18061 @item @code{-aO@emph{DIR}}
18063 When searching for library and object files, look in directory
18064 DIR. The order in which library files are searched is the same as for
18065 @emph{gnatmake}.
18066 @end table
18068 @geindex -nostdinc (gnatfind)
18071 @table @asis
18073 @item @code{-nostdinc}
18075 Do not look for sources in the system default directory.
18076 @end table
18078 @geindex -nostdlib (gnatfind)
18081 @table @asis
18083 @item @code{-nostdlib}
18085 Do not look for library files in the system default directory.
18086 @end table
18088 @geindex --ext (gnatfind)
18091 @table @asis
18093 @item @code{--ext=@emph{extension}}
18095 Specify an alternate ali file extension. The default is @cite{ali} and other
18096 extensions (e.g. @cite{gli} for C/C++ sources when using @emph{-fdump-xref})
18097 may be specified via this switch. Note that if this switch overrides the
18098 default, which means that only the new extension will be considered.
18099 @end table
18101 @geindex --RTS (gnatfind)
18104 @table @asis
18106 @item @code{--RTS=@emph{rts-path}}
18108 Specifies the default location of the runtime library. Same meaning as the
18109 equivalent @emph{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
18110 @end table
18112 @geindex -d (gnatfind)
18115 @table @asis
18117 @item @code{-d}
18119 If this switch is set, then @cite{gnatfind} will output the parent type
18120 reference for each matching derived types.
18121 @end table
18123 @geindex -e (gnatfind)
18126 @table @asis
18128 @item @code{-e}
18130 By default, @cite{gnatfind} accept the simple regular expression set for
18131 @cite{pattern}. If this switch is set, then the pattern will be
18132 considered as full Unix-style regular expression.
18133 @end table
18135 @geindex -f (gnatfind)
18138 @table @asis
18140 @item @code{-f}
18142 If this switch is set, the output file names will be preceded by their
18143 directory (if the file was found in the search path). If this switch is
18144 not set, the directory will not be printed.
18145 @end table
18147 @geindex -g (gnatfind)
18150 @table @asis
18152 @item @code{-g}
18154 If this switch is set, information is output only for library-level
18155 entities, ignoring local entities. The use of this switch may accelerate
18156 @cite{gnatfind} and @cite{gnatxref}.
18157 @end table
18159 @geindex -IDIR (gnatfind)
18162 @table @asis
18164 @item @code{-I@emph{DIR}}
18166 Equivalent to @code{-aODIR -aIDIR}.
18167 @end table
18169 @geindex -pFILE (gnatfind)
18172 @table @asis
18174 @item @code{-p@emph{FILE}}
18176 Specify a configuration file to use to list the source and object directories.
18178 If a file is specified, then the content of the source directory and object
18179 directory lines are added as if they had been specified respectively
18180 by @code{-aI} and @code{-aO}.
18182 See @ref{154,,Configuration Files for gnatxref and gnatfind} for the syntax
18183 of this configuration file.
18184 @end table
18186 @geindex -r (gnatfind)
18189 @table @asis
18191 @item @code{-r}
18193 By default, @cite{gnatfind} will output only the information about the
18194 declaration, body or type completion of the entities. If this switch is
18195 set, the @cite{gnatfind} will locate every reference to the entities in
18196 the files specified on the command line (or in every file in the search
18197 path if no file is given on the command line).
18198 @end table
18200 @geindex -s (gnatfind)
18203 @table @asis
18205 @item @code{-s}
18207 If this switch is set, then @cite{gnatfind} will output the content
18208 of the Ada source file lines were the entity was found.
18209 @end table
18211 @geindex -t (gnatfind)
18214 @table @asis
18216 @item @code{-t}
18218 If this switch is set, then @cite{gnatfind} will output the type hierarchy for
18219 the specified type. It act like -d option but recursively from parent
18220 type to parent type. When this switch is set it is not possible to
18221 specify more than one file.
18222 @end table
18224 All these switches may be in any order on the command line, and may even
18225 appear after the file names. They need not be separated by spaces, thus
18226 you can say @code{gnatxref -ag} instead of
18227 @code{gnatxref -a -g}.
18229 As stated previously, gnatfind will search in every directory in the
18230 search path. You can force it to look only in the current directory if
18231 you specify @cite{*} at the end of the command line.
18233 @node Configuration Files for gnatxref and gnatfind,Regular Expressions in gnatfind and gnatxref,gnatfind Switches,The Cross-Referencing Tools gnatxref and gnatfind
18234 @anchor{gnat_ugn/gnat_utility_programs configuration-files-for-gnatxref-and-gnatfind}@anchor{154}@anchor{gnat_ugn/gnat_utility_programs id12}@anchor{15a}
18235 @subsection Configuration Files for @emph{gnatxref} and @emph{gnatfind}
18238 Configuration files are used by @cite{gnatxref} and @cite{gnatfind} to specify
18239 the list of source and object directories to consider. They can be
18240 specified via the @code{-p} switch.
18242 The following lines can be included, in any order in the file:
18245 @itemize *
18247 @item 
18249 @table @asis
18251 @item @emph{src_dir=DIR}
18253 [default: @cite{"./"}].
18254 Specifies a directory where to look for source files. Multiple @cite{src_dir}
18255 lines can be specified and they will be searched in the order they
18256 are specified.
18257 @end table
18259 @item 
18261 @table @asis
18263 @item @emph{obj_dir=DIR}
18265 [default: @cite{"./"}].
18266 Specifies a directory where to look for object and library files. Multiple
18267 @cite{obj_dir} lines can be specified, and they will be searched in the order
18268 they are specified
18269 @end table
18270 @end itemize
18272 Any other line will be silently ignored.
18274 @node Regular Expressions in gnatfind and gnatxref,Examples of gnatxref Usage,Configuration Files for gnatxref and gnatfind,The Cross-Referencing Tools gnatxref and gnatfind
18275 @anchor{gnat_ugn/gnat_utility_programs id13}@anchor{15b}@anchor{gnat_ugn/gnat_utility_programs regular-expressions-in-gnatfind-and-gnatxref}@anchor{158}
18276 @subsection Regular Expressions in @cite{gnatfind} and @cite{gnatxref}
18279 As specified in the section about @emph{gnatfind}, the pattern can be a
18280 regular expression. Two kinds of regular expressions
18281 are recognized:
18284 @itemize *
18286 @item 
18288 @table @asis
18290 @item @emph{Globbing pattern}
18292 These are the most common regular expression. They are the same as are
18293 generally used in a Unix shell command line, or in a DOS session.
18295 Here is a more formal grammar:
18297 @example
18298 regexp ::= term
18299 term   ::= elmt            -- matches elmt
18300 term   ::= elmt elmt       -- concatenation (elmt then elmt)
18301 term   ::= *               -- any string of 0 or more characters
18302 term   ::= ?               -- matches any character
18303 term   ::= [char @{char@}]   -- matches any character listed
18304 term   ::= [char - char]   -- matches any character in range
18305 @end example
18306 @end table
18308 @item 
18310 @table @asis
18312 @item @emph{Full regular expression}
18314 The second set of regular expressions is much more powerful. This is the
18315 type of regular expressions recognized by utilities such as @code{grep}.
18317 The following is the form of a regular expression, expressed in same BNF
18318 style as is found in the Ada Reference Manual:
18320 @example
18321 regexp ::= term @{| term@}   -- alternation (term or term ...)
18323 term ::= item @{item@}       -- concatenation (item then item)
18325 item ::= elmt              -- match elmt
18326 item ::= elmt *            -- zero or more elmt's
18327 item ::= elmt +            -- one or more elmt's
18328 item ::= elmt ?            -- matches elmt or nothing
18330 elmt ::= nschar            -- matches given character
18331 elmt ::= [nschar @{nschar@}]   -- matches any character listed
18332 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
18333 elmt ::= [char - char]     -- matches chars in given range
18334 elmt ::= \\ char            -- matches given character
18335 elmt ::= .                 -- matches any single character
18336 elmt ::= ( regexp )        -- parens used for grouping
18338 char ::= any character, including special characters
18339 nschar ::= any character except ()[].*+?^
18340 @end example
18342 Here are a few examples:
18344 @quotation
18347 @table @asis
18349 @item @code{abcde|fghi}
18351 will match any of the two strings @code{abcde} and @code{fghi},
18353 @item @code{abc*d}
18355 will match any string like @code{abd}, @code{abcd}, @code{abccd},
18356 @code{abcccd}, and so on,
18358 @item @code{[a-z]+}
18360 will match any string which has only lowercase characters in it (and at
18361 least one character.
18362 @end table
18363 @end quotation
18364 @end table
18365 @end itemize
18367 @node Examples of gnatxref Usage,Examples of gnatfind Usage,Regular Expressions in gnatfind and gnatxref,The Cross-Referencing Tools gnatxref and gnatfind
18368 @anchor{gnat_ugn/gnat_utility_programs examples-of-gnatxref-usage}@anchor{155}@anchor{gnat_ugn/gnat_utility_programs id14}@anchor{15c}
18369 @subsection Examples of @cite{gnatxref} Usage
18372 @menu
18373 * General Usage:: 
18374 * Using gnatxref with vi:: 
18376 @end menu
18378 @node General Usage,Using gnatxref with vi,,Examples of gnatxref Usage
18379 @anchor{gnat_ugn/gnat_utility_programs general-usage}@anchor{15d}
18380 @subsubsection General Usage
18383 For the following examples, we will consider the following units:
18385 @quotation
18387 @example
18388 main.ads:
18389 1: with Bar;
18390 2: package Main is
18391 3:     procedure Foo (B : in Integer);
18392 4:     C : Integer;
18393 5: private
18394 6:     D : Integer;
18395 7: end Main;
18397 main.adb:
18398 1: package body Main is
18399 2:     procedure Foo (B : in Integer) is
18400 3:     begin
18401 4:        C := B;
18402 5:        D := B;
18403 6:        Bar.Print (B);
18404 7:        Bar.Print (C);
18405 8:     end Foo;
18406 9: end Main;
18408 bar.ads:
18409 1: package Bar is
18410 2:     procedure Print (B : Integer);
18411 3: end bar;
18412 @end example
18413 @end quotation
18415 The first thing to do is to recompile your application (for instance, in
18416 that case just by doing a @code{gnatmake main}, so that GNAT generates
18417 the cross-referencing information.
18418 You can then issue any of the following commands:
18420 @quotation
18423 @itemize *
18425 @item 
18426 @code{gnatxref main.adb}
18427 @cite{gnatxref} generates cross-reference information for main.adb
18428 and every unit 'with'ed by main.adb.
18430 The output would be:
18432 @quotation
18434 @example
18435 B                                                      Type: Integer
18436   Decl: bar.ads           2:22
18437 B                                                      Type: Integer
18438   Decl: main.ads          3:20
18439   Body: main.adb          2:20
18440   Ref:  main.adb          4:13     5:13     6:19
18441 Bar                                                    Type: Unit
18442   Decl: bar.ads           1:9
18443   Ref:  main.adb          6:8      7:8
18444        main.ads           1:6
18445 C                                                      Type: Integer
18446   Decl: main.ads          4:5
18447   Modi: main.adb          4:8
18448   Ref:  main.adb          7:19
18449 D                                                      Type: Integer
18450   Decl: main.ads          6:5
18451   Modi: main.adb          5:8
18452 Foo                                                    Type: Unit
18453   Decl: main.ads          3:15
18454   Body: main.adb          2:15
18455 Main                                                    Type: Unit
18456   Decl: main.ads          2:9
18457   Body: main.adb          1:14
18458 Print                                                   Type: Unit
18459   Decl: bar.ads           2:15
18460   Ref:  main.adb          6:12     7:12
18461 @end example
18462 @end quotation
18464 This shows that the entity @cite{Main} is declared in main.ads, line 2, column 9,
18465 its body is in main.adb, line 1, column 14 and is not referenced any where.
18467 The entity @cite{Print} is declared in bar.ads, line 2, column 15 and it
18468 is referenced in main.adb, line 6 column 12 and line 7 column 12.
18470 @item 
18471 @code{gnatxref package1.adb package2.ads}
18472 @cite{gnatxref} will generates cross-reference information for
18473 package1.adb, package2.ads and any other package 'with'ed by any
18474 of these.
18475 @end itemize
18476 @end quotation
18478 @node Using gnatxref with vi,,General Usage,Examples of gnatxref Usage
18479 @anchor{gnat_ugn/gnat_utility_programs using-gnatxref-with-vi}@anchor{15e}
18480 @subsubsection Using gnatxref with vi
18483 @cite{gnatxref} can generate a tags file output, which can be used
18484 directly from @emph{vi}. Note that the standard version of @emph{vi}
18485 will not work properly with overloaded symbols. Consider using another
18486 free implementation of @emph{vi}, such as @emph{vim}.
18488 @quotation
18490 @example
18491 $ gnatxref -v gnatfind.adb > tags
18492 @end example
18493 @end quotation
18495 The following command will generate the tags file for @cite{gnatfind} itself
18496 (if the sources are in the search path!):
18498 @quotation
18500 @example
18501 $ gnatxref -v gnatfind.adb > tags
18502 @end example
18503 @end quotation
18505 From @emph{vi}, you can then use the command @code{:tag @emph{entity}}
18506 (replacing @cite{entity} by whatever you are looking for), and vi will
18507 display a new file with the corresponding declaration of entity.
18509 @node Examples of gnatfind Usage,,Examples of gnatxref Usage,The Cross-Referencing Tools gnatxref and gnatfind
18510 @anchor{gnat_ugn/gnat_utility_programs id15}@anchor{15f}@anchor{gnat_ugn/gnat_utility_programs examples-of-gnatfind-usage}@anchor{159}
18511 @subsection Examples of @cite{gnatfind} Usage
18515 @itemize *
18517 @item 
18518 @code{gnatfind -f xyz:main.adb}
18519 Find declarations for all entities xyz referenced at least once in
18520 main.adb. The references are search in every library file in the search
18521 path.
18523 The directories will be printed as well (as the @code{-f}
18524 switch is set)
18526 The output will look like:
18528 @quotation
18530 @example
18531 directory/main.ads:106:14: xyz <= declaration
18532 directory/main.adb:24:10: xyz <= body
18533 directory/foo.ads:45:23: xyz <= declaration
18534 @end example
18535 @end quotation
18537 I.e., one of the entities xyz found in main.adb is declared at
18538 line 12 of main.ads (and its body is in main.adb), and another one is
18539 declared at line 45 of foo.ads
18541 @item 
18542 @code{gnatfind -fs xyz:main.adb}
18543 This is the same command as the previous one, but @cite{gnatfind} will
18544 display the content of the Ada source file lines.
18546 The output will look like:
18548 @example
18549 directory/main.ads:106:14: xyz <= declaration
18550    procedure xyz;
18551 directory/main.adb:24:10: xyz <= body
18552    procedure xyz is
18553 directory/foo.ads:45:23: xyz <= declaration
18554    xyz : Integer;
18555 @end example
18557 This can make it easier to find exactly the location your are looking
18558 for.
18560 @item 
18561 @code{gnatfind -r "*x*":main.ads:123 foo.adb}
18562 Find references to all entities containing an x that are
18563 referenced on line 123 of main.ads.
18564 The references will be searched only in main.ads and foo.adb.
18566 @item 
18567 @code{gnatfind main.ads:123}
18568 Find declarations and bodies for all entities that are referenced on
18569 line 123 of main.ads.
18571 This is the same as @code{gnatfind "*":main.adb:123`}
18573 @item 
18574 @code{gnatfind mydir/main.adb:123:45}
18575 Find the declaration for the entity referenced at column 45 in
18576 line 123 of file main.adb in directory mydir. Note that it
18577 is usual to omit the identifier name when the column is given,
18578 since the column position identifies a unique reference.
18580 The column has to be the beginning of the identifier, and should not
18581 point to any character in the middle of the identifier.
18582 @end itemize
18584 @node The Ada to HTML Converter gnathtml,,The Cross-Referencing Tools gnatxref and gnatfind,GNAT Utility Programs
18585 @anchor{gnat_ugn/gnat_utility_programs the-ada-to-html-converter-gnathtml}@anchor{23}@anchor{gnat_ugn/gnat_utility_programs id16}@anchor{160}
18586 @section The Ada to HTML Converter @cite{gnathtml}
18589 @geindex gnathtml
18591 @emph{gnathtml} is a Perl script that allows Ada source files to be browsed using
18592 standard Web browsers. For installation information, see @ref{161,,Installing gnathtml}.
18594 Ada reserved keywords are highlighted in a bold font and Ada comments in
18595 a blue font. Unless your program was compiled with the gcc @emph{-gnatx}
18596 switch to suppress the generation of cross-referencing information, user
18597 defined variables and types will appear in a different color; you will
18598 be able to click on any identifier and go to its declaration.
18600 @menu
18601 * Invoking gnathtml:: 
18602 * Installing gnathtml:: 
18604 @end menu
18606 @node Invoking gnathtml,Installing gnathtml,,The Ada to HTML Converter gnathtml
18607 @anchor{gnat_ugn/gnat_utility_programs invoking-gnathtml}@anchor{162}@anchor{gnat_ugn/gnat_utility_programs id17}@anchor{163}
18608 @subsection Invoking @emph{gnathtml}
18611 The command line is as follows:
18613 @quotation
18615 @example
18616 $ perl gnathtml.pl [`switches`] `ada-files`
18617 @end example
18618 @end quotation
18620 You can specify as many Ada files as you want. @cite{gnathtml} will generate
18621 an html file for every ada file, and a global file called @code{index.htm}.
18622 This file is an index of every identifier defined in the files.
18624 The following switches are available:
18626 @geindex -83 (gnathtml)
18629 @table @asis
18631 @item @code{83}
18633 Only the Ada 83 subset of keywords will be highlighted.
18634 @end table
18636 @geindex -cc (gnathtml)
18639 @table @asis
18641 @item @code{cc @emph{color}}
18643 This option allows you to change the color used for comments. The default
18644 value is green. The color argument can be any name accepted by html.
18645 @end table
18647 @geindex -d (gnathtml)
18650 @table @asis
18652 @item @code{d}
18654 If the Ada files depend on some other files (for instance through
18655 @cite{with} clauses, the latter files will also be converted to html.
18656 Only the files in the user project will be converted to html, not the files
18657 in the run-time library itself.
18658 @end table
18660 @geindex -D (gnathtml)
18663 @table @asis
18665 @item @code{D}
18667 This command is the same as @emph{-d} above, but @emph{gnathtml} will
18668 also look for files in the run-time library, and generate html files for them.
18669 @end table
18671 @geindex -ext (gnathtml)
18674 @table @asis
18676 @item @code{ext @emph{extension}}
18678 This option allows you to change the extension of the generated HTML files.
18679 If you do not specify an extension, it will default to @code{htm}.
18680 @end table
18682 @geindex -f (gnathtml)
18685 @table @asis
18687 @item @code{f}
18689 By default, gnathtml will generate html links only for global entities
18690 ('with'ed units, global variables and types,...).  If you specify
18691 @emph{-f} on the command line, then links will be generated for local
18692 entities too.
18693 @end table
18695 @geindex -l (gnathtml)
18698 @table @asis
18700 @item @code{l @emph{number}}
18702 If this switch is provided and @cite{number} is not 0, then
18703 @cite{gnathtml} will number the html files every @cite{number} line.
18704 @end table
18706 @geindex -I (gnathtml)
18709 @table @asis
18711 @item @code{I @emph{dir}}
18713 Specify a directory to search for library files (@code{.ALI} files) and
18714 source files. You can provide several -I switches on the command line,
18715 and the directories will be parsed in the order of the command line.
18716 @end table
18718 @geindex -o (gnathtml)
18721 @table @asis
18723 @item @code{o @emph{dir}}
18725 Specify the output directory for html files. By default, gnathtml will
18726 saved the generated html files in a subdirectory named @code{html/}.
18727 @end table
18729 @geindex -p (gnathtml)
18732 @table @asis
18734 @item @code{p @emph{file}}
18736 If you are using Emacs and the most recent Emacs Ada mode, which provides
18737 a full Integrated Development Environment for compiling, checking,
18738 running and debugging applications, you may use @code{.gpr} files
18739 to give the directories where Emacs can find sources and object files.
18741 Using this switch, you can tell gnathtml to use these files.
18742 This allows you to get an html version of your application, even if it
18743 is spread over multiple directories.
18744 @end table
18746 @geindex -sc (gnathtml)
18749 @table @asis
18751 @item @code{sc @emph{color}}
18753 This switch allows you to change the color used for symbol
18754 definitions.
18755 The default value is red. The color argument can be any name accepted by html.
18756 @end table
18758 @geindex -t (gnathtml)
18761 @table @asis
18763 @item @code{t @emph{file}}
18765 This switch provides the name of a file. This file contains a list of
18766 file names to be converted, and the effect is exactly as though they had
18767 appeared explicitly on the command line. This
18768 is the recommended way to work around the command line length limit on some
18769 systems.
18770 @end table
18772 @node Installing gnathtml,,Invoking gnathtml,The Ada to HTML Converter gnathtml
18773 @anchor{gnat_ugn/gnat_utility_programs installing-gnathtml}@anchor{161}@anchor{gnat_ugn/gnat_utility_programs id18}@anchor{164}
18774 @subsection Installing @cite{gnathtml}
18777 @cite{Perl} needs to be installed on your machine to run this script.
18778 @cite{Perl} is freely available for almost every architecture and
18779 operating system via the Internet.
18781 On Unix systems, you  may want to modify  the  first line of  the script
18782 @cite{gnathtml},  to explicitly  specify  where Perl
18783 is located. The syntax of this line is:
18785 @quotation
18787 @example
18788 #!full_path_name_to_perl
18789 @end example
18790 @end quotation
18792 Alternatively, you may run the script using the following command line:
18794 @quotation
18796 @example
18797 $ perl gnathtml.pl [`switches`] `files`
18798 @end example
18799 @end quotation
18801 @c -- +---------------------------------------------------------------------+
18803 @c -- | The following sections are present only in the PRO and GPL editions |
18805 @c -- +---------------------------------------------------------------------+
18814 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
18816 @node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
18817 @anchor{gnat_ugn/gnat_and_program_execution gnat-and-program-execution}@anchor{c}@anchor{gnat_ugn/gnat_and_program_execution doc}@anchor{165}@anchor{gnat_ugn/gnat_and_program_execution id1}@anchor{166}
18818 @chapter GNAT and Program Execution
18821 This chapter covers several topics:
18824 @itemize *
18826 @item 
18827 @ref{167,,Running and Debugging Ada Programs}
18829 @item 
18830 @ref{168,,Code Coverage and Profiling}
18832 @item 
18833 @ref{169,,Improving Performance}
18835 @item 
18836 @ref{16a,,Overflow Check Handling in GNAT}
18838 @item 
18839 @ref{16b,,Performing Dimensionality Analysis in GNAT}
18841 @item 
18842 @ref{16c,,Stack Related Facilities}
18844 @item 
18845 @ref{16d,,Memory Management Issues}
18846 @end itemize
18848 @menu
18849 * Running and Debugging Ada Programs:: 
18850 * Code Coverage and Profiling:: 
18851 * Improving Performance:: 
18852 * Overflow Check Handling in GNAT:: 
18853 * Performing Dimensionality Analysis in GNAT:: 
18854 * Stack Related Facilities:: 
18855 * Memory Management Issues:: 
18857 @end menu
18859 @node Running and Debugging Ada Programs,Code Coverage and Profiling,,GNAT and Program Execution
18860 @anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{167}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{24}
18861 @section Running and Debugging Ada Programs
18864 @geindex Debugging
18866 This section discusses how to debug Ada programs.
18868 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18871 @itemize *
18873 @item 
18874 The illegality may be a violation of the static semantics of Ada. In
18875 that case GNAT diagnoses the constructs in the program that are illegal.
18876 It is then a straightforward matter for the user to modify those parts of
18877 the program.
18879 @item 
18880 The illegality may be a violation of the dynamic semantics of Ada. In
18881 that case the program compiles and executes, but may generate incorrect
18882 results, or may terminate abnormally with some exception.
18884 @item 
18885 When presented with a program that contains convoluted errors, GNAT
18886 itself may terminate abnormally without providing full diagnostics on
18887 the incorrect user program.
18888 @end itemize
18890 @geindex Debugger
18892 @geindex gdb
18894 @menu
18895 * The GNAT Debugger GDB:: 
18896 * Running GDB:: 
18897 * Introduction to GDB Commands:: 
18898 * Using Ada Expressions:: 
18899 * Calling User-Defined Subprograms:: 
18900 * Using the next Command in a Function:: 
18901 * Stopping When Ada Exceptions Are Raised:: 
18902 * Ada Tasks:: 
18903 * Debugging Generic Units:: 
18904 * Remote Debugging with gdbserver:: 
18905 * GNAT Abnormal Termination or Failure to Terminate:: 
18906 * Naming Conventions for GNAT Source Files:: 
18907 * Getting Internal Debugging Information:: 
18908 * Stack Traceback:: 
18910 @end menu
18912 @node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
18913 @anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{16e}@anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{16f}
18914 @subsection The GNAT Debugger GDB
18917 @cite{GDB} is a general purpose, platform-independent debugger that
18918 can be used to debug mixed-language programs compiled with @emph{gcc},
18919 and in particular is capable of debugging Ada programs compiled with
18920 GNAT. The latest versions of @cite{GDB} are Ada-aware and can handle
18921 complex Ada data structures.
18923 See @cite{Debugging with GDB},
18924 for full details on the usage of @cite{GDB}, including a section on
18925 its usage on programs. This manual should be consulted for full
18926 details. The section that follows is a brief introduction to the
18927 philosophy and use of @cite{GDB}.
18929 When GNAT programs are compiled, the compiler optionally writes debugging
18930 information into the generated object file, including information on
18931 line numbers, and on declared types and variables. This information is
18932 separate from the generated code. It makes the object files considerably
18933 larger, but it does not add to the size of the actual executable that
18934 will be loaded into memory, and has no impact on run-time performance. The
18935 generation of debug information is triggered by the use of the
18936 -g switch in the @emph{gcc} or @emph{gnatmake} command
18937 used to carry out the compilations. It is important to emphasize that
18938 the use of these options does not change the generated code.
18940 The debugging information is written in standard system formats that
18941 are used by many tools, including debuggers and profilers. The format
18942 of the information is typically designed to describe C types and
18943 semantics, but GNAT implements a translation scheme which allows full
18944 details about Ada types and variables to be encoded into these
18945 standard C formats. Details of this encoding scheme may be found in
18946 the file exp_dbug.ads in the GNAT source distribution. However, the
18947 details of this encoding are, in general, of no interest to a user,
18948 since @cite{GDB} automatically performs the necessary decoding.
18950 When a program is bound and linked, the debugging information is
18951 collected from the object files, and stored in the executable image of
18952 the program. Again, this process significantly increases the size of
18953 the generated executable file, but it does not increase the size of
18954 the executable program itself. Furthermore, if this program is run in
18955 the normal manner, it runs exactly as if the debug information were
18956 not present, and takes no more actual memory.
18958 However, if the program is run under control of @cite{GDB}, the
18959 debugger is activated.  The image of the program is loaded, at which
18960 point it is ready to run.  If a run command is given, then the program
18961 will run exactly as it would have if @cite{GDB} were not present. This
18962 is a crucial part of the @cite{GDB} design philosophy.  @cite{GDB} is
18963 entirely non-intrusive until a breakpoint is encountered.  If no
18964 breakpoint is ever hit, the program will run exactly as it would if no
18965 debugger were present. When a breakpoint is hit, @cite{GDB} accesses
18966 the debugging information and can respond to user commands to inspect
18967 variables, and more generally to report on the state of execution.
18969 @node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
18970 @anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{170}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{171}
18971 @subsection Running GDB
18974 This section describes how to initiate the debugger.
18976 The debugger can be launched from a @cite{GPS} menu or
18977 directly from the command line. The description below covers the latter use.
18978 All the commands shown can be used in the @cite{GPS} debug console window,
18979 but there are usually more GUI-based ways to achieve the same effect.
18981 The command to run @cite{GDB} is
18983 @quotation
18985 @example
18986 $ gdb program
18987 @end example
18988 @end quotation
18990 where @cite{program} is the name of the executable file. This
18991 activates the debugger and results in a prompt for debugger commands.
18992 The simplest command is simply @cite{run}, which causes the program to run
18993 exactly as if the debugger were not present. The following section
18994 describes some of the additional commands that can be given to @cite{GDB}.
18996 @node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
18997 @anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{172}@anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{173}
18998 @subsection Introduction to GDB Commands
19001 @cite{GDB} contains a large repertoire of commands.
19002 See @cite{Debugging with GDB} for extensive documentation on the use
19003 of these commands, together with examples of their use. Furthermore,
19004 the command @emph{help} invoked from within GDB activates a simple help
19005 facility which summarizes the available commands and their options.
19006 In this section we summarize a few of the most commonly
19007 used commands to give an idea of what @cite{GDB} is about. You should create
19008 a simple program with debugging information and experiment with the use of
19009 these @cite{GDB} commands on the program as you read through the
19010 following section.
19013 @itemize *
19015 @item 
19017 @table @asis
19019 @item @emph{set args `arguments`}
19021 The @cite{arguments} list above is a list of arguments to be passed to
19022 the program on a subsequent run command, just as though the arguments
19023 had been entered on a normal invocation of the program. The @cite{set args}
19024 command is not needed if the program does not require arguments.
19025 @end table
19027 @item 
19029 @table @asis
19031 @item @emph{run}
19033 The @cite{run} command causes execution of the program to start from
19034 the beginning. If the program is already running, that is to say if
19035 you are currently positioned at a breakpoint, then a prompt will ask
19036 for confirmation that you want to abandon the current execution and
19037 restart.
19038 @end table
19040 @item 
19042 @table @asis
19044 @item @emph{breakpoint `location`}
19046 The breakpoint command sets a breakpoint, that is to say a point at which
19047 execution will halt and @cite{GDB} will await further
19048 commands. @cite{location} is
19049 either a line number within a file, given in the format @cite{file:linenumber},
19050 or it is the name of a subprogram. If you request that a breakpoint be set on
19051 a subprogram that is overloaded, a prompt will ask you to specify on which of
19052 those subprograms you want to breakpoint. You can also
19053 specify that all of them should be breakpointed. If the program is run
19054 and execution encounters the breakpoint, then the program
19055 stops and @cite{GDB} signals that the breakpoint was encountered by
19056 printing the line of code before which the program is halted.
19057 @end table
19059 @item 
19061 @table @asis
19063 @item @emph{catch exception `name`}
19065 This command causes the program execution to stop whenever exception
19066 @cite{name} is raised.  If @cite{name} is omitted, then the execution is
19067 suspended when any exception is raised.
19068 @end table
19070 @item 
19072 @table @asis
19074 @item @emph{print `expression`}
19076 This will print the value of the given expression. Most simple
19077 Ada expression formats are properly handled by @cite{GDB}, so the expression
19078 can contain function calls, variables, operators, and attribute references.
19079 @end table
19081 @item 
19083 @table @asis
19085 @item @emph{continue}
19087 Continues execution following a breakpoint, until the next breakpoint or the
19088 termination of the program.
19089 @end table
19091 @item 
19093 @table @asis
19095 @item @emph{step}
19097 Executes a single line after a breakpoint. If the next statement
19098 is a subprogram call, execution continues into (the first statement of)
19099 the called subprogram.
19100 @end table
19102 @item 
19104 @table @asis
19106 @item @emph{next}
19108 Executes a single line. If this line is a subprogram call, executes and
19109 returns from the call.
19110 @end table
19112 @item 
19114 @table @asis
19116 @item @emph{list}
19118 Lists a few lines around the current source location. In practice, it
19119 is usually more convenient to have a separate edit window open with the
19120 relevant source file displayed. Successive applications of this command
19121 print subsequent lines. The command can be given an argument which is a
19122 line number, in which case it displays a few lines around the specified one.
19123 @end table
19125 @item 
19127 @table @asis
19129 @item @emph{backtrace}
19131 Displays a backtrace of the call chain. This command is typically
19132 used after a breakpoint has occurred, to examine the sequence of calls that
19133 leads to the current breakpoint. The display includes one line for each
19134 activation record (frame) corresponding to an active subprogram.
19135 @end table
19137 @item 
19139 @table @asis
19141 @item @emph{up}
19143 At a breakpoint, @cite{GDB} can display the values of variables local
19144 to the current frame. The command @cite{up} can be used to
19145 examine the contents of other active frames, by moving the focus up
19146 the stack, that is to say from callee to caller, one frame at a time.
19147 @end table
19149 @item 
19151 @table @asis
19153 @item @emph{down}
19155 Moves the focus of @cite{GDB} down from the frame currently being
19156 examined to the frame of its callee (the reverse of the previous command),
19157 @end table
19159 @item 
19161 @table @asis
19163 @item @emph{frame `n`}
19165 Inspect the frame with the given number. The value 0 denotes the frame
19166 of the current breakpoint, that is to say the top of the call stack.
19167 @end table
19169 @item 
19171 @table @asis
19173 @item @emph{kill}
19175 Kills the child process in which the program is running under GDB.
19176 This may be useful for several purposes:
19179 @itemize *
19181 @item 
19182 It allows you to recompile and relink your program, since on many systems
19183 you cannot regenerate an executable file while it is running in a process.
19185 @item 
19186 You can run your program outside the debugger, on systems that do not
19187 permit executing a program outside GDB while breakpoints are set
19188 within GDB.
19190 @item 
19191 It allows you to debug a core dump rather than a running process.
19192 @end itemize
19193 @end table
19194 @end itemize
19196 The above list is a very short introduction to the commands that
19197 @cite{GDB} provides. Important additional capabilities, including conditional
19198 breakpoints, the ability to execute command sequences on a breakpoint,
19199 the ability to debug at the machine instruction level and many other
19200 features are described in detail in @cite{Debugging with GDB}.
19201 Note that most commands can be abbreviated
19202 (for example, c for continue, bt for backtrace).
19204 @node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
19205 @anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{174}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{175}
19206 @subsection Using Ada Expressions
19209 @geindex Ada expressions (in gdb)
19211 @cite{GDB} supports a fairly large subset of Ada expression syntax, with some
19212 extensions. The philosophy behind the design of this subset is
19214 @quotation
19217 @itemize *
19219 @item 
19220 That @cite{GDB} should provide basic literals and access to operations for
19221 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19222 leaving more sophisticated computations to subprograms written into the
19223 program (which therefore may be called from @cite{GDB}).
19225 @item 
19226 That type safety and strict adherence to Ada language restrictions
19227 are not particularly relevant in a debugging context.
19229 @item 
19230 That brevity is important to the @cite{GDB} user.
19231 @end itemize
19232 @end quotation
19234 Thus, for brevity, the debugger acts as if there were
19235 implicit @cite{with} and @cite{use} clauses in effect for all user-written
19236 packages, thus making it unnecessary to fully qualify most names with
19237 their packages, regardless of context. Where this causes ambiguity,
19238 @cite{GDB} asks the user's intent.
19240 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
19242 @node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
19243 @anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{176}@anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{177}
19244 @subsection Calling User-Defined Subprograms
19247 An important capability of @cite{GDB} is the ability to call user-defined
19248 subprograms while debugging. This is achieved simply by entering
19249 a subprogram call statement in the form:
19251 @quotation
19253 @example
19254 call subprogram-name (parameters)
19255 @end example
19256 @end quotation
19258 The keyword @cite{call} can be omitted in the normal case where the
19259 @cite{subprogram-name} does not coincide with any of the predefined
19260 @cite{GDB} commands.
19262 The effect is to invoke the given subprogram, passing it the
19263 list of parameters that is supplied. The parameters can be expressions and
19264 can include variables from the program being debugged. The
19265 subprogram must be defined
19266 at the library level within your program, and @cite{GDB} will call the
19267 subprogram within the environment of your program execution (which
19268 means that the subprogram is free to access or even modify variables
19269 within your program).
19271 The most important use of this facility is in allowing the inclusion of
19272 debugging routines that are tailored to particular data structures
19273 in your program. Such debugging routines can be written to provide a suitably
19274 high-level description of an abstract type, rather than a low-level dump
19275 of its physical layout. After all, the standard
19276 @cite{GDB print} command only knows the physical layout of your
19277 types, not their abstract meaning. Debugging routines can provide information
19278 at the desired semantic level and are thus enormously useful.
19280 For example, when debugging GNAT itself, it is crucial to have access to
19281 the contents of the tree nodes used to represent the program internally.
19282 But tree nodes are represented simply by an integer value (which in turn
19283 is an index into a table of nodes).
19284 Using the @cite{print} command on a tree node would simply print this integer
19285 value, which is not very useful. But the PN routine (defined in file
19286 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19287 a useful high level representation of the tree node, which includes the
19288 syntactic category of the node, its position in the source, the integers
19289 that denote descendant nodes and parent node, as well as varied
19290 semantic information. To study this example in more detail, you might want to
19291 look at the body of the PN procedure in the stated file.
19293 Another useful application of this capability is to deal with situations of
19294 complex data which are not handled suitably by GDB. For example, if you specify
19295 Convention Fortran for a multi-dimensional array, GDB does not know that
19296 the ordering of array elements has been switched and will not properly
19297 address the array elements. In such a case, instead of trying to print the
19298 elements directly from GDB, you can write a callable procedure that prints
19299 the elements in the desired format.
19301 @node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
19302 @anchor{gnat_ugn/gnat_and_program_execution using-the-next-command-in-a-function}@anchor{178}@anchor{gnat_ugn/gnat_and_program_execution id8}@anchor{179}
19303 @subsection Using the @emph{next} Command in a Function
19306 When you use the @cite{next} command in a function, the current source
19307 location will advance to the next statement as usual. A special case
19308 arises in the case of a @cite{return} statement.
19310 Part of the code for a return statement is the 'epilogue' of the function.
19311 This is the code that returns to the caller. There is only one copy of
19312 this epilogue code, and it is typically associated with the last return
19313 statement in the function if there is more than one return. In some
19314 implementations, this epilogue is associated with the first statement
19315 of the function.
19317 The result is that if you use the @cite{next} command from a return
19318 statement that is not the last return statement of the function you
19319 may see a strange apparent jump to the last return statement or to
19320 the start of the function. You should simply ignore this odd jump.
19321 The value returned is always that from the first return statement
19322 that was stepped through.
19324 @node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
19325 @anchor{gnat_ugn/gnat_and_program_execution stopping-when-ada-exceptions-are-raised}@anchor{17a}@anchor{gnat_ugn/gnat_and_program_execution id9}@anchor{17b}
19326 @subsection Stopping When Ada Exceptions Are Raised
19329 @geindex Exceptions (in gdb)
19331 You can set catchpoints that stop the program execution when your program
19332 raises selected exceptions.
19335 @itemize *
19337 @item 
19339 @table @asis
19341 @item @emph{catch exception}
19343 Set a catchpoint that stops execution whenever (any task in the) program
19344 raises any exception.
19345 @end table
19347 @item 
19349 @table @asis
19351 @item @emph{catch exception `name`}
19353 Set a catchpoint that stops execution whenever (any task in the) program
19354 raises the exception @cite{name}.
19355 @end table
19357 @item 
19359 @table @asis
19361 @item @emph{catch exception unhandled}
19363 Set a catchpoint that stops executing whenever (any task in the) program
19364 raises an exception for which there is no handler.
19365 @end table
19367 @item 
19369 @table @asis
19371 @item @emph{info exceptions}, @emph{info exceptions `regexp`}
19373 The @cite{info exceptions} command permits the user to examine all defined
19374 exceptions within Ada programs. With a regular expression, @cite{regexp}, as
19375 argument, prints out only those exceptions whose name matches @cite{regexp}.
19376 @end table
19377 @end itemize
19379 @geindex Tasks (in gdb)
19381 @node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
19382 @anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{17c}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{17d}
19383 @subsection Ada Tasks
19386 @cite{GDB} allows the following task-related commands:
19389 @itemize *
19391 @item 
19393 @table @asis
19395 @item @emph{info tasks}
19397 This command shows a list of current Ada tasks, as in the following example:
19399 @example
19400 (gdb) info tasks
19401   ID       TID P-ID   Thread Pri State                 Name
19402    1   8088000   0   807e000  15 Child Activation Wait main_task
19403    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19404    3   809a800   1   80a4800  15 Child Activation Wait a
19405 *  4   80ae800   3   80b8000  15 Running               c
19406 @end example
19408 In this listing, the asterisk before the first task indicates it to be the
19409 currently running task. The first column lists the task ID that is used
19410 to refer to tasks in the following commands.
19411 @end table
19412 @end itemize
19414 @geindex Breakpoints and tasks
19417 @itemize *
19419 @item 
19420 @emph{break `linespec` task `taskid`}, @emph{break `linespec` task `taskid` if ...}
19422 @quotation
19424 These commands are like the @cite{break ... thread ...}.
19425 @cite{linespec} specifies source lines.
19427 Use the qualifier @code{task @emph{taskid}} with a breakpoint command
19428 to specify that you only want @cite{GDB} to stop the program when a
19429 particular Ada task reaches this breakpoint. @cite{taskid} is one of the
19430 numeric task identifiers assigned by @cite{GDB}, shown in the first
19431 column of the @code{info tasks} display.
19433 If you do not specify @code{task @emph{taskid}} when you set a
19434 breakpoint, the breakpoint applies to @emph{all} tasks of your
19435 program.
19437 You can use the @cite{task} qualifier on conditional breakpoints as
19438 well; in this case, place @code{task @emph{taskid}} before the
19439 breakpoint condition (before the @cite{if}).
19440 @end quotation
19441 @end itemize
19443 @geindex Task switching (in gdb)
19446 @itemize *
19448 @item 
19449 @emph{task `taskno`}
19451 @quotation
19453 This command allows switching to the task referred by @cite{taskno}. In
19454 particular, this allows browsing of the backtrace of the specified
19455 task. It is advisable to switch back to the original task before
19456 continuing execution otherwise the scheduling of the program may be
19457 perturbed.
19458 @end quotation
19459 @end itemize
19461 For more detailed information on the tasking support,
19462 see @cite{Debugging with GDB}.
19464 @geindex Debugging Generic Units
19466 @geindex Generics
19468 @node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
19469 @anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{17e}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{17f}
19470 @subsection Debugging Generic Units
19473 GNAT always uses code expansion for generic instantiation. This means that
19474 each time an instantiation occurs, a complete copy of the original code is
19475 made, with appropriate substitutions of formals by actuals.
19477 It is not possible to refer to the original generic entities in
19478 @cite{GDB}, but it is always possible to debug a particular instance of
19479 a generic, by using the appropriate expanded names. For example, if we have
19481 @quotation
19483 @example
19484 procedure g is
19486    generic package k is
19487       procedure kp (v1 : in out integer);
19488    end k;
19490    package body k is
19491       procedure kp (v1 : in out integer) is
19492       begin
19493          v1 := v1 + 1;
19494       end kp;
19495    end k;
19497    package k1 is new k;
19498    package k2 is new k;
19500    var : integer := 1;
19502 begin
19503    k1.kp (var);
19504    k2.kp (var);
19505    k1.kp (var);
19506    k2.kp (var);
19507 end;
19508 @end example
19509 @end quotation
19511 Then to break on a call to procedure kp in the k2 instance, simply
19512 use the command:
19514 @quotation
19516 @example
19517 (gdb) break g.k2.kp
19518 @end example
19519 @end quotation
19521 When the breakpoint occurs, you can step through the code of the
19522 instance in the normal manner and examine the values of local variables, as for
19523 other units.
19525 @geindex Remote Debugging with gdbserver
19527 @node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
19528 @anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{180}@anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{181}
19529 @subsection Remote Debugging with gdbserver
19532 On platforms where gdbserver is supported, it is possible to use this tool
19533 to debug your application remotely.  This can be useful in situations
19534 where the program needs to be run on a target host that is different
19535 from the host used for development, particularly when the target has
19536 a limited amount of resources (either CPU and/or memory).
19538 To do so, start your program using gdbserver on the target machine.
19539 gdbserver then automatically suspends the execution of your program
19540 at its entry point, waiting for a debugger to connect to it.  The
19541 following commands starts an application and tells gdbserver to
19542 wait for a connection with the debugger on localhost port 4444.
19544 @quotation
19546 @example
19547 $ gdbserver localhost:4444 program
19548 Process program created; pid = 5685
19549 Listening on port 4444
19550 @end example
19551 @end quotation
19553 Once gdbserver has started listening, we can tell the debugger to establish
19554 a connection with this gdbserver, and then start the same debugging session
19555 as if the program was being debugged on the same host, directly under
19556 the control of GDB.
19558 @quotation
19560 @example
19561 $ gdb program
19562 (gdb) target remote targethost:4444
19563 Remote debugging using targethost:4444
19564 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19565 (gdb) b foo.adb:3
19566 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19567 (gdb) continue
19568 Continuing.
19570 Breakpoint 1, foo () at foo.adb:4
19571 4       end foo;
19572 @end example
19573 @end quotation
19575 It is also possible to use gdbserver to attach to an already running
19576 program, in which case the execution of that program is simply suspended
19577 until the connection between the debugger and gdbserver is established.
19579 For more information on how to use gdbserver, see the @emph{Using the gdbserver Program}
19580 section in @cite{Debugging with GDB}.
19581 GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
19583 @geindex Abnormal Termination or Failure to Terminate
19585 @node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
19586 @anchor{gnat_ugn/gnat_and_program_execution gnat-abnormal-termination-or-failure-to-terminate}@anchor{182}@anchor{gnat_ugn/gnat_and_program_execution id13}@anchor{183}
19587 @subsection GNAT Abnormal Termination or Failure to Terminate
19590 When presented with programs that contain serious errors in syntax
19591 or semantics,
19592 GNAT may on rare occasions  experience problems in operation, such
19593 as aborting with a
19594 segmentation fault or illegal memory access, raising an internal
19595 exception, terminating abnormally, or failing to terminate at all.
19596 In such cases, you can activate
19597 various features of GNAT that can help you pinpoint the construct in your
19598 program that is the likely source of the problem.
19600 The following strategies are presented in increasing order of
19601 difficulty, corresponding to your experience in using GNAT and your
19602 familiarity with compiler internals.
19605 @itemize *
19607 @item 
19608 Run @emph{gcc} with the @emph{-gnatf}. This first
19609 switch causes all errors on a given line to be reported. In its absence,
19610 only the first error on a line is displayed.
19612 The @emph{-gnatdO} switch causes errors to be displayed as soon as they
19613 are encountered, rather than after compilation is terminated. If GNAT
19614 terminates prematurely or goes into an infinite loop, the last error
19615 message displayed may help to pinpoint the culprit.
19617 @item 
19618 Run @emph{gcc} with the @emph{-v (verbose)} switch. In this
19619 mode, @emph{gcc} produces ongoing information about the progress of the
19620 compilation and provides the name of each procedure as code is
19621 generated. This switch allows you to find which Ada procedure was being
19622 compiled when it encountered a code generation problem.
19623 @end itemize
19625 @geindex -gnatdc switch
19628 @itemize *
19630 @item 
19631 Run @emph{gcc} with the @emph{-gnatdc} switch. This is a GNAT specific
19632 switch that does for the front-end what @emph{-v} does
19633 for the back end. The system prints the name of each unit,
19634 either a compilation unit or nested unit, as it is being analyzed.
19636 @item 
19637 Finally, you can start
19638 @cite{gdb} directly on the @cite{gnat1} executable. @cite{gnat1} is the
19639 front-end of GNAT, and can be run independently (normally it is just
19640 called from @emph{gcc}). You can use @cite{gdb} on @cite{gnat1} as you
19641 would on a C program (but @ref{16e,,The GNAT Debugger GDB} for caveats). The
19642 @cite{where} command is the first line of attack; the variable
19643 @cite{lineno} (seen by @cite{print lineno}), used by the second phase of
19644 @cite{gnat1} and by the @emph{gcc} backend, indicates the source line at
19645 which the execution stopped, and @cite{input_file name} indicates the name of
19646 the source file.
19647 @end itemize
19649 @node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
19650 @anchor{gnat_ugn/gnat_and_program_execution naming-conventions-for-gnat-source-files}@anchor{184}@anchor{gnat_ugn/gnat_and_program_execution id14}@anchor{185}
19651 @subsection Naming Conventions for GNAT Source Files
19654 In order to examine the workings of the GNAT system, the following
19655 brief description of its organization may be helpful:
19658 @itemize *
19660 @item 
19661 Files with prefix @code{sc} contain the lexical scanner.
19663 @item 
19664 All files prefixed with @code{par} are components of the parser. The
19665 numbers correspond to chapters of the Ada Reference Manual. For example,
19666 parsing of select statements can be found in @code{par-ch9.adb}.
19668 @item 
19669 All files prefixed with @code{sem} perform semantic analysis. The
19670 numbers correspond to chapters of the Ada standard. For example, all
19671 issues involving context clauses can be found in @code{sem_ch10.adb}. In
19672 addition, some features of the language require sufficient special processing
19673 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19674 dynamic dispatching, etc.
19676 @item 
19677 All files prefixed with @code{exp} perform normalization and
19678 expansion of the intermediate representation (abstract syntax tree, or AST).
19679 these files use the same numbering scheme as the parser and semantics files.
19680 For example, the construction of record initialization procedures is done in
19681 @code{exp_ch3.adb}.
19683 @item 
19684 The files prefixed with @code{bind} implement the binder, which
19685 verifies the consistency of the compilation, determines an order of
19686 elaboration, and generates the bind file.
19688 @item 
19689 The files @code{atree.ads} and @code{atree.adb} detail the low-level
19690 data structures used by the front-end.
19692 @item 
19693 The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
19694 the abstract syntax tree as produced by the parser.
19696 @item 
19697 The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
19698 all entities, computed during semantic analysis.
19700 @item 
19701 Library management issues are dealt with in files with prefix
19702 @code{lib}.
19704 @geindex Annex A (in Ada Reference Manual)
19706 @item 
19707 Ada files with the prefix @code{a-} are children of @cite{Ada}, as
19708 defined in Annex A.
19710 @geindex Annex B (in Ada reference Manual)
19712 @item 
19713 Files with prefix @code{i-} are children of @cite{Interfaces}, as
19714 defined in Annex B.
19716 @geindex System (package in Ada Reference Manual)
19718 @item 
19719 Files with prefix @code{s-} are children of @cite{System}. This includes
19720 both language-defined children and GNAT run-time routines.
19722 @geindex GNAT (package)
19724 @item 
19725 Files with prefix @code{g-} are children of @cite{GNAT}. These are useful
19726 general-purpose packages, fully documented in their specs. All
19727 the other @code{.c} files are modifications of common @emph{gcc} files.
19728 @end itemize
19730 @node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
19731 @anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{186}@anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{187}
19732 @subsection Getting Internal Debugging Information
19735 Most compilers have internal debugging switches and modes. GNAT
19736 does also, except GNAT internal debugging switches and modes are not
19737 secret. A summary and full description of all the compiler and binder
19738 debug flags are in the file @code{debug.adb}. You must obtain the
19739 sources of the compiler to see the full detailed effects of these flags.
19741 The switches that print the source of the program (reconstructed from
19742 the internal tree) are of general interest for user programs, as are the
19743 options to print
19744 the full internal tree, and the entity table (the symbol table
19745 information). The reconstructed source provides a readable version of the
19746 program after the front-end has completed analysis and  expansion,
19747 and is useful when studying the performance of specific constructs.
19748 For example, constraint checks are indicated, complex aggregates
19749 are replaced with loops and assignments, and tasking primitives
19750 are replaced with run-time calls.
19752 @geindex traceback
19754 @geindex stack traceback
19756 @geindex stack unwinding
19758 @node Stack Traceback,,Getting Internal Debugging Information,Running and Debugging Ada Programs
19759 @anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{188}@anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{189}
19760 @subsection Stack Traceback
19763 Traceback is a mechanism to display the sequence of subprogram calls that
19764 leads to a specified execution point in a program. Often (but not always)
19765 the execution point is an instruction at which an exception has been raised.
19766 This mechanism is also known as @emph{stack unwinding} because it obtains
19767 its information by scanning the run-time stack and recovering the activation
19768 records of all active subprograms. Stack unwinding is one of the most
19769 important tools for program debugging.
19771 The first entry stored in traceback corresponds to the deepest calling level,
19772 that is to say the subprogram currently executing the instruction
19773 from which we want to obtain the traceback.
19775 Note that there is no runtime performance penalty when stack traceback
19776 is enabled, and no exception is raised during program execution.
19778 @geindex traceback
19779 @geindex non-symbolic
19781 @menu
19782 * Non-Symbolic Traceback:: 
19783 * Symbolic Traceback:: 
19785 @end menu
19787 @node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
19788 @anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{18a}@anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{18b}
19789 @subsubsection Non-Symbolic Traceback
19792 Note: this feature is not supported on all platforms. See
19793 @code{GNAT.Traceback} spec in @code{g-traceb.ads}
19794 for a complete list of supported platforms.
19796 @subsubheading Tracebacks From an Unhandled Exception
19799 A runtime non-symbolic traceback is a list of addresses of call instructions.
19800 To enable this feature you must use the @emph{-E}
19801 @cite{gnatbind}'s option. With this option a stack traceback is stored as part
19802 of exception information. You can retrieve this information using the
19803 @cite{addr2line} tool.
19805 Here is a simple example:
19807 @quotation
19809 @example
19810 procedure STB is
19812    procedure P1 is
19813    begin
19814       raise Constraint_Error;
19815    end P1;
19817    procedure P2 is
19818    begin
19819       P1;
19820    end P2;
19822 begin
19823    P2;
19824 end STB;
19825 @end example
19827 @example
19828 $ gnatmake stb -bargs -E
19829 $ stb
19831 Execution terminated by unhandled exception
19832 Exception name: CONSTRAINT_ERROR
19833 Message: stb.adb:5
19834 Call stack traceback locations:
19835 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19836 @end example
19837 @end quotation
19839 As we see the traceback lists a sequence of addresses for the unhandled
19840 exception @cite{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19841 guess that this exception come from procedure P1. To translate these
19842 addresses into the source lines where the calls appear, the
19843 @cite{addr2line} tool, described below, is invaluable. The use of this tool
19844 requires the program to be compiled with debug information.
19846 @quotation
19848 @example
19849 $ gnatmake -g stb -bargs -E
19850 $ stb
19852 Execution terminated by unhandled exception
19853 Exception name: CONSTRAINT_ERROR
19854 Message: stb.adb:5
19855 Call stack traceback locations:
19856 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19858 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19859    0x4011f1 0x77e892a4
19861 00401373 at d:/stb/stb.adb:5
19862 0040138B at d:/stb/stb.adb:10
19863 0040139C at d:/stb/stb.adb:14
19864 00401335 at d:/stb/b~stb.adb:104
19865 004011C4 at /build/.../crt1.c:200
19866 004011F1 at /build/.../crt1.c:222
19867 77E892A4 in ?? at ??:0
19868 @end example
19869 @end quotation
19871 The @cite{addr2line} tool has several other useful options:
19873 @quotation
19876 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
19877 @item
19879 @code{--functions}
19881 @tab
19883 to get the function name corresponding to any location
19885 @item
19887 @code{--demangle=gnat}
19889 @tab
19891 to use the gnat decoding mode for the function names.
19892 Note that for binutils version 2.9.x the option is
19893 simply @code{--demangle}.
19895 @end multitable
19898 @example
19899 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19900    0x40139c 0x401335 0x4011c4 0x4011f1
19902 00401373 in stb.p1 at d:/stb/stb.adb:5
19903 0040138B in stb.p2 at d:/stb/stb.adb:10
19904 0040139C in stb at d:/stb/stb.adb:14
19905 00401335 in main at d:/stb/b~stb.adb:104
19906 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
19907 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
19908 @end example
19909 @end quotation
19911 From this traceback we can see that the exception was raised in
19912 @code{stb.adb} at line 5, which was reached from a procedure call in
19913 @code{stb.adb} at line 10, and so on. The @code{b~std.adb} is the binder file,
19914 which contains the call to the main program.
19915 @ref{11c,,Running gnatbind}. The remaining entries are assorted runtime routines,
19916 and the output will vary from platform to platform.
19918 It is also possible to use @cite{GDB} with these traceback addresses to debug
19919 the program. For example, we can break at a given code location, as reported
19920 in the stack traceback:
19922 @quotation
19924 @example
19925 $ gdb -nw stb
19926 @end example
19927 @end quotation
19929 Furthermore, this feature is not implemented inside Windows DLL. Only
19930 the non-symbolic traceback is reported in this case.
19932 @quotation
19934 @example
19935 (gdb) break *0x401373
19936 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19937 @end example
19938 @end quotation
19940 It is important to note that the stack traceback addresses
19941 do not change when debug information is included. This is particularly useful
19942 because it makes it possible to release software without debug information (to
19943 minimize object size), get a field report that includes a stack traceback
19944 whenever an internal bug occurs, and then be able to retrieve the sequence
19945 of calls with the same program compiled with debug information.
19947 @subsubheading Tracebacks From Exception Occurrences
19950 Non-symbolic tracebacks are obtained by using the @emph{-E} binder argument.
19951 The stack traceback is attached to the exception information string, and can
19952 be retrieved in an exception handler within the Ada program, by means of the
19953 Ada facilities defined in @cite{Ada.Exceptions}. Here is a simple example:
19955 @quotation
19957 @example
19958 with Ada.Text_IO;
19959 with Ada.Exceptions;
19961 procedure STB is
19963    use Ada;
19964    use Ada.Exceptions;
19966    procedure P1 is
19967       K : Positive := 1;
19968    begin
19969       K := K - 1;
19970    exception
19971       when E : others =>
19972          Text_IO.Put_Line (Exception_Information (E));
19973    end P1;
19975    procedure P2 is
19976    begin
19977       P1;
19978    end P2;
19980 begin
19981    P2;
19982 end STB;
19983 @end example
19984 @end quotation
19986 This program will output:
19988 @quotation
19990 @example
19991 $ stb
19993 Exception name: CONSTRAINT_ERROR
19994 Message: stb.adb:12
19995 Call stack traceback locations:
19996 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19997 @end example
19998 @end quotation
20000 @subsubheading Tracebacks From Anywhere in a Program
20003 It is also possible to retrieve a stack traceback from anywhere in a
20004 program. For this you need to
20005 use the @cite{GNAT.Traceback} API. This package includes a procedure called
20006 @cite{Call_Chain} that computes a complete stack traceback, as well as useful
20007 display procedures described below. It is not necessary to use the
20008 @emph{-E gnatbind} option in this case, because the stack traceback mechanism
20009 is invoked explicitly.
20011 In the following example we compute a traceback at a specific location in
20012 the program, and we display it using @cite{GNAT.Debug_Utilities.Image} to
20013 convert addresses to strings:
20015 @quotation
20017 @example
20018 with Ada.Text_IO;
20019 with GNAT.Traceback;
20020 with GNAT.Debug_Utilities;
20022 procedure STB is
20024    use Ada;
20025    use GNAT;
20026    use GNAT.Traceback;
20028    procedure P1 is
20029       TB  : Tracebacks_Array (1 .. 10);
20030       --  We are asking for a maximum of 10 stack frames.
20031       Len : Natural;
20032       --  Len will receive the actual number of stack frames returned.
20033    begin
20034       Call_Chain (TB, Len);
20036       Text_IO.Put ("In STB.P1 : ");
20038       for K in 1 .. Len loop
20039          Text_IO.Put (Debug_Utilities.Image (TB (K)));
20040          Text_IO.Put (' ');
20041       end loop;
20043       Text_IO.New_Line;
20044    end P1;
20046    procedure P2 is
20047    begin
20048       P1;
20049    end P2;
20051 begin
20052    P2;
20053 end STB;
20054 @end example
20056 @example
20057 $ gnatmake -g stb
20058 $ stb
20060 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20061 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20062 @end example
20063 @end quotation
20065 You can then get further information by invoking the @cite{addr2line}
20066 tool as described earlier (note that the hexadecimal addresses
20067 need to be specified in C format, with a leading '0x').
20069 @geindex traceback
20070 @geindex symbolic
20072 @node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
20073 @anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{18c}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{18d}
20074 @subsubsection Symbolic Traceback
20077 A symbolic traceback is a stack traceback in which procedure names are
20078 associated with each code location.
20080 Note that this feature is not supported on all platforms. See
20081 @code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
20082 list of currently supported platforms.
20084 Note that the symbolic traceback requires that the program be compiled
20085 with debug information. If it is not compiled with debug information
20086 only the non-symbolic information will be valid.
20088 @subsubheading Tracebacks From Exception Occurrences
20091 Here is an example:
20093 @quotation
20095 @example
20096 with Ada.Text_IO;
20097 with GNAT.Traceback.Symbolic;
20099 procedure STB is
20101    procedure P1 is
20102    begin
20103       raise Constraint_Error;
20104    end P1;
20106    procedure P2 is
20107    begin
20108       P1;
20109    end P2;
20111    procedure P3 is
20112    begin
20113       P2;
20114    end P3;
20116 begin
20117    P3;
20118 exception
20119    when E : others =>
20120       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20121 end STB;
20122 @end example
20124 @example
20125 $ gnatmake -g .\stb -bargs -E
20126 $ stb
20128 0040149F in stb.p1 at stb.adb:8
20129 004014B7 in stb.p2 at stb.adb:13
20130 004014CF in stb.p3 at stb.adb:18
20131 004015DD in ada.stb at stb.adb:22
20132 00401461 in main at b~stb.adb:168
20133 004011C4 in __mingw_CRTStartup at crt1.c:200
20134 004011F1 in mainCRTStartup at crt1.c:222
20135 77E892A4 in ?? at ??:0
20136 @end example
20137 @end quotation
20139 In the above example the @code{.\} syntax in the @emph{gnatmake} command
20140 is currently required by @emph{addr2line} for files that are in
20141 the current working directory.
20142 Moreover, the exact sequence of linker options may vary from platform
20143 to platform.
20144 The above @emph{-largs} section is for Windows platforms. By contrast,
20145 under Unix there is no need for the @emph{-largs} section.
20146 Differences across platforms are due to details of linker implementation.
20148 @subsubheading Tracebacks From Anywhere in a Program
20151 It is possible to get a symbolic stack traceback
20152 from anywhere in a program, just as for non-symbolic tracebacks.
20153 The first step is to obtain a non-symbolic
20154 traceback, and then call @cite{Symbolic_Traceback} to compute the symbolic
20155 information. Here is an example:
20157 @quotation
20159 @example
20160 with Ada.Text_IO;
20161 with GNAT.Traceback;
20162 with GNAT.Traceback.Symbolic;
20164 procedure STB is
20166    use Ada;
20167    use GNAT.Traceback;
20168    use GNAT.Traceback.Symbolic;
20170    procedure P1 is
20171       TB  : Tracebacks_Array (1 .. 10);
20172       --  We are asking for a maximum of 10 stack frames.
20173       Len : Natural;
20174       --  Len will receive the actual number of stack frames returned.
20175    begin
20176       Call_Chain (TB, Len);
20177       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20178    end P1;
20180    procedure P2 is
20181    begin
20182       P1;
20183    end P2;
20185 begin
20186    P2;
20187 end STB;
20188 @end example
20189 @end quotation
20191 @subsubheading Automatic Symbolic Tracebacks
20194 Symbolic tracebacks may also be enabled by using the -Es switch to gnatbind (as
20195 in @cite{gprbuild -g ... -bargs -Es}).
20196 This will cause the Exception_Information to contain a symbolic traceback,
20197 which will also be printed if an unhandled exception terminates the
20198 program.
20200 @geindex Code Coverage
20202 @geindex Profiling
20204 @node Code Coverage and Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
20205 @anchor{gnat_ugn/gnat_and_program_execution id19}@anchor{168}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-and-profiling}@anchor{25}
20206 @section Code Coverage and Profiling
20209 This section describes how to use the @cite{gcov} coverage testing tool and
20210 the @cite{gprof} profiler tool on Ada programs.
20212 @geindex gcov
20214 @menu
20215 * Code Coverage of Ada Programs with gcov:: 
20216 * Profiling an Ada Program with gprof:: 
20218 @end menu
20220 @node Code Coverage of Ada Programs with gcov,Profiling an Ada Program with gprof,,Code Coverage and Profiling
20221 @anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{18e}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-of-ada-programs-with-gcov}@anchor{18f}
20222 @subsection Code Coverage of Ada Programs with gcov
20225 @cite{gcov} is a test coverage program: it analyzes the execution of a given
20226 program on selected tests, to help you determine the portions of the program
20227 that are still untested.
20229 @cite{gcov} is part of the GCC suite, and is described in detail in the GCC
20230 User's Guide. You can refer to this documentation for a more complete
20231 description.
20233 This chapter provides a quick startup guide, and
20234 details some GNAT-specific features.
20236 @menu
20237 * Quick startup guide:: 
20238 * GNAT specifics:: 
20240 @end menu
20242 @node Quick startup guide,GNAT specifics,,Code Coverage of Ada Programs with gcov
20243 @anchor{gnat_ugn/gnat_and_program_execution id21}@anchor{190}@anchor{gnat_ugn/gnat_and_program_execution quick-startup-guide}@anchor{191}
20244 @subsubsection Quick startup guide
20247 In order to perform coverage analysis of a program using @cite{gcov}, several
20248 steps are needed:
20251 @enumerate 
20253 @item 
20254 Instrument the code during the compilation process,
20256 @item 
20257 Execute the instrumented program, and
20259 @item 
20260 Invoke the @cite{gcov} tool to generate the coverage results.
20261 @end enumerate
20263 @geindex -fprofile-arcs (gcc)
20265 @geindex -ftest-coverage (gcc
20267 @geindex -fprofile-arcs (gnatbind)
20269 The code instrumentation needed by gcov is created at the object level.
20270 The source code is not modified in any way, because the instrumentation code is
20271 inserted by gcc during the compilation process. To compile your code with code
20272 coverage activated, you need to recompile your whole project using the
20273 switches
20274 @cite{-fprofile-arcs} and @cite{-ftest-coverage}, and link it using
20275 @cite{-fprofile-arcs}.
20277 @quotation
20279 @example
20280 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \\
20281    -largs -fprofile-arcs
20282 @end example
20283 @end quotation
20285 This compilation process will create @code{.gcno} files together with
20286 the usual object files.
20288 Once the program is compiled with coverage instrumentation, you can
20289 run it as many times as needed -- on portions of a test suite for
20290 example. The first execution will produce @code{.gcda} files at the
20291 same location as the @code{.gcno} files.  Subsequent executions
20292 will update those files, so that a cumulative result of the covered
20293 portions of the program is generated.
20295 Finally, you need to call the @cite{gcov} tool. The different options of
20296 @cite{gcov} are described in the GCC User's Guide, section 'Invoking gcov'.
20298 This will create annotated source files with a @code{.gcov} extension:
20299 @code{my_main.adb} file will be analyzed in @code{my_main.adb.gcov}.
20301 @node GNAT specifics,,Quick startup guide,Code Coverage of Ada Programs with gcov
20302 @anchor{gnat_ugn/gnat_and_program_execution gnat-specifics}@anchor{192}@anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{193}
20303 @subsubsection GNAT specifics
20306 Because of Ada semantics, portions of the source code may be shared among
20307 several object files. This is the case for example when generics are
20308 involved, when inlining is active  or when declarations generate  initialisation
20309 calls. In order to take
20310 into account this shared code, you need to call @cite{gcov} on all
20311 source files of the tested program at once.
20313 The list of source files might exceed the system's maximum command line
20314 length. In order to bypass this limitation, a new mechanism has been
20315 implemented in @cite{gcov}: you can now list all your project's files into a
20316 text file, and provide this file to gcov as a parameter,  preceded by a @code{@@}
20317 (e.g. @code{gcov @@mysrclist.txt}).
20319 Note that on AIX compiling a static library with @cite{-fprofile-arcs} is
20320 not supported as there can be unresolved symbols during the final link.
20322 @geindex gprof
20324 @geindex Profiling
20326 @node Profiling an Ada Program with gprof,,Code Coverage of Ada Programs with gcov,Code Coverage and Profiling
20327 @anchor{gnat_ugn/gnat_and_program_execution profiling-an-ada-program-with-gprof}@anchor{194}@anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{195}
20328 @subsection Profiling an Ada Program with gprof
20331 This section is not meant to be an exhaustive documentation of @cite{gprof}.
20332 Full documentation for it can be found in the @cite{GNU Profiler User's Guide}
20333 documentation that is part of this GNAT distribution.
20335 Profiling a program helps determine the parts of a program that are executed
20336 most often, and are therefore the most time-consuming.
20338 @cite{gprof} is the standard GNU profiling tool; it has been enhanced to
20339 better handle Ada programs and multitasking.
20340 It is currently supported on the following platforms
20343 @itemize *
20345 @item 
20346 linux x86/x86_64
20348 @item 
20349 solaris sparc/sparc64/x86
20351 @item 
20352 windows x86
20353 @end itemize
20355 In order to profile a program using @cite{gprof}, several steps are needed:
20358 @enumerate 
20360 @item 
20361 Instrument the code, which requires a full recompilation of the project with the
20362 proper switches.
20364 @item 
20365 Execute the program under the analysis conditions, i.e. with the desired
20366 input.
20368 @item 
20369 Analyze the results using the @cite{gprof} tool.
20370 @end enumerate
20372 The following sections detail the different steps, and indicate how
20373 to interpret the results.
20375 @menu
20376 * Compilation for profiling:: 
20377 * Program execution:: 
20378 * Running gprof:: 
20379 * Interpretation of profiling results:: 
20381 @end menu
20383 @node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
20384 @anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{196}@anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{197}
20385 @subsubsection Compilation for profiling
20388 @geindex -pg (gcc)
20389 @geindex for profiling
20391 @geindex -pg (gnatlink)
20392 @geindex for profiling
20394 In order to profile a program the first step is to tell the compiler
20395 to generate the necessary profiling information. The compiler switch to be used
20396 is @code{-pg}, which must be added to other compilation switches. This
20397 switch needs to be specified both during compilation and link stages, and can
20398 be specified once when using gnatmake:
20400 @quotation
20402 @example
20403 $ gnatmake -f -pg -P my_project
20404 @end example
20405 @end quotation
20407 Note that only the objects that were compiled with the @code{-pg} switch will
20408 be profiled; if you need to profile your whole project, use the @code{-f}
20409 gnatmake switch to force full recompilation.
20411 @node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
20412 @anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{198}@anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{199}
20413 @subsubsection Program execution
20416 Once the program has been compiled for profiling, you can run it as usual.
20418 The only constraint imposed by profiling is that the program must terminate
20419 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20420 properly analyzed.
20422 Once the program completes execution, a data file called @code{gmon.out} is
20423 generated in the directory where the program was launched from. If this file
20424 already exists, it will be overwritten.
20426 @node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
20427 @anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{19a}@anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{19b}
20428 @subsubsection Running gprof
20431 The @cite{gprof} tool is called as follow:
20433 @quotation
20435 @example
20436 $ gprof my_prog gmon.out
20437 @end example
20438 @end quotation
20440 or simply:
20442 @quotation
20444 @example
20445 $  gprof my_prog
20446 @end example
20447 @end quotation
20449 The complete form of the gprof command line is the following:
20451 @quotation
20453 @example
20454 $ gprof [switches] [executable [data-file]]
20455 @end example
20456 @end quotation
20458 @cite{gprof} supports numerous switches. The order of these
20459 switch does not matter. The full list of options can be found in
20460 the GNU Profiler User's Guide documentation that comes with this documentation.
20462 The following is the subset of those switches that is most relevant:
20464 @geindex --demangle (gprof)
20467 @table @asis
20469 @item @code{--demangle[=@emph{style}]}, @code{--no-demangle}
20471 These options control whether symbol names should be demangled when
20472 printing output.  The default is to demangle C++ symbols.  The
20473 @code{--no-demangle} option may be used to turn off demangling. Different
20474 compilers have different mangling styles.  The optional demangling style
20475 argument can be used to choose an appropriate demangling style for your
20476 compiler, in particular Ada symbols generated by GNAT can be demangled using
20477 @code{--demangle=gnat}.
20478 @end table
20480 @geindex -e (gprof)
20483 @table @asis
20485 @item @code{-e @emph{function_name}}
20487 The @code{-e @emph{function}} option tells @cite{gprof} not to print
20488 information about the function @cite{function_name} (and its
20489 children...) in the call graph.  The function will still be listed
20490 as a child of any functions that call it, but its index number will be
20491 shown as @code{[not printed]}.  More than one @code{-e} option may be
20492 given; only one @cite{function_name} may be indicated with each @code{-e}
20493 option.
20494 @end table
20496 @geindex -E (gprof)
20499 @table @asis
20501 @item @code{-E @emph{function_name}}
20503 The @code{-E @emph{function}} option works like the @code{-e} option, but
20504 execution time spent in the function (and children who were not called from
20505 anywhere else), will not be used to compute the percentages-of-time for
20506 the call graph.  More than one @code{-E} option may be given; only one
20507 @cite{function_name} may be indicated with each @code{-E} option.
20508 @end table
20510 @geindex -f (gprof)
20513 @table @asis
20515 @item @code{-f @emph{function_name}}
20517 The @code{-f @emph{function}} option causes @cite{gprof} to limit the
20518 call graph to the function @cite{function_name} and its children (and
20519 their children...).  More than one @code{-f} option may be given;
20520 only one @cite{function_name} may be indicated with each @code{-f}
20521 option.
20522 @end table
20524 @geindex -F (gprof)
20527 @table @asis
20529 @item @code{-F @emph{function_name}}
20531 The @code{-F @emph{function}} option works like the @code{-f} option, but
20532 only time spent in the function and its children (and their
20533 children...) will be used to determine total-time and
20534 percentages-of-time for the call graph.  More than one @code{-F} option
20535 may be given; only one @cite{function_name} may be indicated with each
20536 @code{-F} option.  The @code{-F} option overrides the @code{-E} option.
20537 @end table
20539 @node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
20540 @anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{19c}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{19d}
20541 @subsubsection Interpretation of profiling results
20544 The results of the profiling analysis are represented by two arrays: the
20545 'flat profile' and the 'call graph'. Full documentation of those outputs
20546 can be found in the GNU Profiler User's Guide.
20548 The flat profile shows the time spent in each function of the program, and how
20549 many time it has been called. This allows you to locate easily the most
20550 time-consuming functions.
20552 The call graph shows, for each subprogram, the subprograms that call it,
20553 and the subprograms that it calls. It also provides an estimate of the time
20554 spent in each of those callers/called subprograms.
20556 @node Improving Performance,Overflow Check Handling in GNAT,Code Coverage and Profiling,GNAT and Program Execution
20557 @anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{26}@anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{169}
20558 @section Improving Performance
20561 @geindex Improving performance
20563 This section presents several topics related to program performance.
20564 It first describes some of the tradeoffs that need to be considered
20565 and some of the techniques for making your program run faster.
20568 It then documents the unused subprogram/data elimination feature,
20569 which can reduce the size of program executables.
20571 @menu
20572 * Performance Considerations:: 
20573 * Text_IO Suggestions:: 
20574 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
20576 @end menu
20578 @node Performance Considerations,Text_IO Suggestions,,Improving Performance
20579 @anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{19e}@anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{19f}
20580 @subsection Performance Considerations
20583 The GNAT system provides a number of options that allow a trade-off
20584 between
20587 @itemize *
20589 @item 
20590 performance of the generated code
20592 @item 
20593 speed of compilation
20595 @item 
20596 minimization of dependences and recompilation
20598 @item 
20599 the degree of run-time checking.
20600 @end itemize
20602 The defaults (if no options are selected) aim at improving the speed
20603 of compilation and minimizing dependences, at the expense of performance
20604 of the generated code:
20607 @itemize *
20609 @item 
20610 no optimization
20612 @item 
20613 no inlining of subprogram calls
20615 @item 
20616 all run-time checks enabled except overflow and elaboration checks
20617 @end itemize
20619 These options are suitable for most program development purposes. This
20620 section describes how you can modify these choices, and also provides
20621 some guidelines on debugging optimized code.
20623 @menu
20624 * Controlling Run-Time Checks:: 
20625 * Use of Restrictions:: 
20626 * Optimization Levels:: 
20627 * Debugging Optimized Code:: 
20628 * Inlining of Subprograms:: 
20629 * Floating_Point_Operations:: 
20630 * Vectorization of loops:: 
20631 * Other Optimization Switches:: 
20632 * Optimization and Strict Aliasing:: 
20633 * Aliased Variables and Optimization:: 
20634 * Atomic Variables and Optimization:: 
20635 * Passive Task Optimization:: 
20637 @end menu
20639 @node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
20640 @anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{1a0}@anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{1a1}
20641 @subsubsection Controlling Run-Time Checks
20644 By default, GNAT generates all run-time checks, except stack overflow
20645 checks, and checks for access before elaboration on subprogram
20646 calls. The latter are not required in default mode, because all
20647 necessary checking is done at compile time.
20649 @geindex -gnatp (gcc)
20651 @geindex -gnato (gcc)
20653 The gnat switch, @emph{-gnatp} allows this default to be modified. See
20654 @ref{f9,,Run-Time Checks}.
20656 Our experience is that the default is suitable for most development
20657 purposes.
20659 Elaboration checks are off by default, and also not needed by default, since
20660 GNAT uses a static elaboration analysis approach that avoids the need for
20661 run-time checking. This manual contains a full chapter discussing the issue
20662 of elaboration checks, and if the default is not satisfactory for your use,
20663 you should read this chapter.
20665 For validity checks, the minimal checks required by the Ada Reference
20666 Manual (for case statements and assignments to array elements) are on
20667 by default. These can be suppressed by use of the @emph{-gnatVn} switch.
20668 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
20669 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
20670 it may be reasonable to routinely use @emph{-gnatVn}. Validity checks
20671 are also suppressed entirely if @emph{-gnatp} is used.
20673 @geindex Overflow checks
20675 @geindex Checks
20676 @geindex overflow
20678 @geindex Suppress
20680 @geindex Unsuppress
20682 @geindex pragma Suppress
20684 @geindex pragma Unsuppress
20686 Note that the setting of the switches controls the default setting of
20687 the checks. They may be modified using either @cite{pragma Suppress} (to
20688 remove checks) or @cite{pragma Unsuppress} (to add back suppressed
20689 checks) in the program source.
20691 @node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
20692 @anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{1a2}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{1a3}
20693 @subsubsection Use of Restrictions
20696 The use of pragma Restrictions allows you to control which features are
20697 permitted in your program. Apart from the obvious point that if you avoid
20698 relatively expensive features like finalization (enforceable by the use
20699 of pragma Restrictions (No_Finalization), the use of this pragma does not
20700 affect the generated code in most cases.
20702 One notable exception to this rule is that the possibility of task abort
20703 results in some distributed overhead, particularly if finalization or
20704 exception handlers are used. The reason is that certain sections of code
20705 have to be marked as non-abortable.
20707 If you use neither the @cite{abort} statement, nor asynchronous transfer
20708 of control (@cite{select ... then abort}), then this distributed overhead
20709 is removed, which may have a general positive effect in improving
20710 overall performance.  Especially code involving frequent use of tasking
20711 constructs and controlled types will show much improved performance.
20712 The relevant restrictions pragmas are
20714 @quotation
20716 @example
20717 pragma Restrictions (No_Abort_Statements);
20718 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
20719 @end example
20720 @end quotation
20722 It is recommended that these restriction pragmas be used if possible. Note
20723 that this also means that you can write code without worrying about the
20724 possibility of an immediate abort at any point.
20726 @node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
20727 @anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{1a4}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{fc}
20728 @subsubsection Optimization Levels
20731 @geindex -O (gcc)
20733 Without any optimization option,
20734 the compiler's goal is to reduce the cost of
20735 compilation and to make debugging produce the expected results.
20736 Statements are independent: if you stop the program with a breakpoint between
20737 statements, you can then assign a new value to any variable or change
20738 the program counter to any other statement in the subprogram and get exactly
20739 the results you would expect from the source code.
20741 Turning on optimization makes the compiler attempt to improve the
20742 performance and/or code size at the expense of compilation time and
20743 possibly the ability to debug the program.
20745 If you use multiple
20746 -O options, with or without level numbers,
20747 the last such option is the one that is effective.
20749 The default is optimization off. This results in the fastest compile
20750 times, but GNAT makes absolutely no attempt to optimize, and the
20751 generated programs are considerably larger and slower than when
20752 optimization is enabled. You can use the
20753 @emph{-O} switch (the permitted forms are @emph{-O0}, @emph{-O1}
20754 @emph{-O2}, @emph{-O3}, and @emph{-Os})
20755 to @emph{gcc} to control the optimization level:
20758 @itemize *
20760 @item 
20762 @table @asis
20764 @item @emph{-O0}
20766 No optimization (the default);
20767 generates unoptimized code but has
20768 the fastest compilation time.
20770 Note that many other compilers do fairly extensive optimization
20771 even if 'no optimization' is specified. With gcc, it is
20772 very unusual to use -O0 for production if
20773 execution time is of any concern, since -O0
20774 really does mean no optimization at all. This difference between
20775 gcc and other compilers should be kept in mind when doing
20776 performance comparisons.
20777 @end table
20779 @item 
20781 @table @asis
20783 @item @emph{-O1}
20785 Moderate optimization;
20786 optimizes reasonably well but does not
20787 degrade compilation time significantly.
20788 @end table
20790 @item 
20792 @table @asis
20794 @item @emph{-O2}
20796 Full optimization;
20797 generates highly optimized code and has
20798 the slowest compilation time.
20799 @end table
20801 @item 
20803 @table @asis
20805 @item @emph{-O3}
20807 Full optimization as in @emph{-O2};
20808 also uses more aggressive automatic inlining of subprograms within a unit
20809 (@ref{10f,,Inlining of Subprograms}) and attempts to vectorize loops.
20810 @end table
20812 @item 
20814 @table @asis
20816 @item @emph{-Os}
20818 Optimize space usage (code and data) of resulting program.
20819 @end table
20820 @end itemize
20822 Higher optimization levels perform more global transformations on the
20823 program and apply more expensive analysis algorithms in order to generate
20824 faster and more compact code. The price in compilation time, and the
20825 resulting improvement in execution time,
20826 both depend on the particular application and the hardware environment.
20827 You should experiment to find the best level for your application.
20829 Since the precise set of optimizations done at each level will vary from
20830 release to release (and sometime from target to target), it is best to think
20831 of the optimization settings in general terms.
20832 See the @emph{Options That Control Optimization} section in
20833 @cite{Using the GNU Compiler Collection (GCC)}
20834 for details about
20835 the @emph{-O} settings and a number of @emph{-f} options that
20836 individually enable or disable specific optimizations.
20838 Unlike some other compilation systems, @emph{gcc} has
20839 been tested extensively at all optimization levels. There are some bugs
20840 which appear only with optimization turned on, but there have also been
20841 bugs which show up only in @emph{unoptimized} code. Selecting a lower
20842 level of optimization does not improve the reliability of the code
20843 generator, which in practice is highly reliable at all optimization
20844 levels.
20846 Note regarding the use of @emph{-O3}: The use of this optimization level
20847 is generally discouraged with GNAT, since it often results in larger
20848 executables which may run more slowly. See further discussion of this point
20849 in @ref{10f,,Inlining of Subprograms}.
20851 @node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
20852 @anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{1a5}@anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{1a6}
20853 @subsubsection Debugging Optimized Code
20856 @geindex Debugging optimized code
20858 @geindex Optimization and debugging
20860 Although it is possible to do a reasonable amount of debugging at
20861 nonzero optimization levels,
20862 the higher the level the more likely that
20863 source-level constructs will have been eliminated by optimization.
20864 For example, if a loop is strength-reduced, the loop
20865 control variable may be completely eliminated and thus cannot be
20866 displayed in the debugger.
20867 This can only happen at @emph{-O2} or @emph{-O3}.
20868 Explicit temporary variables that you code might be eliminated at
20869 level @emph{-O1} or higher.
20871 @geindex -g (gcc)
20873 The use of the @emph{-g} switch,
20874 which is needed for source-level debugging,
20875 affects the size of the program executable on disk,
20876 and indeed the debugging information can be quite large.
20877 However, it has no effect on the generated code (and thus does not
20878 degrade performance)
20880 Since the compiler generates debugging tables for a compilation unit before
20881 it performs optimizations, the optimizing transformations may invalidate some
20882 of the debugging data.  You therefore need to anticipate certain
20883 anomalous situations that may arise while debugging optimized code.
20884 These are the most common cases:
20887 @itemize *
20889 @item 
20890 @emph{The 'hopping Program Counter':}  Repeated @cite{step} or @cite{next}
20891 commands show
20892 the PC bouncing back and forth in the code.  This may result from any of
20893 the following optimizations:
20896 @itemize -
20898 @item 
20899 @emph{Common subexpression elimination:} using a single instance of code for a
20900 quantity that the source computes several times.  As a result you
20901 may not be able to stop on what looks like a statement.
20903 @item 
20904 @emph{Invariant code motion:} moving an expression that does not change within a
20905 loop, to the beginning of the loop.
20907 @item 
20908 @emph{Instruction scheduling:} moving instructions so as to
20909 overlap loads and stores (typically) with other code, or in
20910 general to move computations of values closer to their uses. Often
20911 this causes you to pass an assignment statement without the assignment
20912 happening and then later bounce back to the statement when the
20913 value is actually needed.  Placing a breakpoint on a line of code
20914 and then stepping over it may, therefore, not always cause all the
20915 expected side-effects.
20916 @end itemize
20918 @item 
20919 @emph{The 'big leap':} More commonly known as @emph{cross-jumping}, in which
20920 two identical pieces of code are merged and the program counter suddenly
20921 jumps to a statement that is not supposed to be executed, simply because
20922 it (and the code following) translates to the same thing as the code
20923 that @emph{was} supposed to be executed.  This effect is typically seen in
20924 sequences that end in a jump, such as a @cite{goto}, a @cite{return}, or
20925 a @cite{break} in a C @cite{switch} statement.
20927 @item 
20928 @emph{The 'roving variable':} The symptom is an unexpected value in a variable.
20929 There are various reasons for this effect:
20932 @itemize -
20934 @item 
20935 In a subprogram prologue, a parameter may not yet have been moved to its
20936 'home'.
20938 @item 
20939 A variable may be dead, and its register re-used.  This is
20940 probably the most common cause.
20942 @item 
20943 As mentioned above, the assignment of a value to a variable may
20944 have been moved.
20946 @item 
20947 A variable may be eliminated entirely by value propagation or
20948 other means.  In this case, GCC may incorrectly generate debugging
20949 information for the variable
20950 @end itemize
20952 In general, when an unexpected value appears for a local variable or parameter
20953 you should first ascertain if that value was actually computed by
20954 your program, as opposed to being incorrectly reported by the debugger.
20955 Record fields or
20956 array elements in an object designated by an access value
20957 are generally less of a problem, once you have ascertained that the access
20958 value is sensible.
20959 Typically, this means checking variables in the preceding code and in the
20960 calling subprogram to verify that the value observed is explainable from other
20961 values (one must apply the procedure recursively to those
20962 other values); or re-running the code and stopping a little earlier
20963 (perhaps before the call) and stepping to better see how the variable obtained
20964 the value in question; or continuing to step @emph{from} the point of the
20965 strange value to see if code motion had simply moved the variable's
20966 assignments later.
20967 @end itemize
20969 In light of such anomalies, a recommended technique is to use @emph{-O0}
20970 early in the software development cycle, when extensive debugging capabilities
20971 are most needed, and then move to @emph{-O1} and later @emph{-O2} as
20972 the debugger becomes less critical.
20973 Whether to use the @emph{-g} switch in the release version is
20974 a release management issue.
20975 Note that if you use @emph{-g} you can then use the @emph{strip} program
20976 on the resulting executable,
20977 which removes both debugging information and global symbols.
20979 @node Inlining of Subprograms,Floating_Point_Operations,Debugging Optimized Code,Performance Considerations
20980 @anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{1a7}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{10f}
20981 @subsubsection Inlining of Subprograms
20984 A call to a subprogram in the current unit is inlined if all the
20985 following conditions are met:
20988 @itemize *
20990 @item 
20991 The optimization level is at least @emph{-O1}.
20993 @item 
20994 The called subprogram is suitable for inlining: It must be small enough
20995 and not contain something that @emph{gcc} cannot support in inlined
20996 subprograms.
20998 @geindex pragma Inline
21000 @geindex Inline
21002 @item 
21003 Any one of the following applies: @cite{pragma Inline} is applied to the
21004 subprogram; the subprogram is local to the unit and called once from
21005 within it; the subprogram is small and optimization level @emph{-O2} is
21006 specified; optimization level @emph{-O3} is specified.
21007 @end itemize
21009 Calls to subprograms in @emph{with}ed units are normally not inlined.
21010 To achieve actual inlining (that is, replacement of the call by the code
21011 in the body of the subprogram), the following conditions must all be true:
21014 @itemize *
21016 @item 
21017 The optimization level is at least @emph{-O1}.
21019 @item 
21020 The called subprogram is suitable for inlining: It must be small enough
21021 and not contain something that @emph{gcc} cannot support in inlined
21022 subprograms.
21024 @item 
21025 There is a @cite{pragma Inline} for the subprogram.
21027 @item 
21028 The @emph{-gnatn} switch is used on the command line.
21029 @end itemize
21031 Even if all these conditions are met, it may not be possible for
21032 the compiler to inline the call, due to the length of the body,
21033 or features in the body that make it impossible for the compiler
21034 to do the inlining.
21036 Note that specifying the @emph{-gnatn} switch causes additional
21037 compilation dependencies. Consider the following:
21039 @quotation
21041 @example
21042 package R is
21043    procedure Q;
21044    pragma Inline (Q);
21045 end R;
21046 package body R is
21047    ...
21048 end R;
21050 with R;
21051 procedure Main is
21052 begin
21053    ...
21054    R.Q;
21055 end Main;
21056 @end example
21057 @end quotation
21059 With the default behavior (no @emph{-gnatn} switch specified), the
21060 compilation of the @cite{Main} procedure depends only on its own source,
21061 @code{main.adb}, and the spec of the package in file @code{r.ads}. This
21062 means that editing the body of @cite{R} does not require recompiling
21063 @cite{Main}.
21065 On the other hand, the call @cite{R.Q} is not inlined under these
21066 circumstances. If the @emph{-gnatn} switch is present when @cite{Main}
21067 is compiled, the call will be inlined if the body of @cite{Q} is small
21068 enough, but now @cite{Main} depends on the body of @cite{R} in
21069 @code{r.adb} as well as on the spec. This means that if this body is edited,
21070 the main program must be recompiled. Note that this extra dependency
21071 occurs whether or not the call is in fact inlined by @emph{gcc}.
21073 The use of front end inlining with @emph{-gnatN} generates similar
21074 additional dependencies.
21076 @geindex -fno-inline (gcc)
21078 Note: The @emph{-fno-inline} switch overrides all other conditions and ensures that
21079 no inlining occurs, unless requested with pragma Inline_Always for @emph{gcc}
21080 back-ends. The extra dependences resulting from @emph{-gnatn} will still be active,
21081 even if this switch is used to suppress the resulting inlining actions.
21083 @geindex -fno-inline-functions (gcc)
21085 Note: The @emph{-fno-inline-functions} switch can be used to prevent
21086 automatic inlining of subprograms if @emph{-O3} is used.
21088 @geindex -fno-inline-small-functions (gcc)
21090 Note: The @emph{-fno-inline-small-functions} switch can be used to prevent
21091 automatic inlining of small subprograms if @emph{-O2} is used.
21093 @geindex -fno-inline-functions-called-once (gcc)
21095 Note: The @emph{-fno-inline-functions-called-once} switch
21096 can be used to prevent inlining of subprograms local to the unit
21097 and called once from within it if @emph{-O1} is used.
21099 Note regarding the use of @emph{-O3}: @emph{-gnatn} is made up of two
21100 sub-switches @emph{-gnatn1} and @emph{-gnatn2} that can be directly
21101 specified in lieu of it, @emph{-gnatn} being translated into one of them
21102 based on the optimization level. With @emph{-O2} or below, @emph{-gnatn}
21103 is equivalent to @emph{-gnatn1} which activates pragma @cite{Inline} with
21104 moderate inlining across modules. With @emph{-O3}, @emph{-gnatn} is
21105 equivalent to @emph{-gnatn2} which activates pragma @cite{Inline} with
21106 full inlining across modules. If you have used pragma @cite{Inline} in
21107 appropriate cases, then it is usually much better to use @emph{-O2}
21108 and @emph{-gnatn} and avoid the use of @emph{-O3} which has the additional
21109 effect of inlining subprograms you did not think should be inlined. We have
21110 found that the use of @emph{-O3} may slow down the compilation and increase
21111 the code size by performing excessive inlining, leading to increased
21112 instruction cache pressure from the increased code size and thus minor
21113 performance improvements. So the bottom line here is that you should not
21114 automatically assume that @emph{-O3} is better than @emph{-O2}, and
21115 indeed you should use @emph{-O3} only if tests show that it actually
21116 improves performance for your program.
21118 @node Floating_Point_Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
21119 @anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{1a8}@anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{1a9}
21120 @subsubsection Floating_Point_Operations
21123 @geindex Floating-Point Operations
21125 On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
21126 64-bit standard IEEE floating-point representations, and operations will
21127 use standard IEEE arithmetic as provided by the processor. On most, but
21128 not all, architectures, the attribute Machine_Overflows is False for these
21129 types, meaning that the semantics of overflow is implementation-defined.
21130 In the case of GNAT, these semantics correspond to the normal IEEE
21131 treatment of infinities and NaN (not a number) values. For example,
21132 1.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
21133 avoiding explicit overflow checks, the performance is greatly improved
21134 on many targets. However, if required, floating-point overflow can be
21135 enabled by the use of the pragma Check_Float_Overflow.
21137 Another consideration that applies specifically to x86 32-bit
21138 architectures is which form of floating-point arithmetic is used.
21139 By default the operations use the old style x86 floating-point,
21140 which implements an 80-bit extended precision form (on these
21141 architectures the type Long_Long_Float corresponds to that form).
21142 In addition, generation of efficient code in this mode means that
21143 the extended precision form will be used for intermediate results.
21144 This may be helpful in improving the final precision of a complex
21145 expression. However it means that the results obtained on the x86
21146 will be different from those on other architectures, and for some
21147 algorithms, the extra intermediate precision can be detrimental.
21149 In addition to this old-style floating-point, all modern x86 chips
21150 implement an alternative floating-point operation model referred
21151 to as SSE2. In this model there is no extended form, and furthermore
21152 execution performance is significantly enhanced. To force GNAT to use
21153 this more modern form, use both of the switches:
21155 @quotation
21157 -msse2 -mfpmath=sse
21158 @end quotation
21160 A unit compiled with these switches will automatically use the more
21161 efficient SSE2 instruction set for Float and Long_Float operations.
21162 Note that the ABI has the same form for both floating-point models,
21163 so it is permissible to mix units compiled with and without these
21164 switches.
21166 @node Vectorization of loops,Other Optimization Switches,Floating_Point_Operations,Performance Considerations
21167 @anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{1aa}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{1ab}
21168 @subsubsection Vectorization of loops
21171 @geindex Optimization Switches
21173 You can take advantage of the auto-vectorizer present in the @emph{gcc}
21174 back end to vectorize loops with GNAT.  The corresponding command line switch
21175 is @emph{-ftree-vectorize} but, as it is enabled by default at @emph{-O3}
21176 and other aggressive optimizations helpful for vectorization also are enabled
21177 by default at this level, using @emph{-O3} directly is recommended.
21179 You also need to make sure that the target architecture features a supported
21180 SIMD instruction set.  For example, for the x86 architecture, you should at
21181 least specify @emph{-msse2} to get significant vectorization (but you don't
21182 need to specify it for x86-64 as it is part of the base 64-bit architecture).
21183 Similarly, for the PowerPC architecture, you should specify @emph{-maltivec}.
21185 The preferred loop form for vectorization is the @cite{for} iteration scheme.
21186 Loops with a @cite{while} iteration scheme can also be vectorized if they are
21187 very simple, but the vectorizer will quickly give up otherwise.  With either
21188 iteration scheme, the flow of control must be straight, in particular no
21189 @cite{exit} statement may appear in the loop body.  The loop may however
21190 contain a single nested loop, if it can be vectorized when considered alone:
21192 @quotation
21194 @example
21195 A : array (1..4, 1..4) of Long_Float;
21196 S : array (1..4) of Long_Float;
21198 procedure Sum is
21199 begin
21200    for I in A'Range(1) loop
21201       for J in A'Range(2) loop
21202          S (I) := S (I) + A (I, J);
21203       end loop;
21204    end loop;
21205 end Sum;
21206 @end example
21207 @end quotation
21209 The vectorizable operations depend on the targeted SIMD instruction set, but
21210 the adding and some of the multiplying operators are generally supported, as
21211 well as the logical operators for modular types. Note that compiling
21212 with @emph{-gnatp} might well reveal cases where some checks do thwart
21213 vectorization.
21215 Type conversions may also prevent vectorization if they involve semantics that
21216 are not directly supported by the code generator or the SIMD instruction set.
21217 A typical example is direct conversion from floating-point to integer types.
21218 The solution in this case is to use the following idiom:
21220 @quotation
21222 @example
21223 Integer (S'Truncation (F))
21224 @end example
21225 @end quotation
21227 if @cite{S} is the subtype of floating-point object @cite{F}.
21229 In most cases, the vectorizable loops are loops that iterate over arrays.
21230 All kinds of array types are supported, i.e. constrained array types with
21231 static bounds:
21233 @quotation
21235 @example
21236 type Array_Type is array (1 .. 4) of Long_Float;
21237 @end example
21238 @end quotation
21240 constrained array types with dynamic bounds:
21242 @quotation
21244 @example
21245 type Array_Type is array (1 .. Q.N) of Long_Float;
21247 type Array_Type is array (Q.K .. 4) of Long_Float;
21249 type Array_Type is array (Q.K .. Q.N) of Long_Float;
21250 @end example
21251 @end quotation
21253 or unconstrained array types:
21255 @quotation
21257 @example
21258 type Array_Type is array (Positive range <>) of Long_Float;
21259 @end example
21260 @end quotation
21262 The quality of the generated code decreases when the dynamic aspect of the
21263 array type increases, the worst code being generated for unconstrained array
21264 types.  This is so because, the less information the compiler has about the
21265 bounds of the array, the more fallback code it needs to generate in order to
21266 fix things up at run time.
21268 It is possible to specify that a given loop should be subject to vectorization
21269 preferably to other optimizations by means of pragma @cite{Loop_Optimize}:
21271 @quotation
21273 @example
21274 pragma Loop_Optimize (Vector);
21275 @end example
21276 @end quotation
21278 placed immediately within the loop will convey the appropriate hint to the
21279 compiler for this loop.
21281 It is also possible to help the compiler generate better vectorized code
21282 for a given loop by asserting that there are no loop-carried dependencies
21283 in the loop.  Consider for example the procedure:
21285 @quotation
21287 @example
21288 type Arr is array (1 .. 4) of Long_Float;
21290 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
21291 begin
21292   for I in Arr'Range loop
21293     R(I) := X(I) + Y(I);
21294   end loop;
21295 end;
21296 @end example
21297 @end quotation
21299 By default, the compiler cannot unconditionally vectorize the loop because
21300 assigning to a component of the array designated by R in one iteration could
21301 change the value read from the components of the array designated by X or Y
21302 in a later iteration.  As a result, the compiler will generate two versions
21303 of the loop in the object code, one vectorized and the other not vectorized,
21304 as well as a test to select the appropriate version at run time.  This can
21305 be overcome by another hint:
21307 @quotation
21309 @example
21310 pragma Loop_Optimize (Ivdep);
21311 @end example
21312 @end quotation
21314 placed immediately within the loop will tell the compiler that it can safely
21315 omit the non-vectorized version of the loop as well as the run-time test.
21317 @node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
21318 @anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{1ac}@anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{1ad}
21319 @subsubsection Other Optimization Switches
21322 @geindex Optimization Switches
21324 Since @cite{GNAT} uses the @emph{gcc} back end, all the specialized
21325 @emph{gcc} optimization switches are potentially usable. These switches
21326 have not been extensively tested with GNAT but can generally be expected
21327 to work. Examples of switches in this category are @emph{-funroll-loops}
21328 and the various target-specific @emph{-m} options (in particular, it has
21329 been observed that @emph{-march=xxx} can significantly improve performance
21330 on appropriate machines). For full details of these switches, see
21331 the @cite{Submodel Options} section in the @cite{Hardware Models and Configurations}
21332 chapter of @cite{Using the GNU Compiler Collection (GCC)}.
21334 @node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
21335 @anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{f3}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{1ae}
21336 @subsubsection Optimization and Strict Aliasing
21339 @geindex Aliasing
21341 @geindex Strict Aliasing
21343 @geindex No_Strict_Aliasing
21345 The strong typing capabilities of Ada allow an optimizer to generate
21346 efficient code in situations where other languages would be forced to
21347 make worst case assumptions preventing such optimizations. Consider
21348 the following example:
21350 @quotation
21352 @example
21353 procedure R is
21354    type Int1 is new Integer;
21355    type Int2 is new Integer;
21356    type Int1A is access Int1;
21357    type Int2A is access Int2;
21358    Int1V : Int1A;
21359    Int2V : Int2A;
21360    ...
21362 begin
21363    ...
21364    for J in Data'Range loop
21365       if Data (J) = Int1V.all then
21366          Int2V.all := Int2V.all + 1;
21367       end if;
21368    end loop;
21369    ...
21370 end R;
21371 @end example
21372 @end quotation
21374 In this example, since the variable @cite{Int1V} can only access objects
21375 of type @cite{Int1}, and @cite{Int2V} can only access objects of type
21376 @cite{Int2}, there is no possibility that the assignment to
21377 @cite{Int2V.all} affects the value of @cite{Int1V.all}. This means that
21378 the compiler optimizer can "know" that the value @cite{Int1V.all} is constant
21379 for all iterations of the loop and avoid the extra memory reference
21380 required to dereference it each time through the loop.
21382 This kind of optimization, called strict aliasing analysis, is
21383 triggered by specifying an optimization level of @emph{-O2} or
21384 higher or @emph{-Os} and allows @cite{GNAT} to generate more efficient code
21385 when access values are involved.
21387 However, although this optimization is always correct in terms of
21388 the formal semantics of the Ada Reference Manual, difficulties can
21389 arise if features like @cite{Unchecked_Conversion} are used to break
21390 the typing system. Consider the following complete program example:
21392 @quotation
21394 @example
21395 package p1 is
21396    type int1 is new integer;
21397    type int2 is new integer;
21398    type a1 is access int1;
21399    type a2 is access int2;
21400 end p1;
21402 with p1; use p1;
21403 package p2 is
21404    function to_a2 (Input : a1) return a2;
21405 end p2;
21407 with Unchecked_Conversion;
21408 package body p2 is
21409    function to_a2 (Input : a1) return a2 is
21410       function to_a2u is
21411         new Unchecked_Conversion (a1, a2);
21412    begin
21413       return to_a2u (Input);
21414    end to_a2;
21415 end p2;
21417 with p2; use p2;
21418 with p1; use p1;
21419 with Text_IO; use Text_IO;
21420 procedure m is
21421    v1 : a1 := new int1;
21422    v2 : a2 := to_a2 (v1);
21423 begin
21424    v1.all := 1;
21425    v2.all := 0;
21426    put_line (int1'image (v1.all));
21427 end;
21428 @end example
21429 @end quotation
21431 This program prints out 0 in @emph{-O0} or @emph{-O1}
21432 mode, but it prints out 1 in @emph{-O2} mode. That's
21433 because in strict aliasing mode, the compiler can and
21434 does assume that the assignment to @cite{v2.all} could not
21435 affect the value of @cite{v1.all}, since different types
21436 are involved.
21438 This behavior is not a case of non-conformance with the standard, since
21439 the Ada RM specifies that an unchecked conversion where the resulting
21440 bit pattern is not a correct value of the target type can result in an
21441 abnormal value and attempting to reference an abnormal value makes the
21442 execution of a program erroneous.  That's the case here since the result
21443 does not point to an object of type @cite{int2}.  This means that the
21444 effect is entirely unpredictable.
21446 However, although that explanation may satisfy a language
21447 lawyer, in practice an applications programmer expects an
21448 unchecked conversion involving pointers to create true
21449 aliases and the behavior of printing 1 seems plain wrong.
21450 In this case, the strict aliasing optimization is unwelcome.
21452 Indeed the compiler recognizes this possibility, and the
21453 unchecked conversion generates a warning:
21455 @quotation
21457 @example
21458 p2.adb:5:07: warning: possible aliasing problem with type "a2"
21459 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
21460 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
21461 @end example
21462 @end quotation
21464 Unfortunately the problem is recognized when compiling the body of
21465 package @cite{p2}, but the actual "bad" code is generated while
21466 compiling the body of @cite{m} and this latter compilation does not see
21467 the suspicious @cite{Unchecked_Conversion}.
21469 As implied by the warning message, there are approaches you can use to
21470 avoid the unwanted strict aliasing optimization in a case like this.
21472 One possibility is to simply avoid the use of @emph{-O2}, but
21473 that is a bit drastic, since it throws away a number of useful
21474 optimizations that do not involve strict aliasing assumptions.
21476 A less drastic approach is to compile the program using the
21477 option @emph{-fno-strict-aliasing}. Actually it is only the
21478 unit containing the dereferencing of the suspicious pointer
21479 that needs to be compiled. So in this case, if we compile
21480 unit @cite{m} with this switch, then we get the expected
21481 value of zero printed. Analyzing which units might need
21482 the switch can be painful, so a more reasonable approach
21483 is to compile the entire program with options @emph{-O2}
21484 and @emph{-fno-strict-aliasing}. If the performance is
21485 satisfactory with this combination of options, then the
21486 advantage is that the entire issue of possible "wrong"
21487 optimization due to strict aliasing is avoided.
21489 To avoid the use of compiler switches, the configuration
21490 pragma @cite{No_Strict_Aliasing} with no parameters may be
21491 used to specify that for all access types, the strict
21492 aliasing optimization should be suppressed.
21494 However, these approaches are still overkill, in that they causes
21495 all manipulations of all access values to be deoptimized. A more
21496 refined approach is to concentrate attention on the specific
21497 access type identified as problematic.
21499 First, if a careful analysis of uses of the pointer shows
21500 that there are no possible problematic references, then
21501 the warning can be suppressed by bracketing the
21502 instantiation of @cite{Unchecked_Conversion} to turn
21503 the warning off:
21505 @quotation
21507 @example
21508 pragma Warnings (Off);
21509 function to_a2u is
21510   new Unchecked_Conversion (a1, a2);
21511 pragma Warnings (On);
21512 @end example
21513 @end quotation
21515 Of course that approach is not appropriate for this particular
21516 example, since indeed there is a problematic reference. In this
21517 case we can take one of two other approaches.
21519 The first possibility is to move the instantiation of unchecked
21520 conversion to the unit in which the type is declared. In
21521 this example, we would move the instantiation of
21522 @cite{Unchecked_Conversion} from the body of package
21523 @cite{p2} to the spec of package @cite{p1}. Now the
21524 warning disappears. That's because any use of the
21525 access type knows there is a suspicious unchecked
21526 conversion, and the strict aliasing optimization
21527 is automatically suppressed for the type.
21529 If it is not practical to move the unchecked conversion to the same unit
21530 in which the destination access type is declared (perhaps because the
21531 source type is not visible in that unit), you may use pragma
21532 @cite{No_Strict_Aliasing} for the type. This pragma must occur in the
21533 same declarative sequence as the declaration of the access type:
21535 @quotation
21537 @example
21538 type a2 is access int2;
21539 pragma No_Strict_Aliasing (a2);
21540 @end example
21541 @end quotation
21543 Here again, the compiler now knows that the strict aliasing optimization
21544 should be suppressed for any reference to type @cite{a2} and the
21545 expected behavior is obtained.
21547 Finally, note that although the compiler can generate warnings for
21548 simple cases of unchecked conversions, there are tricker and more
21549 indirect ways of creating type incorrect aliases which the compiler
21550 cannot detect. Examples are the use of address overlays and unchecked
21551 conversions involving composite types containing access types as
21552 components. In such cases, no warnings are generated, but there can
21553 still be aliasing problems. One safe coding practice is to forbid the
21554 use of address clauses for type overlaying, and to allow unchecked
21555 conversion only for primitive types. This is not really a significant
21556 restriction since any possible desired effect can be achieved by
21557 unchecked conversion of access values.
21559 The aliasing analysis done in strict aliasing mode can certainly
21560 have significant benefits. We have seen cases of large scale
21561 application code where the time is increased by up to 5% by turning
21562 this optimization off. If you have code that includes significant
21563 usage of unchecked conversion, you might want to just stick with
21564 @emph{-O1} and avoid the entire issue. If you get adequate
21565 performance at this level of optimization level, that's probably
21566 the safest approach. If tests show that you really need higher
21567 levels of optimization, then you can experiment with @emph{-O2}
21568 and @emph{-O2 -fno-strict-aliasing} to see how much effect this
21569 has on size and speed of the code. If you really need to use
21570 @emph{-O2} with strict aliasing in effect, then you should
21571 review any uses of unchecked conversion of access types,
21572 particularly if you are getting the warnings described above.
21574 @node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
21575 @anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{1af}@anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{1b0}
21576 @subsubsection Aliased Variables and Optimization
21579 @geindex Aliasing
21581 There are scenarios in which programs may
21582 use low level techniques to modify variables
21583 that otherwise might be considered to be unassigned. For example,
21584 a variable can be passed to a procedure by reference, which takes
21585 the address of the parameter and uses the address to modify the
21586 variable's value, even though it is passed as an IN parameter.
21587 Consider the following example:
21589 @quotation
21591 @example
21592 procedure P is
21593    Max_Length : constant Natural := 16;
21594    type Char_Ptr is access all Character;
21596    procedure Get_String(Buffer: Char_Ptr; Size : Integer);
21597    pragma Import (C, Get_String, "get_string");
21599    Name : aliased String (1 .. Max_Length) := (others => ' ');
21600    Temp : Char_Ptr;
21602    function Addr (S : String) return Char_Ptr is
21603       function To_Char_Ptr is
21604         new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
21605    begin
21606       return To_Char_Ptr (S (S'First)'Address);
21607    end;
21609 begin
21610    Temp := Addr (Name);
21611    Get_String (Temp, Max_Length);
21612 end;
21613 @end example
21614 @end quotation
21616 where Get_String is a C function that uses the address in Temp to
21617 modify the variable @cite{Name}. This code is dubious, and arguably
21618 erroneous, and the compiler would be entitled to assume that
21619 @cite{Name} is never modified, and generate code accordingly.
21621 However, in practice, this would cause some existing code that
21622 seems to work with no optimization to start failing at high
21623 levels of optimzization.
21625 What the compiler does for such cases is to assume that marking
21626 a variable as aliased indicates that some "funny business" may
21627 be going on. The optimizer recognizes the aliased keyword and
21628 inhibits optimizations that assume the value cannot be assigned.
21629 This means that the above example will in fact "work" reliably,
21630 that is, it will produce the expected results.
21632 @node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
21633 @anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{1b1}@anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{1b2}
21634 @subsubsection Atomic Variables and Optimization
21637 @geindex Atomic
21639 There are two considerations with regard to performance when
21640 atomic variables are used.
21642 First, the RM only guarantees that access to atomic variables
21643 be atomic, it has nothing to say about how this is achieved,
21644 though there is a strong implication that this should not be
21645 achieved by explicit locking code. Indeed GNAT will never
21646 generate any locking code for atomic variable access (it will
21647 simply reject any attempt to make a variable or type atomic
21648 if the atomic access cannot be achieved without such locking code).
21650 That being said, it is important to understand that you cannot
21651 assume that the entire variable will always be accessed. Consider
21652 this example:
21654 @quotation
21656 @example
21657 type R is record
21658    A,B,C,D : Character;
21659 end record;
21660 for R'Size use 32;
21661 for R'Alignment use 4;
21663 RV : R;
21664 pragma Atomic (RV);
21665 X : Character;
21667 X := RV.B;
21668 @end example
21669 @end quotation
21671 You cannot assume that the reference to @cite{RV.B}
21672 will read the entire 32-bit
21673 variable with a single load instruction. It is perfectly legitimate if
21674 the hardware allows it to do a byte read of just the B field. This read
21675 is still atomic, which is all the RM requires. GNAT can and does take
21676 advantage of this, depending on the architecture and optimization level.
21677 Any assumption to the contrary is non-portable and risky. Even if you
21678 examine the assembly language and see a full 32-bit load, this might
21679 change in a future version of the compiler.
21681 If your application requires that all accesses to @cite{RV} in this
21682 example be full 32-bit loads, you need to make a copy for the access
21683 as in:
21685 @quotation
21687 @example
21688 declare
21689    RV_Copy : constant R := RV;
21690 begin
21691    X := RV_Copy.B;
21692 end;
21693 @end example
21694 @end quotation
21696 Now the reference to RV must read the whole variable.
21697 Actually one can imagine some compiler which figures
21698 out that the whole copy is not required (because only
21699 the B field is actually accessed), but GNAT
21700 certainly won't do that, and we don't know of any
21701 compiler that would not handle this right, and the
21702 above code will in practice work portably across
21703 all architectures (that permit the Atomic declaration).
21705 The second issue with atomic variables has to do with
21706 the possible requirement of generating synchronization
21707 code. For more details on this, consult the sections on
21708 the pragmas Enable/Disable_Atomic_Synchronization in the
21709 GNAT Reference Manual. If performance is critical, and
21710 such synchronization code is not required, it may be
21711 useful to disable it.
21713 @node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
21714 @anchor{gnat_ugn/gnat_and_program_execution id41}@anchor{1b3}@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{1b4}
21715 @subsubsection Passive Task Optimization
21718 @geindex Passive Task
21720 A passive task is one which is sufficiently simple that
21721 in theory a compiler could recognize it an implement it
21722 efficiently without creating a new thread. The original design
21723 of Ada 83 had in mind this kind of passive task optimization, but
21724 only a few Ada 83 compilers attempted it. The problem was that
21725 it was difficult to determine the exact conditions under which
21726 the optimization was possible. The result is a very fragile
21727 optimization where a very minor change in the program can
21728 suddenly silently make a task non-optimizable.
21730 With the revisiting of this issue in Ada 95, there was general
21731 agreement that this approach was fundamentally flawed, and the
21732 notion of protected types was introduced. When using protected
21733 types, the restrictions are well defined, and you KNOW that the
21734 operations will be optimized, and furthermore this optimized
21735 performance is fully portable.
21737 Although it would theoretically be possible for GNAT to attempt to
21738 do this optimization, but it really doesn't make sense in the
21739 context of Ada 95, and none of the Ada 95 compilers implement
21740 this optimization as far as we know. In particular GNAT never
21741 attempts to perform this optimization.
21743 In any new Ada 95 code that is written, you should always
21744 use protected types in place of tasks that might be able to
21745 be optimized in this manner.
21746 Of course this does not help if you have legacy Ada 83 code
21747 that depends on this optimization, but it is unusual to encounter
21748 a case where the performance gains from this optimization
21749 are significant.
21751 Your program should work correctly without this optimization. If
21752 you have performance problems, then the most practical
21753 approach is to figure out exactly where these performance problems
21754 arise, and update those particular tasks to be protected types. Note
21755 that typically clients of the tasks who call entries, will not have
21756 to be modified, only the task definition itself.
21758 @node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
21759 @anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{1b5}@anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{1b6}
21760 @subsection @cite{Text_IO} Suggestions
21763 @geindex Text_IO and performance
21765 The @cite{Ada.Text_IO} package has fairly high overheads due in part to
21766 the requirement of maintaining page and line counts. If performance
21767 is critical, a recommendation is to use @cite{Stream_IO} instead of
21768 @cite{Text_IO} for volume output, since this package has less overhead.
21770 If @cite{Text_IO} must be used, note that by default output to the standard
21771 output and standard error files is unbuffered (this provides better
21772 behavior when output statements are used for debugging, or if the
21773 progress of a program is observed by tracking the output, e.g. by
21774 using the Unix @emph{tail -f} command to watch redirected output.
21776 If you are generating large volumes of output with @cite{Text_IO} and
21777 performance is an important factor, use a designated file instead
21778 of the standard output file, or change the standard output file to
21779 be buffered using @cite{Interfaces.C_Streams.setvbuf}.
21781 @node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
21782 @anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{1b7}@anchor{gnat_ugn/gnat_and_program_execution reducing-size-of-executables-with-unused-subprogram-data-elimination}@anchor{1b8}
21783 @subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
21786 @geindex Uunused subprogram/data elimination
21788 This section describes how you can eliminate unused subprograms and data from
21789 your executable just by setting options at compilation time.
21791 @menu
21792 * About unused subprogram/data elimination:: 
21793 * Compilation options:: 
21794 * Example of unused subprogram/data elimination:: 
21796 @end menu
21798 @node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
21799 @anchor{gnat_ugn/gnat_and_program_execution id44}@anchor{1b9}@anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{1ba}
21800 @subsubsection About unused subprogram/data elimination
21803 By default, an executable contains all code and data of its composing objects
21804 (directly linked or coming from statically linked libraries), even data or code
21805 never used by this executable.
21807 This feature will allow you to eliminate such unused code from your
21808 executable, making it smaller (in disk and in memory).
21810 This functionality is available on all Linux platforms except for the IA-64
21811 architecture and on all cross platforms using the ELF binary file format.
21812 In both cases GNU binutils version 2.16 or later are required to enable it.
21814 @node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
21815 @anchor{gnat_ugn/gnat_and_program_execution id45}@anchor{1bb}@anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{1bc}
21816 @subsubsection Compilation options
21819 The operation of eliminating the unused code and data from the final executable
21820 is directly performed by the linker.
21822 @geindex -ffunction-sections (gcc)
21824 @geindex -fdata-sections (gcc)
21826 In order to do this, it has to work with objects compiled with the
21827 following options:
21828 @emph{-ffunction-sections} @emph{-fdata-sections}.
21830 These options are usable with C and Ada files.
21831 They will place respectively each
21832 function or data in a separate section in the resulting object file.
21834 Once the objects and static libraries are created with these options, the
21835 linker can perform the dead code elimination. You can do this by setting
21836 the @emph{-Wl,--gc-sections} option to gcc command or in the
21837 @emph{-largs} section of @emph{gnatmake}. This will perform a
21838 garbage collection of code and data never referenced.
21840 If the linker performs a partial link (@emph{-r} linker option), then you
21841 will need to provide the entry point using the @emph{-e} / @emph{--entry}
21842 linker option.
21844 Note that objects compiled without the @emph{-ffunction-sections} and
21845 @emph{-fdata-sections} options can still be linked with the executable.
21846 However, no dead code elimination will be performed on those objects (they will
21847 be linked as is).
21849 The GNAT static library is now compiled with -ffunction-sections and
21850 -fdata-sections on some platforms. This allows you to eliminate the unused code
21851 and data of the GNAT library from your executable.
21853 @node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
21854 @anchor{gnat_ugn/gnat_and_program_execution id46}@anchor{1bd}@anchor{gnat_ugn/gnat_and_program_execution example-of-unused-subprogram-data-elimination}@anchor{1be}
21855 @subsubsection Example of unused subprogram/data elimination
21858 Here is a simple example:
21860 @quotation
21862 @example
21863 with Aux;
21865 procedure Test is
21866 begin
21867    Aux.Used (10);
21868 end Test;
21870 package Aux is
21871    Used_Data   : Integer;
21872    Unused_Data : Integer;
21874    procedure Used   (Data : Integer);
21875    procedure Unused (Data : Integer);
21876 end Aux;
21878 package body Aux is
21879    procedure Used (Data : Integer) is
21880    begin
21881       Used_Data := Data;
21882    end Used;
21884    procedure Unused (Data : Integer) is
21885    begin
21886       Unused_Data := Data;
21887    end Unused;
21888 end Aux;
21889 @end example
21890 @end quotation
21892 @cite{Unused} and @cite{Unused_Data} are never referenced in this code
21893 excerpt, and hence they may be safely removed from the final executable.
21895 @quotation
21897 @example
21898 $ gnatmake test
21900 $ nm test | grep used
21901 020015f0 T aux__unused
21902 02005d88 B aux__unused_data
21903 020015cc T aux__used
21904 02005d84 B aux__used_data
21906 $ gnatmake test -cargs -fdata-sections -ffunction-sections \\
21907      -largs -Wl,--gc-sections
21909 $ nm test | grep used
21910 02005350 T aux__used
21911 0201ffe0 B aux__used_data
21912 @end example
21913 @end quotation
21915 It can be observed that the procedure @cite{Unused} and the object
21916 @cite{Unused_Data} are removed by the linker when using the
21917 appropriate options.
21919 @geindex Overflow checks
21921 @geindex Checks (overflow)
21924 @node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
21925 @anchor{gnat_ugn/gnat_and_program_execution id54}@anchor{16a}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{27}
21926 @section Overflow Check Handling in GNAT
21929 This section explains how to control the handling of overflow checks.
21931 @menu
21932 * Background:: 
21933 * Management of Overflows in GNAT:: 
21934 * Specifying the Desired Mode:: 
21935 * Default Settings:: 
21936 * Implementation Notes:: 
21938 @end menu
21940 @node Background,Management of Overflows in GNAT,,Overflow Check Handling in GNAT
21941 @anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{1bf}@anchor{gnat_ugn/gnat_and_program_execution background}@anchor{1c0}
21942 @subsection Background
21945 Overflow checks are checks that the compiler may make to ensure
21946 that intermediate results are not out of range. For example:
21948 @quotation
21950 @example
21951 A : Integer;
21953 A := A + 1;
21954 @end example
21955 @end quotation
21957 If @cite{A} has the value @cite{Integer'Last}, then the addition may cause
21958 overflow since the result is out of range of the type @cite{Integer}.
21959 In this case @cite{Constraint_Error} will be raised if checks are
21960 enabled.
21962 A trickier situation arises in examples like the following:
21964 @quotation
21966 @example
21967 A, C : Integer;
21969 A := (A + 1) + C;
21970 @end example
21971 @end quotation
21973 where @cite{A} is @cite{Integer'Last} and @cite{C} is @cite{-1}.
21974 Now the final result of the expression on the right hand side is
21975 @cite{Integer'Last} which is in range, but the question arises whether the
21976 intermediate addition of @cite{(A + 1)} raises an overflow error.
21978 The (perhaps surprising) answer is that the Ada language
21979 definition does not answer this question. Instead it leaves
21980 it up to the implementation to do one of two things if overflow
21981 checks are enabled.
21984 @itemize *
21986 @item 
21987 raise an exception (@cite{Constraint_Error}), or
21989 @item 
21990 yield the correct mathematical result which is then used in
21991 subsequent operations.
21992 @end itemize
21994 If the compiler chooses the first approach, then the assignment of this
21995 example will indeed raise @cite{Constraint_Error} if overflow checking is
21996 enabled, or result in erroneous execution if overflow checks are suppressed.
21998 But if the compiler
21999 chooses the second approach, then it can perform both additions yielding
22000 the correct mathematical result, which is in range, so no exception
22001 will be raised, and the right result is obtained, regardless of whether
22002 overflow checks are suppressed.
22004 Note that in the first example an
22005 exception will be raised in either case, since if the compiler
22006 gives the correct mathematical result for the addition, it will
22007 be out of range of the target type of the assignment, and thus
22008 fails the range check.
22010 This lack of specified behavior in the handling of overflow for
22011 intermediate results is a source of non-portability, and can thus
22012 be problematic when programs are ported. Most typically this arises
22013 in a situation where the original compiler did not raise an exception,
22014 and then the application is moved to a compiler where the check is
22015 performed on the intermediate result and an unexpected exception is
22016 raised.
22018 Furthermore, when using Ada 2012's preconditions and other
22019 assertion forms, another issue arises. Consider:
22021 @quotation
22023 @example
22024 procedure P (A, B : Integer) with
22025   Pre => A + B <= Integer'Last;
22026 @end example
22027 @end quotation
22029 One often wants to regard arithmetic in a context like this from
22030 a mathematical point of view. So for example, if the two actual parameters
22031 for a call to @cite{P} are both @cite{Integer'Last}, then
22032 the precondition should be regarded as False. If we are executing
22033 in a mode with run-time checks enabled for preconditions, then we would
22034 like this precondition to fail, rather than raising an exception
22035 because of the intermediate overflow.
22037 However, the language definition leaves the specification of
22038 whether the above condition fails (raising @cite{Assert_Error}) or
22039 causes an intermediate overflow (raising @cite{Constraint_Error})
22040 up to the implementation.
22042 The situation is worse in a case such as the following:
22044 @quotation
22046 @example
22047 procedure Q (A, B, C : Integer) with
22048   Pre => A + B + C <= Integer'Last;
22049 @end example
22050 @end quotation
22052 Consider the call
22054 @quotation
22056 @example
22057 Q (A => Integer'Last, B => 1, C => -1);
22058 @end example
22059 @end quotation
22061 From a mathematical point of view the precondition
22062 is True, but at run time we may (but are not guaranteed to) get an
22063 exception raised because of the intermediate overflow (and we really
22064 would prefer this precondition to be considered True at run time).
22066 @node Management of Overflows in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
22067 @anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{1c1}@anchor{gnat_ugn/gnat_and_program_execution management-of-overflows-in-gnat}@anchor{1c2}
22068 @subsection Management of Overflows in GNAT
22071 To deal with the portability issue, and with the problem of
22072 mathematical versus run-time interpretation of the expressions in
22073 assertions, GNAT provides comprehensive control over the handling
22074 of intermediate overflow. GNAT can operate in three modes, and
22075 furthemore, permits separate selection of operating modes for
22076 the expressions within assertions (here the term 'assertions'
22077 is used in the technical sense, which includes preconditions and so forth)
22078 and for expressions appearing outside assertions.
22080 The three modes are:
22083 @itemize *
22085 @item 
22086 @emph{Use base type for intermediate operations} (@cite{STRICT})
22088 In this mode, all intermediate results for predefined arithmetic
22089 operators are computed using the base type, and the result must
22090 be in range of the base type. If this is not the
22091 case then either an exception is raised (if overflow checks are
22092 enabled) or the execution is erroneous (if overflow checks are suppressed).
22093 This is the normal default mode.
22095 @item 
22096 @emph{Most intermediate overflows avoided} (@cite{MINIMIZED})
22098 In this mode, the compiler attempts to avoid intermediate overflows by
22099 using a larger integer type, typically @cite{Long_Long_Integer},
22100 as the type in which arithmetic is
22101 performed for predefined arithmetic operators. This may be slightly more
22102 expensive at
22103 run time (compared to suppressing intermediate overflow checks), though
22104 the cost is negligible on modern 64-bit machines. For the examples given
22105 earlier, no intermediate overflows would have resulted in exceptions,
22106 since the intermediate results are all in the range of
22107 @cite{Long_Long_Integer} (typically 64-bits on nearly all implementations
22108 of GNAT). In addition, if checks are enabled, this reduces the number of
22109 checks that must be made, so this choice may actually result in an
22110 improvement in space and time behavior.
22112 However, there are cases where @cite{Long_Long_Integer} is not large
22113 enough, consider the following example:
22115 @quotation
22117 @example
22118 procedure R (A, B, C, D : Integer) with
22119   Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
22120 @end example
22121 @end quotation
22123 where @cite{A} = @cite{B} = @cite{C} = @cite{D} = @cite{Integer'Last}.
22124 Now the intermediate results are
22125 out of the range of @cite{Long_Long_Integer} even though the final result
22126 is in range and the precondition is True (from a mathematical point
22127 of view). In such a case, operating in this mode, an overflow occurs
22128 for the intermediate computation (which is why this mode
22129 says @emph{most} intermediate overflows are avoided). In this case,
22130 an exception is raised if overflow checks are enabled, and the
22131 execution is erroneous if overflow checks are suppressed.
22133 @item 
22134 @emph{All intermediate overflows avoided} (@cite{ELIMINATED})
22136 In this mode, the compiler  avoids all intermediate overflows
22137 by using arbitrary precision arithmetic as required. In this
22138 mode, the above example with @cite{A**2 * B**2} would
22139 not cause intermediate overflow, because the intermediate result
22140 would be evaluated using sufficient precision, and the result
22141 of evaluating the precondition would be True.
22143 This mode has the advantage of avoiding any intermediate
22144 overflows, but at the expense of significant run-time overhead,
22145 including the use of a library (included automatically in this
22146 mode) for multiple-precision arithmetic.
22148 This mode provides cleaner semantics for assertions, since now
22149 the run-time behavior emulates true arithmetic behavior for the
22150 predefined arithmetic operators, meaning that there is never a
22151 conflict between the mathematical view of the assertion, and its
22152 run-time behavior.
22154 Note that in this mode, the behavior is unaffected by whether or
22155 not overflow checks are suppressed, since overflow does not occur.
22156 It is possible for gigantic intermediate expressions to raise
22157 @cite{Storage_Error} as a result of attempting to compute the
22158 results of such expressions (e.g. @cite{Integer'Last ** Integer'Last})
22159 but overflow is impossible.
22160 @end itemize
22162 Note that these modes apply only to the evaluation of predefined
22163 arithmetic, membership, and comparison operators for signed integer
22164 arithmetic.
22166 For fixed-point arithmetic, checks can be suppressed. But if checks
22167 are enabled
22168 then fixed-point values are always checked for overflow against the
22169 base type for intermediate expressions (that is such checks always
22170 operate in the equivalent of @cite{STRICT} mode).
22172 For floating-point, on nearly all architectures, @cite{Machine_Overflows}
22173 is False, and IEEE infinities are generated, so overflow exceptions
22174 are never raised. If you want to avoid infinities, and check that
22175 final results of expressions are in range, then you can declare a
22176 constrained floating-point type, and range checks will be carried
22177 out in the normal manner (with infinite values always failing all
22178 range checks).
22180 @node Specifying the Desired Mode,Default Settings,Management of Overflows in GNAT,Overflow Check Handling in GNAT
22181 @anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{f8}@anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{1c3}
22182 @subsection Specifying the Desired Mode
22185 @geindex pragma Overflow_Mode
22187 The desired mode of for handling intermediate overflow can be specified using
22188 either the @cite{Overflow_Mode} pragma or an equivalent compiler switch.
22189 The pragma has the form
22191 @quotation
22193 @example
22194 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
22195 @end example
22196 @end quotation
22198 where @cite{MODE} is one of
22201 @itemize *
22203 @item 
22204 @cite{STRICT}:  intermediate overflows checked (using base type)
22206 @item 
22207 @cite{MINIMIZED}: minimize intermediate overflows
22209 @item 
22210 @cite{ELIMINATED}: eliminate intermediate overflows
22211 @end itemize
22213 The case is ignored, so @cite{MINIMIZED}, @cite{Minimized} and
22214 @cite{minimized} all have the same effect.
22216 If only the @cite{General} parameter is present, then the given @cite{MODE}
22217 applies
22218 to expressions both within and outside assertions. If both arguments
22219 are present, then @cite{General} applies to expressions outside assertions,
22220 and @cite{Assertions} applies to expressions within assertions. For example:
22222 @quotation
22224 @example
22225 pragma Overflow_Mode
22226   (General => Minimized, Assertions => Eliminated);
22227 @end example
22228 @end quotation
22230 specifies that general expressions outside assertions be evaluated
22231 in 'minimize intermediate overflows' mode, and expressions within
22232 assertions be evaluated in 'eliminate intermediate overflows' mode.
22233 This is often a reasonable choice, avoiding excessive overhead
22234 outside assertions, but assuring a high degree of portability
22235 when importing code from another compiler, while incurring
22236 the extra overhead for assertion expressions to ensure that
22237 the behavior at run time matches the expected mathematical
22238 behavior.
22240 The @cite{Overflow_Mode} pragma has the same scoping and placement
22241 rules as pragma @cite{Suppress}, so it can occur either as a
22242 configuration pragma, specifying a default for the whole
22243 program, or in a declarative scope, where it applies to the
22244 remaining declarations and statements in that scope.
22246 Note that pragma @cite{Overflow_Mode} does not affect whether
22247 overflow checks are enabled or suppressed. It only controls the
22248 method used to compute intermediate values. To control whether
22249 overflow checking is enabled or suppressed, use pragma @cite{Suppress}
22250 or @cite{Unsuppress} in the usual manner
22252 @geindex -gnato? (gcc)
22254 @geindex -gnato?? (gcc)
22256 Additionally, a compiler switch @emph{-gnato?} or @emph{-gnato??}
22257 can be used to control the checking mode default (which can be subsequently
22258 overridden using pragmas).
22260 Here @code{?} is one of the digits @code{1} through @code{3}:
22262 @quotation
22265 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
22266 @item
22268 @code{1}
22270 @tab
22272 use base type for intermediate operations (@cite{STRICT})
22274 @item
22276 @code{2}
22278 @tab
22280 minimize intermediate overflows (@cite{MINIMIZED})
22282 @item
22284 @code{3}
22286 @tab
22288 eliminate intermediate overflows (@cite{ELIMINATED})
22290 @end multitable
22292 @end quotation
22294 As with the pragma, if only one digit appears then it applies to all
22295 cases; if two digits are given, then the first applies outside
22296 assertions, and the second within assertions. Thus the equivalent
22297 of the example pragma above would be
22298 @emph{-gnato23}.
22300 If no digits follow the @emph{-gnato}, then it is equivalent to
22301 @emph{-gnato11},
22302 causing all intermediate operations to be computed using the base
22303 type (@cite{STRICT} mode).
22305 @node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
22306 @anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{1c4}@anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{1c5}
22307 @subsection Default Settings
22310 The default mode for overflow checks is
22312 @quotation
22314 @example
22315 General => Strict
22316 @end example
22317 @end quotation
22319 which causes all computations both inside and outside assertions to use
22320 the base type.
22322 This retains compatibility with previous versions of
22323 GNAT which suppressed overflow checks by default and always
22324 used the base type for computation of intermediate results.
22326 @c Sphinx allows no emphasis within :index: role. As a workaround we
22327 @c point the index to "switch" and use emphasis for "-gnato".
22329 The 
22330 @geindex -gnato (gcc)
22331 switch @emph{-gnato} (with no digits following)
22332 is equivalent to
22334 @quotation
22336 @example
22337 General => Strict
22338 @end example
22339 @end quotation
22341 which causes overflow checking of all intermediate overflows
22342 both inside and outside assertions against the base type.
22344 The pragma @cite{Suppress (Overflow_Check)} disables overflow
22345 checking, but it has no effect on the method used for computing
22346 intermediate results.
22348 The pragma @cite{Unsuppress (Overflow_Check)} enables overflow
22349 checking, but it has no effect on the method used for computing
22350 intermediate results.
22352 @node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
22353 @anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{1c6}@anchor{gnat_ugn/gnat_and_program_execution id59}@anchor{1c7}
22354 @subsection Implementation Notes
22357 In practice on typical 64-bit machines, the @cite{MINIMIZED} mode is
22358 reasonably efficient, and can be generally used. It also helps
22359 to ensure compatibility with code imported from some other
22360 compiler to GNAT.
22362 Setting all intermediate overflows checking (@cite{CHECKED} mode)
22363 makes sense if you want to
22364 make sure that your code is compatible with any other possible
22365 Ada implementation. This may be useful in ensuring portability
22366 for code that is to be exported to some other compiler than GNAT.
22368 The Ada standard allows the reassociation of expressions at
22369 the same precedence level if no parentheses are present. For
22370 example, @cite{A+B+C} parses as though it were @cite{(A+B)+C}, but
22371 the compiler can reintepret this as @cite{A+(B+C)}, possibly
22372 introducing or eliminating an overflow exception. The GNAT
22373 compiler never takes advantage of this freedom, and the
22374 expression @cite{A+B+C} will be evaluated as @cite{(A+B)+C}.
22375 If you need the other order, you can write the parentheses
22376 explicitly @cite{A+(B+C)} and GNAT will respect this order.
22378 The use of @cite{ELIMINATED} mode will cause the compiler to
22379 automatically include an appropriate arbitrary precision
22380 integer arithmetic package. The compiler will make calls
22381 to this package, though only in cases where it cannot be
22382 sure that @cite{Long_Long_Integer} is sufficient to guard against
22383 intermediate overflows. This package does not use dynamic
22384 alllocation, but it does use the secondary stack, so an
22385 appropriate secondary stack package must be present (this
22386 is always true for standard full Ada, but may require
22387 specific steps for restricted run times such as ZFP).
22389 Although @cite{ELIMINATED} mode causes expressions to use arbitrary
22390 precision arithmetic, avoiding overflow, the final result
22391 must be in an appropriate range. This is true even if the
22392 final result is of type @cite{[Long_[Long_]]Integer'Base}, which
22393 still has the same bounds as its associated constrained
22394 type at run-time.
22396 Currently, the @cite{ELIMINATED} mode is only available on target
22397 platforms for which @cite{Long_Long_Integer} is 64-bits (nearly all GNAT
22398 platforms).
22400 @node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
22401 @anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{28}@anchor{gnat_ugn/gnat_and_program_execution id60}@anchor{16b}
22402 @section Performing Dimensionality Analysis in GNAT
22405 @geindex Dimensionality analysis
22407 The GNAT compiler supports dimensionality checking. The user can
22408 specify physical units for objects, and the compiler will verify that uses
22409 of these objects are compatible with their dimensions, in a fashion that is
22410 familiar to engineering practice. The dimensions of algebraic expressions
22411 (including powers with static exponents) are computed from their constituents.
22413 @geindex Dimension_System aspect
22415 @geindex Dimension aspect
22417 This feature depends on Ada 2012 aspect specifications, and is available from
22418 version 7.0.1 of GNAT onwards.
22419 The GNAT-specific aspect @cite{Dimension_System}
22420 allows you to define a system of units; the aspect @cite{Dimension}
22421 then allows the user to declare dimensioned quantities within a given system.
22422 (These aspects are described in the @emph{Implementation Defined Aspects}
22423 chapter of the @emph{GNAT Reference Manual}).
22425 The major advantage of this model is that it does not require the declaration of
22426 multiple operators for all possible combinations of types: it is only necessary
22427 to use the proper subtypes in object declarations.
22429 @geindex System.Dim.Mks package (GNAT library)
22431 @geindex MKS_Type type
22433 The simplest way to impose dimensionality checking on a computation is to make
22434 use of the package @cite{System.Dim.Mks},
22435 which is part of the GNAT library. This
22436 package defines a floating-point type @cite{MKS_Type},
22437 for which a sequence of
22438 dimension names are specified, together with their conventional abbreviations.
22439 The following should be read together with the full specification of the
22440 package, in file @code{s-dimmks.ads}.
22442 @quotation
22444 @geindex s-dimmks.ads file
22446 @example
22447 type Mks_Type is new Long_Long_Float
22448   with
22449    Dimension_System => (
22450      (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
22451      (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
22452      (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
22453      (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
22454      (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
22455      (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
22456      (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
22457 @end example
22458 @end quotation
22460 The package then defines a series of subtypes that correspond to these
22461 conventional units. For example:
22463 @quotation
22465 @example
22466 subtype Length is Mks_Type
22467   with
22468    Dimension => (Symbol => 'm', Meter  => 1, others => 0);
22469 @end example
22470 @end quotation
22472 and similarly for @cite{Mass}, @cite{Time}, @cite{Electric_Current},
22473 @cite{Thermodynamic_Temperature}, @cite{Amount_Of_Substance}, and
22474 @cite{Luminous_Intensity} (the standard set of units of the SI system).
22476 The package also defines conventional names for values of each unit, for
22477 example:
22479 @quotation
22481 @example
22482 m   : constant Length           := 1.0;
22483 kg  : constant Mass             := 1.0;
22484 s   : constant Time             := 1.0;
22485 A   : constant Electric_Current := 1.0;
22486 @end example
22487 @end quotation
22489 as well as useful multiples of these units:
22491 @quotation
22493 @example
22494  cm  : constant Length := 1.0E-02;
22495  g   : constant Mass   := 1.0E-03;
22496  min : constant Time   := 60.0;
22497  day : constant Time   := 60.0 * 24.0 * min;
22499 @end example
22500 @end quotation
22502 Using this package, you can then define a derived unit by
22503 providing the aspect that
22504 specifies its dimensions within the MKS system, as well as the string to
22505 be used for output of a value of that unit:
22507 @quotation
22509 @example
22510 subtype Acceleration is Mks_Type
22511   with Dimension => ("m/sec^2",
22512                      Meter => 1,
22513                      Second => -2,
22514                      others => 0);
22515 @end example
22516 @end quotation
22518 Here is a complete example of use:
22520 @quotation
22522 @example
22523 with System.Dim.MKS; use System.Dim.Mks;
22524 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
22525 with Text_IO; use Text_IO;
22526 procedure Free_Fall is
22527   subtype Acceleration is Mks_Type
22528     with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
22529   G : constant acceleration := 9.81 * m / (s ** 2);
22530   T : Time := 10.0*s;
22531   Distance : Length;
22533 begin
22534   Put ("Gravitational constant: ");
22535   Put (G, Aft => 2, Exp => 0); Put_Line ("");
22536   Distance := 0.5 * G * T ** 2;
22537   Put ("distance travelled in 10 seconds of free fall ");
22538   Put (Distance, Aft => 2, Exp => 0);
22539   Put_Line ("");
22540 end Free_Fall;
22541 @end example
22542 @end quotation
22544 Execution of this program yields:
22546 @quotation
22548 @example
22549 Gravitational constant:  9.81 m/sec^2
22550 distance travelled in 10 seconds of free fall 490.50 m
22551 @end example
22552 @end quotation
22554 However, incorrect assignments such as:
22556 @quotation
22558 @example
22559 Distance := 5.0;
22560 Distance := 5.0 * kg:
22561 @end example
22562 @end quotation
22564 are rejected with the following diagnoses:
22566 @quotation
22568 @example
22569 Distance := 5.0;
22570    >>> dimensions mismatch in assignment
22571    >>> left-hand side has dimension [L]
22572    >>> right-hand side is dimensionless
22574 Distance := 5.0 * kg:
22575    >>> dimensions mismatch in assignment
22576    >>> left-hand side has dimension [L]
22577    >>> right-hand side has dimension [M]
22578 @end example
22579 @end quotation
22581 The dimensions of an expression are properly displayed, even if there is
22582 no explicit subtype for it. If we add to the program:
22584 @quotation
22586 @example
22587 Put ("Final velocity: ");
22588 Put (G * T, Aft =>2, Exp =>0);
22589 Put_Line ("");
22590 @end example
22591 @end quotation
22593 then the output includes:
22595 @quotation
22597 @example
22598 Final velocity: 98.10 m.s**(-1)
22599 @end example
22600 @end quotation
22602 @node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
22603 @anchor{gnat_ugn/gnat_and_program_execution id61}@anchor{16c}@anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{29}
22604 @section Stack Related Facilities
22607 This section describes some useful tools associated with stack
22608 checking and analysis. In
22609 particular, it deals with dynamic and static stack usage measurements.
22611 @menu
22612 * Stack Overflow Checking:: 
22613 * Static Stack Usage Analysis:: 
22614 * Dynamic Stack Usage Analysis:: 
22616 @end menu
22618 @node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
22619 @anchor{gnat_ugn/gnat_and_program_execution id62}@anchor{1c8}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{f4}
22620 @subsection Stack Overflow Checking
22623 @geindex Stack Overflow Checking
22625 @geindex -fstack-check (gcc)
22627 For most operating systems, @emph{gcc} does not perform stack overflow
22628 checking by default. This means that if the main environment task or
22629 some other task exceeds the available stack space, then unpredictable
22630 behavior will occur. Most native systems offer some level of protection by
22631 adding a guard page at the end of each task stack. This mechanism is usually
22632 not enough for dealing properly with stack overflow situations because
22633 a large local variable could "jump" above the guard page.
22634 Furthermore, when the
22635 guard page is hit, there may not be any space left on the stack for executing
22636 the exception propagation code. Enabling stack checking avoids
22637 such situations.
22639 To activate stack checking, compile all units with the gcc option
22640 @cite{-fstack-check}. For example:
22642 @quotation
22644 @example
22645 $ gcc -c -fstack-check package1.adb
22646 @end example
22647 @end quotation
22649 Units compiled with this option will generate extra instructions to check
22650 that any use of the stack (for procedure calls or for declaring local
22651 variables in declare blocks) does not exceed the available stack space.
22652 If the space is exceeded, then a @cite{Storage_Error} exception is raised.
22654 For declared tasks, the stack size is controlled by the size
22655 given in an applicable @cite{Storage_Size} pragma or by the value specified
22656 at bind time with @code{-d} (@ref{11f,,Switches for gnatbind}) or is set to
22657 the default size as defined in the GNAT runtime otherwise.
22659 @geindex GNAT_STACK_LIMIT
22661 For the environment task, the stack size depends on
22662 system defaults and is unknown to the compiler. Stack checking
22663 may still work correctly if a fixed
22664 size stack is allocated, but this cannot be guaranteed.
22665 To ensure that a clean exception is signalled for stack
22666 overflow, set the environment variable
22667 @geindex GNAT_STACK_LIMIT
22668 @geindex environment variable; GNAT_STACK_LIMIT
22669 @code{GNAT_STACK_LIMIT} to indicate the maximum
22670 stack area that can be used, as in:
22672 @quotation
22674 @example
22675 $ SET GNAT_STACK_LIMIT 1600
22676 @end example
22677 @end quotation
22679 The limit is given in kilobytes, so the above declaration would
22680 set the stack limit of the environment task to 1.6 megabytes.
22681 Note that the only purpose of this usage is to limit the amount
22682 of stack used by the environment task. If it is necessary to
22683 increase the amount of stack for the environment task, then this
22684 is an operating systems issue, and must be addressed with the
22685 appropriate operating systems commands.
22687 @node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
22688 @anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{f5}@anchor{gnat_ugn/gnat_and_program_execution id63}@anchor{1c9}
22689 @subsection Static Stack Usage Analysis
22692 @geindex Static Stack Usage Analysis
22694 @geindex -fstack-usage
22696 A unit compiled with @code{-fstack-usage} will generate an extra file
22697 that specifies
22698 the maximum amount of stack used, on a per-function basis.
22699 The file has the same
22700 basename as the target object file with a @code{.su} extension.
22701 Each line of this file is made up of three fields:
22704 @itemize *
22706 @item 
22707 The name of the function.
22709 @item 
22710 A number of bytes.
22712 @item 
22713 One or more qualifiers: @cite{static}, @cite{dynamic}, @cite{bounded}.
22714 @end itemize
22716 The second field corresponds to the size of the known part of the function
22717 frame.
22719 The qualifier @cite{static} means that the function frame size
22720 is purely static.
22721 It usually means that all local variables have a static size.
22722 In this case, the second field is a reliable measure of the function stack
22723 utilization.
22725 The qualifier @cite{dynamic} means that the function frame size is not static.
22726 It happens mainly when some local variables have a dynamic size. When this
22727 qualifier appears alone, the second field is not a reliable measure
22728 of the function stack analysis. When it is qualified with  @cite{bounded}, it
22729 means that the second field is a reliable maximum of the function stack
22730 utilization.
22732 A unit compiled with @code{-Wstack-usage} will issue a warning for each
22733 subprogram whose stack usage might be larger than the specified amount of
22734 bytes.  The wording is in keeping with the qualifier documented above.
22736 @node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
22737 @anchor{gnat_ugn/gnat_and_program_execution id64}@anchor{1ca}@anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{121}
22738 @subsection Dynamic Stack Usage Analysis
22741 It is possible to measure the maximum amount of stack used by a task, by
22742 adding a switch to @emph{gnatbind}, as:
22744 @quotation
22746 @example
22747 $ gnatbind -u0 file
22748 @end example
22749 @end quotation
22751 With this option, at each task termination, its stack usage is  output on
22752 @code{stderr}.
22753 It is not always convenient to output the stack usage when the program
22754 is still running. Hence, it is possible to delay this output until program
22755 termination. for a given number of tasks specified as the argument of the
22756 @code{-u} option. For instance:
22758 @quotation
22760 @example
22761 $ gnatbind -u100 file
22762 @end example
22763 @end quotation
22765 will buffer the stack usage information of the first 100 tasks to terminate and
22766 output this info at program termination. Results are displayed in four
22767 columns:
22769 @quotation
22771 @example
22772 Index | Task Name | Stack Size | Stack Usage
22773 @end example
22774 @end quotation
22776 where:
22779 @itemize *
22781 @item 
22782 @emph{Index} is a number associated with each task.
22784 @item 
22785 @emph{Task Name} is the name of the task analyzed.
22787 @item 
22788 @emph{Stack Size} is the maximum size for the stack.
22790 @item 
22791 @emph{Stack Usage} is the measure done by the stack analyzer.
22792 In order to prevent overflow, the stack
22793 is not entirely analyzed, and it's not possible to know exactly how
22794 much has actually been used.
22795 @end itemize
22797 The environment task stack, e.g., the stack that contains the main unit, is
22798 only processed when the environment variable GNAT_STACK_LIMIT is set.
22800 The package @cite{GNAT.Task_Stack_Usage} provides facilities to get
22801 stack usage reports at run-time. See its body for the details.
22803 @node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
22804 @anchor{gnat_ugn/gnat_and_program_execution id65}@anchor{16d}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{2a}
22805 @section Memory Management Issues
22808 This section describes some useful memory pools provided in the GNAT library
22809 and in particular the GNAT Debug Pool facility, which can be used to detect
22810 incorrect uses of access values (including 'dangling references').
22813 @menu
22814 * Some Useful Memory Pools:: 
22815 * The GNAT Debug Pool Facility:: 
22817 @end menu
22819 @node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
22820 @anchor{gnat_ugn/gnat_and_program_execution id66}@anchor{1cb}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{1cc}
22821 @subsection Some Useful Memory Pools
22824 @geindex Memory Pool
22826 @geindex storage
22827 @geindex pool
22829 The @cite{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
22830 storage pool. Allocations use the standard system call @cite{malloc} while
22831 deallocations use the standard system call @cite{free}. No reclamation is
22832 performed when the pool goes out of scope. For performance reasons, the
22833 standard default Ada allocators/deallocators do not use any explicit storage
22834 pools but if they did, they could use this storage pool without any change in
22835 behavior. That is why this storage pool is used  when the user
22836 manages to make the default implicit allocator explicit as in this example:
22838 @quotation
22840 @example
22841 type T1 is access Something;
22842  -- no Storage pool is defined for T2
22844 type T2 is access Something_Else;
22845 for T2'Storage_Pool use T1'Storage_Pool;
22846 -- the above is equivalent to
22847 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
22848 @end example
22849 @end quotation
22851 The @cite{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
22852 pool. The allocation strategy is similar to @cite{Pool_Local}'s
22853 except that the all
22854 storage allocated with this pool is reclaimed when the pool object goes out of
22855 scope. This pool provides a explicit mechanism similar to the implicit one
22856 provided by several Ada 83 compilers for allocations performed through a local
22857 access type and whose purpose was to reclaim memory when exiting the
22858 scope of a given local access. As an example, the following program does not
22859 leak memory even though it does not perform explicit deallocation:
22861 @quotation
22863 @example
22864 with System.Pool_Local;
22865 procedure Pooloc1 is
22866    procedure Internal is
22867       type A is access Integer;
22868       X : System.Pool_Local.Unbounded_Reclaim_Pool;
22869       for A'Storage_Pool use X;
22870       v : A;
22871    begin
22872       for I in  1 .. 50 loop
22873          v := new Integer;
22874       end loop;
22875    end Internal;
22876 begin
22877    for I in  1 .. 100 loop
22878       Internal;
22879    end loop;
22880 end Pooloc1;
22881 @end example
22882 @end quotation
22884 The @cite{System.Pool_Size} package implements the Stack_Bounded_Pool used when
22885 @cite{Storage_Size} is specified for an access type.
22886 The whole storage for the pool is
22887 allocated at once, usually on the stack at the point where the access type is
22888 elaborated. It is automatically reclaimed when exiting the scope where the
22889 access type is defined. This package is not intended to be used directly by the
22890 user and it is implicitly used for each such declaration:
22892 @quotation
22894 @example
22895 type T1 is access Something;
22896 for T1'Storage_Size use 10_000;
22897 @end example
22898 @end quotation
22900 @node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
22901 @anchor{gnat_ugn/gnat_and_program_execution id67}@anchor{1cd}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{1ce}
22902 @subsection The GNAT Debug Pool Facility
22905 @geindex Debug Pool
22907 @geindex storage
22908 @geindex pool
22909 @geindex memory corruption
22911 The use of unchecked deallocation and unchecked conversion can easily
22912 lead to incorrect memory references. The problems generated by such
22913 references are usually difficult to tackle because the symptoms can be
22914 very remote from the origin of the problem. In such cases, it is
22915 very helpful to detect the problem as early as possible. This is the
22916 purpose of the Storage Pool provided by @cite{GNAT.Debug_Pools}.
22918 In order to use the GNAT specific debugging pool, the user must
22919 associate a debug pool object with each of the access types that may be
22920 related to suspected memory problems. See Ada Reference Manual 13.11.
22922 @quotation
22924 @example
22925 type Ptr is access Some_Type;
22926 Pool : GNAT.Debug_Pools.Debug_Pool;
22927 for Ptr'Storage_Pool use Pool;
22928 @end example
22929 @end quotation
22931 @cite{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
22932 pool: the @cite{Checked_Pool}. Such pools, like standard Ada storage pools,
22933 allow the user to redefine allocation and deallocation strategies. They
22934 also provide a checkpoint for each dereference, through the use of
22935 the primitive operation @cite{Dereference} which is implicitly called at
22936 each dereference of an access value.
22938 Once an access type has been associated with a debug pool, operations on
22939 values of the type may raise four distinct exceptions,
22940 which correspond to four potential kinds of memory corruption:
22943 @itemize *
22945 @item 
22946 @cite{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
22948 @item 
22949 @cite{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
22951 @item 
22952 @cite{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
22954 @item 
22955 @cite{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
22956 @end itemize
22958 For types associated with a Debug_Pool, dynamic allocation is performed using
22959 the standard GNAT allocation routine. References to all allocated chunks of
22960 memory are kept in an internal dictionary. Several deallocation strategies are
22961 provided, whereupon the user can choose to release the memory to the system,
22962 keep it allocated for further invalid access checks, or fill it with an easily
22963 recognizable pattern for debug sessions. The memory pattern is the old IBM
22964 hexadecimal convention: @cite{16#DEADBEEF#}.
22966 See the documentation in the file g-debpoo.ads for more information on the
22967 various strategies.
22969 Upon each dereference, a check is made that the access value denotes a
22970 properly allocated memory location. Here is a complete example of use of
22971 @cite{Debug_Pools}, that includes typical instances of  memory corruption:
22973 @quotation
22975 @example
22976 with Gnat.Io; use Gnat.Io;
22977 with Unchecked_Deallocation;
22978 with Unchecked_Conversion;
22979 with GNAT.Debug_Pools;
22980 with System.Storage_Elements;
22981 with Ada.Exceptions; use Ada.Exceptions;
22982 procedure Debug_Pool_Test is
22984    type T is access Integer;
22985    type U is access all T;
22987    P : GNAT.Debug_Pools.Debug_Pool;
22988    for T'Storage_Pool use P;
22990    procedure Free is new Unchecked_Deallocation (Integer, T);
22991    function UC is new Unchecked_Conversion (U, T);
22992    A, B : aliased T;
22994    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
22996 begin
22997    Info (P);
22998    A := new Integer;
22999    B := new Integer;
23000    B := A;
23001    Info (P);
23002    Free (A);
23003    begin
23004       Put_Line (Integer'Image(B.all));
23005    exception
23006       when E : others => Put_Line ("raised: " & Exception_Name (E));
23007    end;
23008    begin
23009       Free (B);
23010    exception
23011       when E : others => Put_Line ("raised: " & Exception_Name (E));
23012    end;
23013    B := UC(A'Access);
23014    begin
23015       Put_Line (Integer'Image(B.all));
23016    exception
23017       when E : others => Put_Line ("raised: " & Exception_Name (E));
23018    end;
23019    begin
23020       Free (B);
23021    exception
23022       when E : others => Put_Line ("raised: " & Exception_Name (E));
23023    end;
23024    Info (P);
23025 end Debug_Pool_Test;
23026 @end example
23027 @end quotation
23029 The debug pool mechanism provides the following precise diagnostics on the
23030 execution of this erroneous program:
23032 @quotation
23034 @example
23035 Debug Pool info:
23036   Total allocated bytes :  0
23037   Total deallocated bytes :  0
23038   Current Water Mark:  0
23039   High Water Mark:  0
23041 Debug Pool info:
23042   Total allocated bytes :  8
23043   Total deallocated bytes :  0
23044   Current Water Mark:  8
23045   High Water Mark:  8
23047 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
23048 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
23049 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
23050 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
23051 Debug Pool info:
23052   Total allocated bytes :  8
23053   Total deallocated bytes :  4
23054   Current Water Mark:  4
23055   High Water Mark:  8
23056 @end example
23057 @end quotation
23060 @c -- Non-breaking space in running text
23061 @c -- E.g. Ada |nbsp| 95
23063 @node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
23064 @anchor{gnat_ugn/platform_specific_information platform-specific-information}@anchor{d}@anchor{gnat_ugn/platform_specific_information doc}@anchor{1cf}@anchor{gnat_ugn/platform_specific_information id1}@anchor{1d0}
23065 @chapter Platform-Specific Information
23068 This appendix contains information relating to the implementation
23069 of run-time libraries on various platforms and also covers
23070 topics related to the GNAT implementation on Windows and Mac OS.
23072 @menu
23073 * Run-Time Libraries:: 
23074 * Specifying a Run-Time Library:: 
23075 * Microsoft Windows Topics:: 
23076 * Mac OS Topics:: 
23078 @end menu
23080 @node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
23081 @anchor{gnat_ugn/platform_specific_information id2}@anchor{1d1}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{2b}
23082 @section Run-Time Libraries
23085 @geindex Tasking and threads libraries
23087 @geindex Threads libraries and tasking
23089 @geindex Run-time libraries (platform-specific information)
23091 The GNAT run-time implementation may vary with respect to both the
23092 underlying threads library and the exception handling scheme.
23093 For threads support, one or more of the following are supplied:
23096 @itemize *
23098 @item 
23099 @strong{native threads library}, a binding to the thread package from
23100 the underlying operating system
23102 @item 
23103 @strong{pthreads library} (Sparc Solaris only), a binding to the Solaris
23104 POSIX thread package
23105 @end itemize
23107 For exception handling, either or both of two models are supplied:
23109 @quotation
23111 @geindex Zero-Cost Exceptions
23113 @geindex ZCX (Zero-Cost Exceptions)
23114 @end quotation
23117 @itemize *
23119 @item 
23120 @strong{Zero-Cost Exceptions} ("ZCX"),
23121 which uses binder-generated tables that
23122 are interrogated at run time to locate a handler.
23124 @geindex setjmp/longjmp Exception Model
23126 @geindex SJLJ (setjmp/longjmp Exception Model)
23128 @item 
23129 @strong{setjmp / longjmp} ('SJLJ'),
23130 which uses dynamically-set data to establish
23131 the set of handlers
23132 @end itemize
23134 Most programs should experience a substantial speed improvement by
23135 being compiled with a ZCX run-time.
23136 This is especially true for
23137 tasking applications or applications with many exception handlers.@}
23139 This section summarizes which combinations of threads and exception support
23140 are supplied on various GNAT platforms.
23141 It then shows how to select a particular library either
23142 permanently or temporarily,
23143 explains the properties of (and tradeoffs among) the various threads
23144 libraries, and provides some additional
23145 information about several specific platforms.
23147 @menu
23148 * Summary of Run-Time Configurations:: 
23150 @end menu
23152 @node Summary of Run-Time Configurations,,,Run-Time Libraries
23153 @anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{1d2}@anchor{gnat_ugn/platform_specific_information id3}@anchor{1d3}
23154 @subsection Summary of Run-Time Configurations
23158 @multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
23159 @headitem
23161 Platform
23163 @tab
23165 Run-Time
23167 @tab
23169 Tasking
23171 @tab
23173 Exceptions
23175 @item
23177 ppc-aix
23179 @tab
23181 rts-native
23182 (default)
23184 @tab
23186 native AIX threads
23188 @tab
23192 @item
23194 rts-sjlj
23196 @tab
23198 native AIX threads
23200 @tab
23202 SJLJ
23204 @item
23206 sparc-solaris
23208 @tab
23210 rts-native
23211 (default)
23213 @tab
23215 native Solaris
23216 threads library
23218 @tab
23222 @item
23224 rts-pthread
23226 @tab
23228 pthread library
23230 @tab
23234 @item
23236 rts-sjlj
23238 @tab
23240 native Solaris
23241 threads library
23243 @tab
23245 SJLJ
23247 @item
23249 sparc64-solaris
23251 @tab
23253 rts-native
23254 (default)
23256 @tab
23258 native Solaris
23259 threads library
23261 @tab
23265 @item
23267 x86-linux
23269 @tab
23271 rts-native
23272 (default)
23274 @tab
23276 pthread library
23278 @tab
23282 @item
23284 rts-sjlj
23286 @tab
23288 pthread library
23290 @tab
23292 SJLJ
23294 @item
23296 x86-lynx
23298 @tab
23300 rts-native
23301 (default)
23303 @tab
23305 native LynxOS threads
23307 @tab
23309 SJLJ
23311 @item
23313 x86-solaris
23315 @tab
23317 rts-native
23318 (default)
23320 @tab
23322 native Solaris
23323 threads library
23325 @tab
23329 @item
23331 rts-sjlj
23333 @tab
23335 native Solaris
23336 threads library
23338 @tab
23340 SJLJ
23342 @item
23344 x86-windows
23346 @tab
23348 rts-native
23349 (default)
23351 @tab
23353 native Win32 threads
23355 @tab
23359 @item
23361 rts-sjlj
23363 @tab
23365 native Win32 threads
23367 @tab
23369 SJLJ
23371 @item
23373 x86_64-linux
23375 @tab
23377 rts-native
23378 (default)
23380 @tab
23382 pthread library
23384 @tab
23388 @item
23390 rts-sjlj
23392 @tab
23394 pthread library
23396 @tab
23398 SJLJ
23400 @end multitable
23403 @node Specifying a Run-Time Library,Microsoft Windows Topics,Run-Time Libraries,Platform-Specific Information
23404 @anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{1d4}@anchor{gnat_ugn/platform_specific_information id4}@anchor{1d5}
23405 @section Specifying a Run-Time Library
23408 The @code{adainclude} subdirectory containing the sources of the GNAT
23409 run-time library, and the @code{adalib} subdirectory containing the
23410 @code{ALI} files and the static and/or shared GNAT library, are located
23411 in the gcc target-dependent area:
23413 @quotation
23415 @example
23416 target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
23417 @end example
23418 @end quotation
23420 As indicated above, on some platforms several run-time libraries are supplied.
23421 These libraries are installed in the target dependent area and
23422 contain a complete source and binary subdirectory. The detailed description
23423 below explains the differences between the different libraries in terms of
23424 their thread support.
23426 The default run-time library (when GNAT is installed) is @emph{rts-native}.
23427 This default run time is selected by the means of soft links.
23428 For example on x86-linux:
23430 @example
23432 --  $(target-dir)
23433 --      |
23434 --      +--- adainclude----------+
23435 --      |                        |
23436 --      +--- adalib-----------+  |
23437 --      |                     |  |
23438 --      +--- rts-native       |  |
23439 --      |    |                |  |
23440 --      |    +--- adainclude <---+
23441 --      |    |                |
23442 --      |    +--- adalib <----+
23443 --      |
23444 --      +--- rts-sjlj
23445 --           |
23446 --           +--- adainclude
23447 --           |
23448 --           +--- adalib
23449 @end example
23452 @example
23453                $(target-dir)
23454               __/ /      \ \___
23455       _______/   /        \    \_________________
23456      /          /          \                     \
23457     /          /            \                     \
23458 ADAINCLUDE  ADALIB      rts-native             rts-sjlj
23459    :          :            /    \                 /   \
23460    :          :           /      \               /     \
23461    :          :          /        \             /       \
23462    :          :         /          \           /         \
23463    +-------------> adainclude     adalib   adainclude   adalib
23464               :                     ^
23465               :                     :
23466               +---------------------+
23468               Run-Time Library Directory Structure
23469    (Upper-case names and dotted/dashed arrows represent soft links)
23470 @end example
23472 If the @emph{rts-sjlj} library is to be selected on a permanent basis,
23473 these soft links can be modified with the following commands:
23475 @quotation
23477 @example
23478 $ cd $target
23479 $ rm -f adainclude adalib
23480 $ ln -s rts-sjlj/adainclude adainclude
23481 $ ln -s rts-sjlj/adalib adalib
23482 @end example
23483 @end quotation
23485 Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
23486 @code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
23487 @code{$target/ada_object_path}.
23489 @geindex --RTS option
23491 Selecting another run-time library temporarily can be
23492 achieved by using the @emph{--RTS} switch, e.g., @emph{--RTS=sjlj}
23493 @anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy}@anchor{1d6}
23494 @geindex SCHED_FIFO scheduling policy
23496 @geindex SCHED_RR scheduling policy
23498 @geindex SCHED_OTHER scheduling policy
23500 @menu
23501 * Choosing the Scheduling Policy:: 
23502 * Solaris-Specific Considerations:: 
23503 * Solaris Threads Issues:: 
23504 * AIX-Specific Considerations:: 
23506 @end menu
23508 @node Choosing the Scheduling Policy,Solaris-Specific Considerations,,Specifying a Run-Time Library
23509 @anchor{gnat_ugn/platform_specific_information id5}@anchor{1d7}
23510 @subsection Choosing the Scheduling Policy
23513 When using a POSIX threads implementation, you have a choice of several
23514 scheduling policies: @cite{SCHED_FIFO}, @cite{SCHED_RR} and @cite{SCHED_OTHER}.
23516 Typically, the default is @cite{SCHED_OTHER}, while using @cite{SCHED_FIFO}
23517 or @cite{SCHED_RR} requires special (e.g., root) privileges.
23519 @geindex pragma Time_Slice
23521 @geindex -T0 option
23523 @geindex pragma Task_Dispatching_Policy
23525 By default, GNAT uses the @cite{SCHED_OTHER} policy. To specify
23526 @cite{SCHED_FIFO},
23527 you can use one of the following:
23530 @itemize *
23532 @item 
23533 @cite{pragma Time_Slice (0.0)}
23535 @item 
23536 the corresponding binder option @emph{-T0}
23538 @item 
23539 @cite{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23540 @end itemize
23542 To specify @cite{SCHED_RR},
23543 you should use @cite{pragma Time_Slice} with a
23544 value greater than 0.0, or else use the corresponding @emph{-T}
23545 binder option.
23547 To make sure a program is running as root, you can put something like
23548 this in a library package body in your application:
23550 @quotation
23552 @example
23553 function geteuid return Integer;
23554 pragma Import (C, geteuid, "geteuid");
23555 Ignore : constant Boolean :=
23556   (if geteuid = 0 then True else raise Program_Error with "must be root");
23557 @end example
23558 @end quotation
23560 It gets the effective user id, and if it's not 0 (i.e. root), it raises
23561 Program_Error.
23563 @geindex Solaris Sparc threads libraries
23565 @node Solaris-Specific Considerations,Solaris Threads Issues,Choosing the Scheduling Policy,Specifying a Run-Time Library
23566 @anchor{gnat_ugn/platform_specific_information id6}@anchor{1d8}@anchor{gnat_ugn/platform_specific_information solaris-specific-considerations}@anchor{1d9}
23567 @subsection Solaris-Specific Considerations
23570 This section addresses some topics related to the various threads libraries
23571 on Sparc Solaris.
23573 @geindex rts-pthread threads library
23575 @node Solaris Threads Issues,AIX-Specific Considerations,Solaris-Specific Considerations,Specifying a Run-Time Library
23576 @anchor{gnat_ugn/platform_specific_information id7}@anchor{1da}@anchor{gnat_ugn/platform_specific_information solaris-threads-issues}@anchor{1db}
23577 @subsection Solaris Threads Issues
23580 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
23581 library based on POSIX threads --- @emph{rts-pthread}.
23583 @geindex PTHREAD_PRIO_INHERIT policy (under rts-pthread)
23585 @geindex PTHREAD_PRIO_PROTECT policy (under rts-pthread)
23587 @geindex pragma Locking_Policy (under rts-pthread)
23589 @geindex Inheritance_Locking (under rts-pthread)
23591 @geindex Ceiling_Locking (under rts-pthread)
23593 This run-time library has the advantage of being mostly shared across all
23594 POSIX-compliant thread implementations, and it also provides under
23595 Solaris 8 the @cite{PTHREAD_PRIO_INHERIT}
23596 and @cite{PTHREAD_PRIO_PROTECT}
23597 semantics that can be selected using the predefined pragma
23598 @cite{Locking_Policy}
23599 with respectively
23600 @cite{Inheritance_Locking} and @cite{Ceiling_Locking} as the policy.
23602 As explained above, the native run-time library is based on the Solaris thread
23603 library (@cite{libthread}) and is the default library.
23605 @geindex GNAT_PROCESSOR environment variable (on Sparc Solaris)
23607 When the Solaris threads library is used (this is the default), programs
23608 compiled with GNAT can automatically take advantage of
23609 and can thus execute on multiple processors.
23610 The user can alternatively specify a processor on which the program should run
23611 to emulate a single-processor system. The multiprocessor / uniprocessor choice
23612 is made by
23613 setting the environment variable 
23614 @geindex GNAT_PROCESSOR
23615 @geindex environment variable; GNAT_PROCESSOR
23616 @code{GNAT_PROCESSOR}
23617 to one of the following:
23619 @quotation
23622 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
23623 @headitem
23625 @code{GNAT_PROCESSOR} Value
23627 @tab
23629 Effect
23631 @item
23633 @emph{-2}
23635 @tab
23637 Use the default configuration (run the program on all
23638 available processors) - this is the same as having @cite{GNAT_PROCESSOR}
23639 unset
23641 @item
23643 @emph{-1}
23645 @tab
23647 Let the run-time implementation choose one processor and run the
23648 program on that processor
23650 @item
23652 @emph{0 .. Last_Proc}
23654 @tab
23656 Run the program on the specified processor.
23657 @cite{Last_Proc} is equal to @cite{_SC_NPROCESSORS_CONF - 1}
23658 (where @cite{_SC_NPROCESSORS_CONF} is a system variable).
23660 @end multitable
23662 @end quotation
23664 @node AIX-Specific Considerations,,Solaris Threads Issues,Specifying a Run-Time Library
23665 @anchor{gnat_ugn/platform_specific_information aix-specific-considerations}@anchor{1dc}@anchor{gnat_ugn/platform_specific_information id8}@anchor{1dd}
23666 @subsection AIX-Specific Considerations
23669 @geindex AIX resolver library
23671 On AIX, the resolver library initializes some internal structure on
23672 the first call to @cite{get*by*} functions, which are used to implement
23673 @cite{GNAT.Sockets.Get_Host_By_Name} and
23674 @cite{GNAT.Sockets.Get_Host_By_Address}.
23675 If such initialization occurs within an Ada task, and the stack size for
23676 the task is the default size, a stack overflow may occur.
23678 To avoid this overflow, the user should either ensure that the first call
23679 to @cite{GNAT.Sockets.Get_Host_By_Name} or
23680 @cite{GNAT.Sockets.Get_Host_By_Addrss}
23681 occurs in the environment task, or use @cite{pragma Storage_Size} to
23682 specify a sufficiently large size for the stack of the task that contains
23683 this call.
23685 @geindex Windows NT
23687 @geindex Windows 95
23689 @geindex Windows 98
23691 @node Microsoft Windows Topics,Mac OS Topics,Specifying a Run-Time Library,Platform-Specific Information
23692 @anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{2c}@anchor{gnat_ugn/platform_specific_information id9}@anchor{1de}
23693 @section Microsoft Windows Topics
23696 This section describes topics that are specific to the Microsoft Windows
23697 platforms.
23703 @menu
23704 * Using GNAT on Windows:: 
23705 * Using a network installation of GNAT:: 
23706 * CONSOLE and WINDOWS subsystems:: 
23707 * Temporary Files:: 
23708 * Disabling Command Line Argument Expansion:: 
23709 * Mixed-Language Programming on Windows:: 
23710 * Windows Specific Add-Ons:: 
23712 @end menu
23714 @node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
23715 @anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{1df}@anchor{gnat_ugn/platform_specific_information id10}@anchor{1e0}
23716 @subsection Using GNAT on Windows
23719 One of the strengths of the GNAT technology is that its tool set
23720 (@emph{gcc}, @emph{gnatbind}, @emph{gnatlink}, @emph{gnatmake}, the
23721 @cite{gdb} debugger, etc.) is used in the same way regardless of the
23722 platform.
23724 On Windows this tool set is complemented by a number of Microsoft-specific
23725 tools that have been provided to facilitate interoperability with Windows
23726 when this is required. With these tools:
23729 @itemize *
23731 @item 
23732 You can build applications using the @cite{CONSOLE} or @cite{WINDOWS}
23733 subsystems.
23735 @item 
23736 You can use any Dynamically Linked Library (DLL) in your Ada code (both
23737 relocatable and non-relocatable DLLs are supported).
23739 @item 
23740 You can build Ada DLLs for use in other applications. These applications
23741 can be written in a language other than Ada (e.g., C, C++, etc). Again both
23742 relocatable and non-relocatable Ada DLLs are supported.
23744 @item 
23745 You can include Windows resources in your Ada application.
23747 @item 
23748 You can use or create COM/DCOM objects.
23749 @end itemize
23751 Immediately below are listed all known general GNAT-for-Windows restrictions.
23752 Other restrictions about specific features like Windows Resources and DLLs
23753 are listed in separate sections below.
23756 @itemize *
23758 @item 
23759 It is not possible to use @cite{GetLastError} and @cite{SetLastError}
23760 when tasking, protected records, or exceptions are used. In these
23761 cases, in order to implement Ada semantics, the GNAT run-time system
23762 calls certain Win32 routines that set the last error variable to 0 upon
23763 success. It should be possible to use @cite{GetLastError} and
23764 @cite{SetLastError} when tasking, protected record, and exception
23765 features are not used, but it is not guaranteed to work.
23767 @item 
23768 It is not possible to link against Microsoft C++ libraries except for
23769 import libraries. Interfacing must be done by the mean of DLLs.
23771 @item 
23772 It is possible to link against Microsoft C libraries. Yet the preferred
23773 solution is to use C/C++ compiler that comes with GNAT, since it
23774 doesn't require having two different development environments and makes the
23775 inter-language debugging experience smoother.
23777 @item 
23778 When the compilation environment is located on FAT32 drives, users may
23779 experience recompilations of the source files that have not changed if
23780 Daylight Saving Time (DST) state has changed since the last time files
23781 were compiled. NTFS drives do not have this problem.
23783 @item 
23784 No components of the GNAT toolset use any entries in the Windows
23785 registry. The only entries that can be created are file associations and
23786 PATH settings, provided the user has chosen to create them at installation
23787 time, as well as some minimal book-keeping information needed to correctly
23788 uninstall or integrate different GNAT products.
23789 @end itemize
23791 @node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
23792 @anchor{gnat_ugn/platform_specific_information id11}@anchor{1e1}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{1e2}
23793 @subsection Using a network installation of GNAT
23796 Make sure the system on which GNAT is installed is accessible from the
23797 current machine, i.e., the install location is shared over the network.
23798 Shared resources are accessed on Windows by means of UNC paths, which
23799 have the format @cite{\\server\sharename\path}
23801 In order to use such a network installation, simply add the UNC path of the
23802 @code{bin} directory of your GNAT installation in front of your PATH. For
23803 example, if GNAT is installed in @code{\GNAT} directory of a share location
23804 called @code{c-drive} on a machine @code{LOKI}, the following command will
23805 make it available:
23807 @quotation
23809 @example
23810 $ path \\loki\c-drive\gnat\bin;%path%`
23811 @end example
23812 @end quotation
23814 Be aware that every compilation using the network installation results in the
23815 transfer of large amounts of data across the network and will likely cause
23816 serious performance penalty.
23818 @node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
23819 @anchor{gnat_ugn/platform_specific_information id12}@anchor{1e3}@anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{1e4}
23820 @subsection CONSOLE and WINDOWS subsystems
23823 @geindex CONSOLE Subsystem
23825 @geindex WINDOWS Subsystem
23827 @geindex -mwindows
23829 There are two main subsystems under Windows. The @cite{CONSOLE} subsystem
23830 (which is the default subsystem) will always create a console when
23831 launching the application. This is not something desirable when the
23832 application has a Windows GUI. To get rid of this console the
23833 application must be using the @cite{WINDOWS} subsystem. To do so
23834 the @emph{-mwindows} linker option must be specified.
23836 @quotation
23838 @example
23839 $ gnatmake winprog -largs -mwindows
23840 @end example
23841 @end quotation
23843 @node Temporary Files,Disabling Command Line Argument Expansion,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
23844 @anchor{gnat_ugn/platform_specific_information id13}@anchor{1e5}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{1e6}
23845 @subsection Temporary Files
23848 @geindex Temporary files
23850 It is possible to control where temporary files gets created by setting
23851 the 
23852 @geindex TMP
23853 @geindex environment variable; TMP
23854 @code{TMP} environment variable. The file will be created:
23857 @itemize *
23859 @item 
23860 Under the directory pointed to by the 
23861 @geindex TMP
23862 @geindex environment variable; TMP
23863 @code{TMP} environment variable if
23864 this directory exists.
23866 @item 
23867 Under @code{c:\temp}, if the 
23868 @geindex TMP
23869 @geindex environment variable; TMP
23870 @code{TMP} environment variable is not
23871 set (or not pointing to a directory) and if this directory exists.
23873 @item 
23874 Under the current working directory otherwise.
23875 @end itemize
23877 This allows you to determine exactly where the temporary
23878 file will be created. This is particularly useful in networked
23879 environments where you may not have write access to some
23880 directories.
23882 @node Disabling Command Line Argument Expansion,Mixed-Language Programming on Windows,Temporary Files,Microsoft Windows Topics
23883 @anchor{gnat_ugn/platform_specific_information disabling-command-line-argument-expansion}@anchor{1e7}
23884 @subsection Disabling Command Line Argument Expansion
23887 @geindex Command Line Argument Expansion
23889 By default, an executable compiled for the @strong{Windows} platform will do
23890 the following postprocessing on the arguments passed on the command
23891 line:
23894 @itemize *
23896 @item 
23897 If the argument contains the characters @code{*} and/or @code{?}, then
23898 file expansion will be attempted. For example, if the current directory
23899 contains @code{a.txt} and @code{b.txt}, then when calling:
23901 @example
23902 $ my_ada_program *.txt
23903 @end example
23905 The following arguments will effectively be passed to the main program
23906 (for example when using @code{Ada.Command_Line.Argument}):
23908 @example
23909 Ada.Command_Line.Argument (1) -> "a.txt"
23910 Ada.Command_Line.Argument (2) -> "b.txt"
23911 @end example
23913 @item 
23914 Filename expansion can be disabled for a given argument by using single
23915 quotes. Thus, calling:
23917 @example
23918 $ my_ada_program '*.txt'
23919 @end example
23921 will result in:
23923 @example
23924 Ada.Command_Line.Argument (1) -> "*.txt"
23925 @end example
23926 @end itemize
23928 Note that if the program is launched from a shell such as @strong{Cygwin} @strong{Bash}
23929 then quote removal might be performed by the shell.
23931 In some contexts it might be useful to disable this feature (for example if
23932 the program performs its own argument expansion). In order to do this, a C
23933 symbol needs to be defined and set to @code{0}. You can do this by
23934 adding the following code fragment in one of your @strong{Ada} units:
23936 @example
23937 Do_Argv_Expansion : Integer := 0;
23938 pragma Export (C, Do_Argv_Expansion, "__gnat_do_argv_expansion");
23939 @end example
23941 The results of previous examples will be respectively:
23943 @example
23944 Ada.Command_Line.Argument (1) -> "*.txt"
23945 @end example
23947 and:
23949 @example
23950 Ada.Command_Line.Argument (1) -> "'*.txt'"
23951 @end example
23953 @node Mixed-Language Programming on Windows,Windows Specific Add-Ons,Disabling Command Line Argument Expansion,Microsoft Windows Topics
23954 @anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{1e8}@anchor{gnat_ugn/platform_specific_information id14}@anchor{1e9}
23955 @subsection Mixed-Language Programming on Windows
23958 Developing pure Ada applications on Windows is no different than on
23959 other GNAT-supported platforms. However, when developing or porting an
23960 application that contains a mix of Ada and C/C++, the choice of your
23961 Windows C/C++ development environment conditions your overall
23962 interoperability strategy.
23964 If you use @emph{gcc} or Microsoft C to compile the non-Ada part of
23965 your application, there are no Windows-specific restrictions that
23966 affect the overall interoperability with your Ada code. If you do want
23967 to use the Microsoft tools for your C++ code, you have two choices:
23970 @itemize *
23972 @item 
23973 Encapsulate your C++ code in a DLL to be linked with your Ada
23974 application. In this case, use the Microsoft or whatever environment to
23975 build the DLL and use GNAT to build your executable
23976 (@ref{1ea,,Using DLLs with GNAT}).
23978 @item 
23979 Or you can encapsulate your Ada code in a DLL to be linked with the
23980 other part of your application. In this case, use GNAT to build the DLL
23981 (@ref{1eb,,Building DLLs with GNAT Project files}) and use the Microsoft
23982 or whatever environment to build your executable.
23983 @end itemize
23985 In addition to the description about C main in
23986 @ref{44,,Mixed Language Programming} section, if the C main uses a
23987 stand-alone library it is required on x86-windows to
23988 setup the SEH context. For this the C main must looks like this:
23990 @quotation
23992 @example
23993 /* main.c */
23994 extern void adainit (void);
23995 extern void adafinal (void);
23996 extern void __gnat_initialize(void*);
23997 extern void call_to_ada (void);
23999 int main (int argc, char *argv[])
24001   int SEH [2];
24003   /* Initialize the SEH context */
24004   __gnat_initialize (&SEH);
24006   adainit();
24008   /* Then call Ada services in the stand-alone library */
24010   call_to_ada();
24012   adafinal();
24014 @end example
24015 @end quotation
24017 Note that this is not needed on x86_64-windows where the Windows
24018 native SEH support is used.
24020 @menu
24021 * Windows Calling Conventions:: 
24022 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
24023 * Using DLLs with GNAT:: 
24024 * Building DLLs with GNAT Project files:: 
24025 * Building DLLs with GNAT:: 
24026 * Building DLLs with gnatdll:: 
24027 * Ada DLLs and Finalization:: 
24028 * Creating a Spec for Ada DLLs:: 
24029 * GNAT and Windows Resources:: 
24030 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
24031 * Debugging a DLL:: 
24032 * Setting Stack Size from gnatlink:: 
24033 * Setting Heap Size from gnatlink:: 
24035 @end menu
24037 @node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
24038 @anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{1ec}@anchor{gnat_ugn/platform_specific_information id15}@anchor{1ed}
24039 @subsubsection Windows Calling Conventions
24042 @geindex Stdcall
24044 @geindex APIENTRY
24046 This section pertain only to Win32. On Win64 there is a single native
24047 calling convention. All convention specifiers are ignored on this
24048 platform.
24050 When a subprogram @cite{F} (caller) calls a subprogram @cite{G}
24051 (callee), there are several ways to push @cite{G}'s parameters on the
24052 stack and there are several possible scenarios to clean up the stack
24053 upon @cite{G}'s return. A calling convention is an agreed upon software
24054 protocol whereby the responsibilities between the caller (@cite{F}) and
24055 the callee (@cite{G}) are clearly defined. Several calling conventions
24056 are available for Windows:
24059 @itemize *
24061 @item 
24062 @cite{C} (Microsoft defined)
24064 @item 
24065 @cite{Stdcall} (Microsoft defined)
24067 @item 
24068 @cite{Win32} (GNAT specific)
24070 @item 
24071 @cite{DLL} (GNAT specific)
24072 @end itemize
24074 @menu
24075 * C Calling Convention:: 
24076 * Stdcall Calling Convention:: 
24077 * Win32 Calling Convention:: 
24078 * DLL Calling Convention:: 
24080 @end menu
24082 @node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
24083 @anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{1ee}@anchor{gnat_ugn/platform_specific_information id16}@anchor{1ef}
24084 @subsubsection @cite{C} Calling Convention
24087 This is the default calling convention used when interfacing to C/C++
24088 routines compiled with either @emph{gcc} or Microsoft Visual C++.
24090 In the @cite{C} calling convention subprogram parameters are pushed on the
24091 stack by the caller from right to left. The caller itself is in charge of
24092 cleaning up the stack after the call. In addition, the name of a routine
24093 with @cite{C} calling convention is mangled by adding a leading underscore.
24095 The name to use on the Ada side when importing (or exporting) a routine
24096 with @cite{C} calling convention is the name of the routine. For
24097 instance the C function:
24099 @quotation
24101 @example
24102 int get_val (long);
24103 @end example
24104 @end quotation
24106 should be imported from Ada as follows:
24108 @quotation
24110 @example
24111 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24112 pragma Import (C, Get_Val, External_Name => "get_val");
24113 @end example
24114 @end quotation
24116 Note that in this particular case the @cite{External_Name} parameter could
24117 have been omitted since, when missing, this parameter is taken to be the
24118 name of the Ada entity in lower case. When the @cite{Link_Name} parameter
24119 is missing, as in the above example, this parameter is set to be the
24120 @cite{External_Name} with a leading underscore.
24122 When importing a variable defined in C, you should always use the @cite{C}
24123 calling convention unless the object containing the variable is part of a
24124 DLL (in which case you should use the @cite{Stdcall} calling
24125 convention, @ref{1f0,,Stdcall Calling Convention}).
24127 @node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
24128 @anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{1f0}@anchor{gnat_ugn/platform_specific_information id17}@anchor{1f1}
24129 @subsubsection @cite{Stdcall} Calling Convention
24132 This convention, which was the calling convention used for Pascal
24133 programs, is used by Microsoft for all the routines in the Win32 API for
24134 efficiency reasons. It must be used to import any routine for which this
24135 convention was specified.
24137 In the @cite{Stdcall} calling convention subprogram parameters are pushed
24138 on the stack by the caller from right to left. The callee (and not the
24139 caller) is in charge of cleaning the stack on routine exit. In addition,
24140 the name of a routine with @cite{Stdcall} calling convention is mangled by
24141 adding a leading underscore (as for the @cite{C} calling convention) and a
24142 trailing @code{@@@emph{nn}}, where @cite{nn} is the overall size (in
24143 bytes) of the parameters passed to the routine.
24145 The name to use on the Ada side when importing a C routine with a
24146 @cite{Stdcall} calling convention is the name of the C routine. The leading
24147 underscore and trailing @code{@@@emph{nn}} are added automatically by
24148 the compiler. For instance the Win32 function:
24150 @quotation
24152 @example
24153 APIENTRY int get_val (long);
24154 @end example
24155 @end quotation
24157 should be imported from Ada as follows:
24159 @quotation
24161 @example
24162 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24163 pragma Import (Stdcall, Get_Val);
24164 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
24165 @end example
24166 @end quotation
24168 As for the @cite{C} calling convention, when the @cite{External_Name}
24169 parameter is missing, it is taken to be the name of the Ada entity in lower
24170 case. If instead of writing the above import pragma you write:
24172 @quotation
24174 @example
24175 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24176 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
24177 @end example
24178 @end quotation
24180 then the imported routine is @cite{_retrieve_val@@4}. However, if instead
24181 of specifying the @cite{External_Name} parameter you specify the
24182 @cite{Link_Name} as in the following example:
24184 @quotation
24186 @example
24187 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24188 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
24189 @end example
24190 @end quotation
24192 then the imported routine is @cite{retrieve_val}, that is, there is no
24193 decoration at all. No leading underscore and no Stdcall suffix
24194 @code{@@@emph{nn}}.
24196 This is especially important as in some special cases a DLL's entry
24197 point name lacks a trailing @code{@@@emph{nn}} while the exported
24198 name generated for a call has it.
24200 It is also possible to import variables defined in a DLL by using an
24201 import pragma for a variable. As an example, if a DLL contains a
24202 variable defined as:
24204 @quotation
24206 @example
24207 int my_var;
24208 @end example
24209 @end quotation
24211 then, to access this variable from Ada you should write:
24213 @quotation
24215 @example
24216 My_Var : Interfaces.C.int;
24217 pragma Import (Stdcall, My_Var);
24218 @end example
24219 @end quotation
24221 Note that to ease building cross-platform bindings this convention
24222 will be handled as a @cite{C} calling convention on non-Windows platforms.
24224 @node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
24225 @anchor{gnat_ugn/platform_specific_information id18}@anchor{1f2}@anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{1f3}
24226 @subsubsection @cite{Win32} Calling Convention
24229 This convention, which is GNAT-specific is fully equivalent to the
24230 @cite{Stdcall} calling convention described above.
24232 @node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
24233 @anchor{gnat_ugn/platform_specific_information id19}@anchor{1f4}@anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{1f5}
24234 @subsubsection @cite{DLL} Calling Convention
24237 This convention, which is GNAT-specific is fully equivalent to the
24238 @cite{Stdcall} calling convention described above.
24240 @node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
24241 @anchor{gnat_ugn/platform_specific_information id20}@anchor{1f6}@anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{1f7}
24242 @subsubsection Introduction to Dynamic Link Libraries (DLLs)
24245 @geindex DLL
24247 A Dynamically Linked Library (DLL) is a library that can be shared by
24248 several applications running under Windows. A DLL can contain any number of
24249 routines and variables.
24251 One advantage of DLLs is that you can change and enhance them without
24252 forcing all the applications that depend on them to be relinked or
24253 recompiled. However, you should be aware than all calls to DLL routines are
24254 slower since, as you will understand below, such calls are indirect.
24256 To illustrate the remainder of this section, suppose that an application
24257 wants to use the services of a DLL @code{API.dll}. To use the services
24258 provided by @code{API.dll} you must statically link against the DLL or
24259 an import library which contains a jump table with an entry for each
24260 routine and variable exported by the DLL. In the Microsoft world this
24261 import library is called @code{API.lib}. When using GNAT this import
24262 library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
24263 @code{libAPI.a} or @code{libapi.a} (names are case insensitive).
24265 After you have linked your application with the DLL or the import library
24266 and you run your application, here is what happens:
24269 @itemize *
24271 @item 
24272 Your application is loaded into memory.
24274 @item 
24275 The DLL @code{API.dll} is mapped into the address space of your
24276 application. This means that:
24279 @itemize -
24281 @item 
24282 The DLL will use the stack of the calling thread.
24284 @item 
24285 The DLL will use the virtual address space of the calling process.
24287 @item 
24288 The DLL will allocate memory from the virtual address space of the calling
24289 process.
24291 @item 
24292 Handles (pointers) can be safely exchanged between routines in the DLL
24293 routines and routines in the application using the DLL.
24294 @end itemize
24296 @item 
24297 The entries in the jump table (from the import library @code{libAPI.dll.a}
24298 or @code{API.lib} or automatically created when linking against a DLL)
24299 which is part of your application are initialized with the addresses
24300 of the routines and variables in @code{API.dll}.
24302 @item 
24303 If present in @code{API.dll}, routines @cite{DllMain} or
24304 @cite{DllMainCRTStartup} are invoked. These routines typically contain
24305 the initialization code needed for the well-being of the routines and
24306 variables exported by the DLL.
24307 @end itemize
24309 There is an additional point which is worth mentioning. In the Windows
24310 world there are two kind of DLLs: relocatable and non-relocatable
24311 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
24312 in the target application address space. If the addresses of two
24313 non-relocatable DLLs overlap and these happen to be used by the same
24314 application, a conflict will occur and the application will run
24315 incorrectly. Hence, when possible, it is always preferable to use and
24316 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
24317 supported by GNAT. Note that the @emph{-s} linker option (see GNU Linker
24318 User's Guide) removes the debugging symbols from the DLL but the DLL can
24319 still be relocated.
24321 As a side note, an interesting difference between Microsoft DLLs and
24322 Unix shared libraries, is the fact that on most Unix systems all public
24323 routines are exported by default in a Unix shared library, while under
24324 Windows it is possible (but not required) to list exported routines in
24325 a definition file (see @ref{1f8,,The Definition File}).
24327 @node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
24328 @anchor{gnat_ugn/platform_specific_information id21}@anchor{1f9}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{1ea}
24329 @subsubsection Using DLLs with GNAT
24332 To use the services of a DLL, say @code{API.dll}, in your Ada application
24333 you must have:
24336 @itemize *
24338 @item 
24339 The Ada spec for the routines and/or variables you want to access in
24340 @code{API.dll}. If not available this Ada spec must be built from the C/C++
24341 header files provided with the DLL.
24343 @item 
24344 The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
24345 mentioned an import library is a statically linked library containing the
24346 import table which will be filled at load time to point to the actual
24347 @code{API.dll} routines. Sometimes you don't have an import library for the
24348 DLL you want to use. The following sections will explain how to build
24349 one. Note that this is optional.
24351 @item 
24352 The actual DLL, @code{API.dll}.
24353 @end itemize
24355 Once you have all the above, to compile an Ada application that uses the
24356 services of @code{API.dll} and whose main subprogram is @cite{My_Ada_App},
24357 you simply issue the command
24359 @quotation
24361 @example
24362 $ gnatmake my_ada_app -largs -lAPI
24363 @end example
24364 @end quotation
24366 The argument @emph{-largs -lAPI} at the end of the @emph{gnatmake} command
24367 tells the GNAT linker to look for an import library. The linker will
24368 look for a library name in this specific order:
24371 @itemize *
24373 @item 
24374 @code{libAPI.dll.a}
24376 @item 
24377 @code{API.dll.a}
24379 @item 
24380 @code{libAPI.a}
24382 @item 
24383 @code{API.lib}
24385 @item 
24386 @code{libAPI.dll}
24388 @item 
24389 @code{API.dll}
24390 @end itemize
24392 The first three are the GNU style import libraries. The third is the
24393 Microsoft style import libraries. The last two are the actual DLL names.
24395 Note that if the Ada package spec for @code{API.dll} contains the
24396 following pragma
24398 @quotation
24400 @example
24401 pragma Linker_Options ("-lAPI");
24402 @end example
24403 @end quotation
24405 you do not have to add @emph{-largs -lAPI} at the end of the
24406 @emph{gnatmake} command.
24408 If any one of the items above is missing you will have to create it
24409 yourself. The following sections explain how to do so using as an
24410 example a fictitious DLL called @code{API.dll}.
24412 @menu
24413 * Creating an Ada Spec for the DLL Services:: 
24414 * Creating an Import Library:: 
24416 @end menu
24418 @node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
24419 @anchor{gnat_ugn/platform_specific_information creating-an-ada-spec-for-the-dll-services}@anchor{1fa}@anchor{gnat_ugn/platform_specific_information id22}@anchor{1fb}
24420 @subsubsection Creating an Ada Spec for the DLL Services
24423 A DLL typically comes with a C/C++ header file which provides the
24424 definitions of the routines and variables exported by the DLL. The Ada
24425 equivalent of this header file is a package spec that contains definitions
24426 for the imported entities. If the DLL you intend to use does not come with
24427 an Ada spec you have to generate one such spec yourself. For example if
24428 the header file of @code{API.dll} is a file @code{api.h} containing the
24429 following two definitions:
24431 @quotation
24433 @example
24434 int some_var;
24435 int get (char *);
24436 @end example
24437 @end quotation
24439 then the equivalent Ada spec could be:
24441 @quotation
24443 @example
24444 with Interfaces.C.Strings;
24445 package API is
24446    use Interfaces;
24448    Some_Var : C.int;
24449    function Get (Str : C.Strings.Chars_Ptr) return C.int;
24451 private
24452    pragma Import (C, Get);
24453    pragma Import (DLL, Some_Var);
24454 end API;
24455 @end example
24456 @end quotation
24458 @node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
24459 @anchor{gnat_ugn/platform_specific_information id23}@anchor{1fc}@anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{1fd}
24460 @subsubsection Creating an Import Library
24463 @geindex Import library
24465 If a Microsoft-style import library @code{API.lib} or a GNAT-style
24466 import library @code{libAPI.dll.a} or @code{libAPI.a} is available
24467 with @code{API.dll} you can skip this section. You can also skip this
24468 section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
24469 as in this case it is possible to link directly against the
24470 DLL. Otherwise read on.
24472 @geindex Definition file
24473 @anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{1f8}
24474 @subsubheading The Definition File
24477 As previously mentioned, and unlike Unix systems, the list of symbols
24478 that are exported from a DLL must be provided explicitly in Windows.
24479 The main goal of a definition file is precisely that: list the symbols
24480 exported by a DLL. A definition file (usually a file with a @cite{.def}
24481 suffix) has the following structure:
24483 @quotation
24485 @example
24486 [LIBRARY `name`]
24487 [DESCRIPTION `string`]
24488 EXPORTS
24489    `symbol1`
24490    `symbol2`
24491    ...
24492 @end example
24493 @end quotation
24496 @table @asis
24498 @item @emph{LIBRARY `name`}
24500 This section, which is optional, gives the name of the DLL.
24502 @item @emph{DESCRIPTION `string`}
24504 This section, which is optional, gives a description string that will be
24505 embedded in the import library.
24507 @item @emph{EXPORTS}
24509 This section gives the list of exported symbols (procedures, functions or
24510 variables). For instance in the case of @code{API.dll} the @cite{EXPORTS}
24511 section of @code{API.def} looks like:
24513 @example
24514 EXPORTS
24515    some_var
24516    get
24517 @end example
24518 @end table
24520 Note that you must specify the correct suffix (@code{@@@emph{nn}})
24521 (see @ref{1ec,,Windows Calling Conventions}) for a Stdcall
24522 calling convention function in the exported symbols list.
24524 There can actually be other sections in a definition file, but these
24525 sections are not relevant to the discussion at hand.
24526 @anchor{gnat_ugn/platform_specific_information create-def-file-automatically}@anchor{1fe}
24527 @subsubheading Creating a Definition File Automatically
24530 You can automatically create the definition file @code{API.def}
24531 (see @ref{1f8,,The Definition File}) from a DLL.
24532 For that use the @cite{dlltool} program as follows:
24534 @quotation
24536 @example
24537 $ dlltool API.dll -z API.def --export-all-symbols
24538 @end example
24540 Note that if some routines in the DLL have the @cite{Stdcall} convention
24541 (@ref{1ec,,Windows Calling Conventions}) with stripped @code{@@@emph{nn}}
24542 suffix then you'll have to edit @code{api.def} to add it, and specify
24543 @emph{-k} to @emph{gnatdll} when creating the import library.
24545 Here are some hints to find the right @code{@@@emph{nn}} suffix.
24548 @itemize -
24550 @item 
24551 If you have the Microsoft import library (.lib), it is possible to get
24552 the right symbols by using Microsoft @cite{dumpbin} tool (see the
24553 corresponding Microsoft documentation for further details).
24555 @example
24556 $ dumpbin /exports api.lib
24557 @end example
24559 @item 
24560 If you have a message about a missing symbol at link time the compiler
24561 tells you what symbol is expected. You just have to go back to the
24562 definition file and add the right suffix.
24563 @end itemize
24564 @end quotation
24565 @anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{1ff}
24566 @subsubheading GNAT-Style Import Library
24569 To create a static import library from @code{API.dll} with the GNAT tools
24570 you should create the .def file, then use @cite{gnatdll} tool
24571 (see @ref{200,,Using gnatdll}) as follows:
24573 @quotation
24575 @example
24576 $ gnatdll -e API.def -d API.dll
24577 @end example
24579 @cite{gnatdll} takes as input a definition file @code{API.def} and the
24580 name of the DLL containing the services listed in the definition file
24581 @code{API.dll}. The name of the static import library generated is
24582 computed from the name of the definition file as follows: if the
24583 definition file name is @cite{xyz`}.def`, the import library name will
24584 be @cite{lib`@w{`}xyz`}.a`. Note that in the previous example option
24585 @emph{-e} could have been removed because the name of the definition
24586 file (before the '@cite{.def}' suffix) is the same as the name of the
24587 DLL (@ref{200,,Using gnatdll} for more information about @cite{gnatdll}).
24588 @end quotation
24589 @anchor{gnat_ugn/platform_specific_information msvs-style-import-library}@anchor{201}
24590 @subsubheading Microsoft-Style Import Library
24593 A Microsoft import library is needed only if you plan to make an
24594 Ada DLL available to applications developed with Microsoft
24595 tools (@ref{1e8,,Mixed-Language Programming on Windows}).
24597 To create a Microsoft-style import library for @code{API.dll} you
24598 should create the .def file, then build the actual import library using
24599 Microsoft's @cite{lib} utility:
24601 @quotation
24603 @example
24604 $ lib -machine:IX86 -def:API.def -out:API.lib
24605 @end example
24607 If you use the above command the definition file @code{API.def} must
24608 contain a line giving the name of the DLL:
24610 @example
24611 LIBRARY      "API"
24612 @end example
24614 See the Microsoft documentation for further details about the usage of
24615 @cite{lib}.
24616 @end quotation
24618 @node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
24619 @anchor{gnat_ugn/platform_specific_information id24}@anchor{202}@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{1eb}
24620 @subsubsection Building DLLs with GNAT Project files
24623 @geindex DLLs
24624 @geindex building
24626 There is nothing specific to Windows in the build process.
24627 See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24628 chapter of the @emph{GPRbuild User's Guide}.
24630 Due to a system limitation, it is not possible under Windows to create threads
24631 when inside the @cite{DllMain} routine which is used for auto-initialization
24632 of shared libraries, so it is not possible to have library level tasks in SALs.
24634 @node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
24635 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{203}@anchor{gnat_ugn/platform_specific_information id25}@anchor{204}
24636 @subsubsection Building DLLs with GNAT
24639 @geindex DLLs
24640 @geindex building
24642 This section explain how to build DLLs using the GNAT built-in DLL
24643 support. With the following procedure it is straight forward to build
24644 and use DLLs with GNAT.
24647 @itemize *
24649 @item 
24650 Building object files.
24651 The first step is to build all objects files that are to be included
24652 into the DLL. This is done by using the standard @emph{gnatmake} tool.
24654 @item 
24655 Building the DLL.
24656 To build the DLL you must use @emph{gcc}'s @emph{-shared} and
24657 @emph{-shared-libgcc} options. It is quite simple to use this method:
24659 @example
24660 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
24661 @end example
24663 It is important to note that in this case all symbols found in the
24664 object files are automatically exported. It is possible to restrict
24665 the set of symbols to export by passing to @emph{gcc} a definition
24666 file (see @ref{1f8,,The Definition File}).
24667 For example:
24669 @example
24670 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
24671 @end example
24673 If you use a definition file you must export the elaboration procedures
24674 for every package that required one. Elaboration procedures are named
24675 using the package name followed by "_E".
24677 @item 
24678 Preparing DLL to be used.
24679 For the DLL to be used by client programs the bodies must be hidden
24680 from it and the .ali set with read-only attribute. This is very important
24681 otherwise GNAT will recompile all packages and will not actually use
24682 the code in the DLL. For example:
24684 @example
24685 $ mkdir apilib
24686 $ copy *.ads *.ali api.dll apilib
24687 $ attrib +R apilib\\*.ali
24688 @end example
24689 @end itemize
24691 At this point it is possible to use the DLL by directly linking
24692 against it. Note that you must use the GNAT shared runtime when using
24693 GNAT shared libraries. This is achieved by using @emph{-shared} binder's
24694 option.
24696 @quotation
24698 @example
24699 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
24700 @end example
24701 @end quotation
24703 @node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
24704 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{205}@anchor{gnat_ugn/platform_specific_information id26}@anchor{206}
24705 @subsubsection Building DLLs with gnatdll
24708 @geindex DLLs
24709 @geindex building
24711 Note that it is preferred to use GNAT Project files
24712 (@ref{1eb,,Building DLLs with GNAT Project files}) or the built-in GNAT
24713 DLL support (@ref{203,,Building DLLs with GNAT}) or to build DLLs.
24715 This section explains how to build DLLs containing Ada code using
24716 @cite{gnatdll}. These DLLs will be referred to as Ada DLLs in the
24717 remainder of this section.
24719 The steps required to build an Ada DLL that is to be used by Ada as well as
24720 non-Ada applications are as follows:
24723 @itemize *
24725 @item 
24726 You need to mark each Ada @emph{entity} exported by the DLL with a @cite{C} or
24727 @cite{Stdcall} calling convention to avoid any Ada name mangling for the
24728 entities exported by the DLL
24729 (see @ref{207,,Exporting Ada Entities}). You can
24730 skip this step if you plan to use the Ada DLL only from Ada applications.
24732 @item 
24733 Your Ada code must export an initialization routine which calls the routine
24734 @cite{adainit} generated by @emph{gnatbind} to perform the elaboration of
24735 the Ada code in the DLL (@ref{208,,Ada DLLs and Elaboration}). The initialization
24736 routine exported by the Ada DLL must be invoked by the clients of the DLL
24737 to initialize the DLL.
24739 @item 
24740 When useful, the DLL should also export a finalization routine which calls
24741 routine @cite{adafinal} generated by @emph{gnatbind} to perform the
24742 finalization of the Ada code in the DLL (@ref{209,,Ada DLLs and Finalization}).
24743 The finalization routine exported by the Ada DLL must be invoked by the
24744 clients of the DLL when the DLL services are no further needed.
24746 @item 
24747 You must provide a spec for the services exported by the Ada DLL in each
24748 of the programming languages to which you plan to make the DLL available.
24750 @item 
24751 You must provide a definition file listing the exported entities
24752 (@ref{1f8,,The Definition File}).
24754 @item 
24755 Finally you must use @cite{gnatdll} to produce the DLL and the import
24756 library (@ref{200,,Using gnatdll}).
24757 @end itemize
24759 Note that a relocatable DLL stripped using the @cite{strip}
24760 binutils tool will not be relocatable anymore. To build a DLL without
24761 debug information pass @cite{-largs -s} to @cite{gnatdll}. This
24762 restriction does not apply to a DLL built using a Library Project.
24763 See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24764 chapter of the @emph{GPRbuild User's Guide}.
24766 @c Limitations_When_Using_Ada_DLLs_from Ada:
24768 @menu
24769 * Limitations When Using Ada DLLs from Ada:: 
24770 * Exporting Ada Entities:: 
24771 * Ada DLLs and Elaboration:: 
24773 @end menu
24775 @node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
24776 @anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{20a}
24777 @subsubsection Limitations When Using Ada DLLs from Ada
24780 When using Ada DLLs from Ada applications there is a limitation users
24781 should be aware of. Because on Windows the GNAT run time is not in a DLL of
24782 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
24783 each Ada DLL includes the services of the GNAT run time that are necessary
24784 to the Ada code inside the DLL. As a result, when an Ada program uses an
24785 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
24786 one in the main program.
24788 It is therefore not possible to exchange GNAT run-time objects between the
24789 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
24790 handles (e.g., @cite{Text_IO.File_Type}), tasks types, protected objects
24791 types, etc.
24793 It is completely safe to exchange plain elementary, array or record types,
24794 Windows object handles, etc.
24796 @node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
24797 @anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{207}@anchor{gnat_ugn/platform_specific_information id27}@anchor{20b}
24798 @subsubsection Exporting Ada Entities
24801 @geindex Export table
24803 Building a DLL is a way to encapsulate a set of services usable from any
24804 application. As a result, the Ada entities exported by a DLL should be
24805 exported with the @cite{C} or @cite{Stdcall} calling conventions to avoid
24806 any Ada name mangling. As an example here is an Ada package
24807 @cite{API}, spec and body, exporting two procedures, a function, and a
24808 variable:
24810 @quotation
24812 @example
24813 with Interfaces.C; use Interfaces;
24814 package API is
24815    Count : C.int := 0;
24816    function Factorial (Val : C.int) return C.int;
24818    procedure Initialize_API;
24819    procedure Finalize_API;
24820    --  Initialization & Finalization routines. More in the next section.
24821 private
24822    pragma Export (C, Initialize_API);
24823    pragma Export (C, Finalize_API);
24824    pragma Export (C, Count);
24825    pragma Export (C, Factorial);
24826 end API;
24827 @end example
24829 @example
24830 package body API is
24831    function Factorial (Val : C.int) return C.int is
24832       Fact : C.int := 1;
24833    begin
24834       Count := Count + 1;
24835       for K in 1 .. Val loop
24836          Fact := Fact * K;
24837       end loop;
24838       return Fact;
24839    end Factorial;
24841    procedure Initialize_API is
24842       procedure Adainit;
24843       pragma Import (C, Adainit);
24844    begin
24845       Adainit;
24846    end Initialize_API;
24848    procedure Finalize_API is
24849       procedure Adafinal;
24850       pragma Import (C, Adafinal);
24851    begin
24852       Adafinal;
24853    end Finalize_API;
24854 end API;
24855 @end example
24856 @end quotation
24858 If the Ada DLL you are building will only be used by Ada applications
24859 you do not have to export Ada entities with a @cite{C} or @cite{Stdcall}
24860 convention. As an example, the previous package could be written as
24861 follows:
24863 @quotation
24865 @example
24866 package API is
24867    Count : Integer := 0;
24868    function Factorial (Val : Integer) return Integer;
24870    procedure Initialize_API;
24871    procedure Finalize_API;
24872    --  Initialization and Finalization routines.
24873 end API;
24874 @end example
24876 @example
24877 package body API is
24878    function Factorial (Val : Integer) return Integer is
24879       Fact : Integer := 1;
24880    begin
24881       Count := Count + 1;
24882       for K in 1 .. Val loop
24883          Fact := Fact * K;
24884       end loop;
24885       return Fact;
24886    end Factorial;
24888    ...
24889    --  The remainder of this package body is unchanged.
24890 end API;
24891 @end example
24892 @end quotation
24894 Note that if you do not export the Ada entities with a @cite{C} or
24895 @cite{Stdcall} convention you will have to provide the mangled Ada names
24896 in the definition file of the Ada DLL
24897 (@ref{20c,,Creating the Definition File}).
24899 @node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
24900 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{208}@anchor{gnat_ugn/platform_specific_information id28}@anchor{20d}
24901 @subsubsection Ada DLLs and Elaboration
24904 @geindex DLLs and elaboration
24906 The DLL that you are building contains your Ada code as well as all the
24907 routines in the Ada library that are needed by it. The first thing a
24908 user of your DLL must do is elaborate the Ada code
24909 (@ref{f,,Elaboration Order Handling in GNAT}).
24911 To achieve this you must export an initialization routine
24912 (@cite{Initialize_API} in the previous example), which must be invoked
24913 before using any of the DLL services. This elaboration routine must call
24914 the Ada elaboration routine @cite{adainit} generated by the GNAT binder
24915 (@ref{b4,,Binding with Non-Ada Main Programs}). See the body of
24916 @cite{Initialize_Api} for an example. Note that the GNAT binder is
24917 automatically invoked during the DLL build process by the @cite{gnatdll}
24918 tool (@ref{200,,Using gnatdll}).
24920 When a DLL is loaded, Windows systematically invokes a routine called
24921 @cite{DllMain}. It would therefore be possible to call @cite{adainit}
24922 directly from @cite{DllMain} without having to provide an explicit
24923 initialization routine. Unfortunately, it is not possible to call
24924 @cite{adainit} from the @cite{DllMain} if your program has library level
24925 tasks because access to the @cite{DllMain} entry point is serialized by
24926 the system (that is, only a single thread can execute 'through' it at a
24927 time), which means that the GNAT run time will deadlock waiting for the
24928 newly created task to complete its initialization.
24930 @node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
24931 @anchor{gnat_ugn/platform_specific_information id29}@anchor{20e}@anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{209}
24932 @subsubsection Ada DLLs and Finalization
24935 @geindex DLLs and finalization
24937 When the services of an Ada DLL are no longer needed, the client code should
24938 invoke the DLL finalization routine, if available. The DLL finalization
24939 routine is in charge of releasing all resources acquired by the DLL. In the
24940 case of the Ada code contained in the DLL, this is achieved by calling
24941 routine @cite{adafinal} generated by the GNAT binder
24942 (@ref{b4,,Binding with Non-Ada Main Programs}).
24943 See the body of @cite{Finalize_Api} for an
24944 example. As already pointed out the GNAT binder is automatically invoked
24945 during the DLL build process by the @cite{gnatdll} tool
24946 (@ref{200,,Using gnatdll}).
24948 @node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
24949 @anchor{gnat_ugn/platform_specific_information id30}@anchor{20f}@anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{210}
24950 @subsubsection Creating a Spec for Ada DLLs
24953 To use the services exported by the Ada DLL from another programming
24954 language (e.g., C), you have to translate the specs of the exported Ada
24955 entities in that language. For instance in the case of @cite{API.dll},
24956 the corresponding C header file could look like:
24958 @quotation
24960 @example
24961 extern int *_imp__count;
24962 #define count (*_imp__count)
24963 int factorial (int);
24964 @end example
24965 @end quotation
24967 It is important to understand that when building an Ada DLL to be used by
24968 other Ada applications, you need two different specs for the packages
24969 contained in the DLL: one for building the DLL and the other for using
24970 the DLL. This is because the @cite{DLL} calling convention is needed to
24971 use a variable defined in a DLL, but when building the DLL, the variable
24972 must have either the @cite{Ada} or @cite{C} calling convention. As an
24973 example consider a DLL comprising the following package @cite{API}:
24975 @quotation
24977 @example
24978 package API is
24979    Count : Integer := 0;
24980    ...
24981    --  Remainder of the package omitted.
24982 end API;
24983 @end example
24984 @end quotation
24986 After producing a DLL containing package @cite{API}, the spec that
24987 must be used to import @cite{API.Count} from Ada code outside of the
24988 DLL is:
24990 @quotation
24992 @example
24993 package API is
24994    Count : Integer;
24995    pragma Import (DLL, Count);
24996 end API;
24997 @end example
24998 @end quotation
25000 @menu
25001 * Creating the Definition File:: 
25002 * Using gnatdll:: 
25004 @end menu
25006 @node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
25007 @anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{20c}@anchor{gnat_ugn/platform_specific_information id31}@anchor{211}
25008 @subsubsection Creating the Definition File
25011 The definition file is the last file needed to build the DLL. It lists
25012 the exported symbols. As an example, the definition file for a DLL
25013 containing only package @cite{API} (where all the entities are exported
25014 with a @cite{C} calling convention) is:
25016 @quotation
25018 @example
25019 EXPORTS
25020     count
25021     factorial
25022     finalize_api
25023     initialize_api
25024 @end example
25025 @end quotation
25027 If the @cite{C} calling convention is missing from package @cite{API},
25028 then the definition file contains the mangled Ada names of the above
25029 entities, which in this case are:
25031 @quotation
25033 @example
25034 EXPORTS
25035     api__count
25036     api__factorial
25037     api__finalize_api
25038     api__initialize_api
25039 @end example
25040 @end quotation
25042 @node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
25043 @anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{200}@anchor{gnat_ugn/platform_specific_information id32}@anchor{212}
25044 @subsubsection Using @cite{gnatdll}
25047 @geindex gnatdll
25049 @cite{gnatdll} is a tool to automate the DLL build process once all the Ada
25050 and non-Ada sources that make up your DLL have been compiled.
25051 @cite{gnatdll} is actually in charge of two distinct tasks: build the
25052 static import library for the DLL and the actual DLL. The form of the
25053 @cite{gnatdll} command is
25055 @quotation
25057 @example
25058 $ gnatdll [`switches`] `list-of-files` [-largs `opts`]
25059 @end example
25060 @end quotation
25062 where @cite{list-of-files} is a list of ALI and object files. The object
25063 file list must be the exact list of objects corresponding to the non-Ada
25064 sources whose services are to be included in the DLL. The ALI file list
25065 must be the exact list of ALI files for the corresponding Ada sources
25066 whose services are to be included in the DLL. If @cite{list-of-files} is
25067 missing, only the static import library is generated.
25069 You may specify any of the following switches to @cite{gnatdll}:
25071 @quotation
25073 @geindex -a (gnatdll)
25074 @end quotation
25077 @table @asis
25079 @item @code{-a[@emph{address}]}
25081 Build a non-relocatable DLL at @cite{address}. If @cite{address} is not
25082 specified the default address @cite{0x11000000} will be used. By default,
25083 when this switch is missing, @cite{gnatdll} builds relocatable DLL. We
25084 advise the reader to build relocatable DLL.
25086 @geindex -b (gnatdll)
25088 @item @code{-b @emph{address}}
25090 Set the relocatable DLL base address. By default the address is
25091 @cite{0x11000000}.
25093 @geindex -bargs (gnatdll)
25095 @item @code{-bargs @emph{opts}}
25097 Binder options. Pass @cite{opts} to the binder.
25099 @geindex -d (gnatdll)
25101 @item @code{-d @emph{dllfile}}
25103 @cite{dllfile} is the name of the DLL. This switch must be present for
25104 @cite{gnatdll} to do anything. The name of the generated import library is
25105 obtained algorithmically from @cite{dllfile} as shown in the following
25106 example: if @cite{dllfile} is @cite{xyz.dll}, the import library name is
25107 @cite{libxyz.dll.a}. The name of the definition file to use (if not specified
25108 by option @emph{-e}) is obtained algorithmically from @cite{dllfile}
25109 as shown in the following example:
25110 if @cite{dllfile} is @cite{xyz.dll}, the definition
25111 file used is @cite{xyz.def}.
25113 @geindex -e (gnatdll)
25115 @item @code{-e @emph{deffile}}
25117 @cite{deffile} is the name of the definition file.
25119 @geindex -g (gnatdll)
25121 @item @code{-g}
25123 Generate debugging information. This information is stored in the object
25124 file and copied from there to the final DLL file by the linker,
25125 where it can be read by the debugger. You must use the
25126 @emph{-g} switch if you plan on using the debugger or the symbolic
25127 stack traceback.
25129 @geindex -h (gnatdll)
25131 @item @code{-h}
25133 Help mode. Displays @cite{gnatdll} switch usage information.
25135 @geindex -I (gnatdll)
25137 @item @code{-I@emph{dir}}
25139 Direct @cite{gnatdll} to search the @cite{dir} directory for source and
25140 object files needed to build the DLL.
25141 (@ref{89,,Search Paths and the Run-Time Library (RTL)}).
25143 @geindex -k (gnatdll)
25145 @item @code{-k}
25147 Removes the @code{@@@emph{nn}} suffix from the import library's exported
25148 names, but keeps them for the link names. You must specify this
25149 option if you want to use a @cite{Stdcall} function in a DLL for which
25150 the @code{@@@emph{nn}} suffix has been removed. This is the case for most
25151 of the Windows NT DLL for example. This option has no effect when
25152 @emph{-n} option is specified.
25154 @geindex -l (gnatdll)
25156 @item @code{-l @emph{file}}
25158 The list of ALI and object files used to build the DLL are listed in
25159 @cite{file}, instead of being given in the command line. Each line in
25160 @cite{file} contains the name of an ALI or object file.
25162 @geindex -n (gnatdll)
25164 @item @code{-n}
25166 No Import. Do not create the import library.
25168 @geindex -q (gnatdll)
25170 @item @code{-q}
25172 Quiet mode. Do not display unnecessary messages.
25174 @geindex -v (gnatdll)
25176 @item @code{-v}
25178 Verbose mode. Display extra information.
25180 @geindex -largs (gnatdll)
25182 @item @code{-largs @emph{opts}}
25184 Linker options. Pass @cite{opts} to the linker.
25185 @end table
25187 @subsubheading @cite{gnatdll} Example
25190 As an example the command to build a relocatable DLL from @code{api.adb}
25191 once @code{api.adb} has been compiled and @code{api.def} created is
25193 @quotation
25195 @example
25196 $ gnatdll -d api.dll api.ali
25197 @end example
25198 @end quotation
25200 The above command creates two files: @code{libapi.dll.a} (the import
25201 library) and @code{api.dll} (the actual DLL). If you want to create
25202 only the DLL, just type:
25204 @quotation
25206 @example
25207 $ gnatdll -d api.dll -n api.ali
25208 @end example
25209 @end quotation
25211 Alternatively if you want to create just the import library, type:
25213 @quotation
25215 @example
25216 $ gnatdll -d api.dll
25217 @end example
25218 @end quotation
25220 @subsubheading @cite{gnatdll} behind the Scenes
25223 This section details the steps involved in creating a DLL. @cite{gnatdll}
25224 does these steps for you. Unless you are interested in understanding what
25225 goes on behind the scenes, you should skip this section.
25227 We use the previous example of a DLL containing the Ada package @cite{API},
25228 to illustrate the steps necessary to build a DLL. The starting point is a
25229 set of objects that will make up the DLL and the corresponding ALI
25230 files. In the case of this example this means that @code{api.o} and
25231 @code{api.ali} are available. To build a relocatable DLL, @cite{gnatdll} does
25232 the following:
25235 @itemize *
25237 @item 
25238 @cite{gnatdll} builds the base file (@code{api.base}). A base file gives
25239 the information necessary to generate relocation information for the
25240 DLL.
25242 @example
25243 $ gnatbind -n api
25244 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
25245 @end example
25247 In addition to the base file, the @emph{gnatlink} command generates an
25248 output file @code{api.jnk} which can be discarded. The @emph{-mdll} switch
25249 asks @emph{gnatlink} to generate the routines @cite{DllMain} and
25250 @cite{DllMainCRTStartup} that are called by the Windows loader when the DLL
25251 is loaded into memory.
25253 @item 
25254 @cite{gnatdll} uses @cite{dlltool} (see @ref{213,,Using dlltool}) to build the
25255 export table (@code{api.exp}). The export table contains the relocation
25256 information in a form which can be used during the final link to ensure
25257 that the Windows loader is able to place the DLL anywhere in memory.
25259 @example
25260 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
25261           --output-exp api.exp
25262 @end example
25264 @item 
25265 @cite{gnatdll} builds the base file using the new export table. Note that
25266 @emph{gnatbind} must be called once again since the binder generated file
25267 has been deleted during the previous call to @emph{gnatlink}.
25269 @example
25270 $ gnatbind -n api
25271 $ gnatlink api -o api.jnk api.exp -mdll
25272       -Wl,--base-file,api.base
25273 @end example
25275 @item 
25276 @cite{gnatdll} builds the new export table using the new base file and
25277 generates the DLL import library @code{libAPI.dll.a}.
25279 @example
25280 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
25281           --output-exp api.exp --output-lib libAPI.a
25282 @end example
25284 @item 
25285 Finally @cite{gnatdll} builds the relocatable DLL using the final export
25286 table.
25288 @example
25289 $ gnatbind -n api
25290 $ gnatlink api api.exp -o api.dll -mdll
25291 @end example
25292 @end itemize
25293 @anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{213}
25294 @subsubheading Using @cite{dlltool}
25297 @cite{dlltool} is the low-level tool used by @cite{gnatdll} to build
25298 DLLs and static import libraries. This section summarizes the most
25299 common @cite{dlltool} switches. The form of the @cite{dlltool} command
25302 @quotation
25304 @example
25305 $ dlltool [`switches`]
25306 @end example
25307 @end quotation
25309 @cite{dlltool} switches include:
25311 @geindex --base-file (dlltool)
25314 @table @asis
25316 @item @code{--base-file @emph{basefile}}
25318 Read the base file @cite{basefile} generated by the linker. This switch
25319 is used to create a relocatable DLL.
25320 @end table
25322 @geindex --def (dlltool)
25325 @table @asis
25327 @item @code{--def @emph{deffile}}
25329 Read the definition file.
25330 @end table
25332 @geindex --dllname (dlltool)
25335 @table @asis
25337 @item @code{--dllname @emph{name}}
25339 Gives the name of the DLL. This switch is used to embed the name of the
25340 DLL in the static import library generated by @cite{dlltool} with switch
25341 @emph{--output-lib}.
25342 @end table
25344 @geindex -k (dlltool)
25347 @table @asis
25349 @item @code{-k}
25351 Kill @code{@@@emph{nn}} from exported names
25352 (@ref{1ec,,Windows Calling Conventions}
25353 for a discussion about @cite{Stdcall}-style symbols.
25354 @end table
25356 @geindex --help (dlltool)
25359 @table @asis
25361 @item @code{--help}
25363 Prints the @cite{dlltool} switches with a concise description.
25364 @end table
25366 @geindex --output-exp (dlltool)
25369 @table @asis
25371 @item @code{--output-exp @emph{exportfile}}
25373 Generate an export file @cite{exportfile}. The export file contains the
25374 export table (list of symbols in the DLL) and is used to create the DLL.
25375 @end table
25377 @geindex --output-lib (dlltool)
25380 @table @asis
25382 @item @code{--output-lib @emph{libfile}}
25384 Generate a static import library @cite{libfile}.
25385 @end table
25387 @geindex -v (dlltool)
25390 @table @asis
25392 @item @code{-v}
25394 Verbose mode.
25395 @end table
25397 @geindex --as (dlltool)
25400 @table @asis
25402 @item @code{--as @emph{assembler-name}}
25404 Use @cite{assembler-name} as the assembler. The default is @cite{as}.
25405 @end table
25407 @node GNAT and Windows Resources,Using GNAT DLLs from Microsoft Visual Studio Applications,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
25408 @anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{214}@anchor{gnat_ugn/platform_specific_information id33}@anchor{215}
25409 @subsubsection GNAT and Windows Resources
25412 @geindex Resources
25413 @geindex windows
25415 Resources are an easy way to add Windows specific objects to your
25416 application. The objects that can be added as resources include:
25419 @itemize *
25421 @item 
25422 menus
25424 @item 
25425 accelerators
25427 @item 
25428 dialog boxes
25430 @item 
25431 string tables
25433 @item 
25434 bitmaps
25436 @item 
25437 cursors
25439 @item 
25440 icons
25442 @item 
25443 fonts
25445 @item 
25446 version information
25447 @end itemize
25449 For example, a version information resource can be defined as follow and
25450 embedded into an executable or DLL:
25452 A version information resource can be used to embed information into an
25453 executable or a DLL. These information can be viewed using the file properties
25454 from the Windows Explorer. Here is an example of a version information
25455 resource:
25457 @quotation
25459 @example
25460 1 VERSIONINFO
25461 FILEVERSION     1,0,0,0
25462 PRODUCTVERSION  1,0,0,0
25463 BEGIN
25464   BLOCK "StringFileInfo"
25465   BEGIN
25466     BLOCK "080904E4"
25467     BEGIN
25468       VALUE "CompanyName", "My Company Name"
25469       VALUE "FileDescription", "My application"
25470       VALUE "FileVersion", "1.0"
25471       VALUE "InternalName", "my_app"
25472       VALUE "LegalCopyright", "My Name"
25473       VALUE "OriginalFilename", "my_app.exe"
25474       VALUE "ProductName", "My App"
25475       VALUE "ProductVersion", "1.0"
25476     END
25477   END
25479   BLOCK "VarFileInfo"
25480   BEGIN
25481     VALUE "Translation", 0x809, 1252
25482   END
25484 @end example
25485 @end quotation
25487 The value @cite{0809} (langID) is for the U.K English language and
25488 @cite{04E4} (charsetID), which is equal to @cite{1252} decimal, for
25489 multilingual.
25491 This section explains how to build, compile and use resources. Note that this
25492 section does not cover all resource objects, for a complete description see
25493 the corresponding Microsoft documentation.
25495 @menu
25496 * Building Resources:: 
25497 * Compiling Resources:: 
25498 * Using Resources:: 
25500 @end menu
25502 @node Building Resources,Compiling Resources,,GNAT and Windows Resources
25503 @anchor{gnat_ugn/platform_specific_information building-resources}@anchor{216}@anchor{gnat_ugn/platform_specific_information id34}@anchor{217}
25504 @subsubsection Building Resources
25507 @geindex Resources
25508 @geindex building
25510 A resource file is an ASCII file. By convention resource files have an
25511 @code{.rc} extension.
25512 The easiest way to build a resource file is to use Microsoft tools
25513 such as @cite{imagedit.exe} to build bitmaps, icons and cursors and
25514 @cite{dlgedit.exe} to build dialogs.
25515 It is always possible to build an @code{.rc} file yourself by writing a
25516 resource script.
25518 It is not our objective to explain how to write a resource file. A
25519 complete description of the resource script language can be found in the
25520 Microsoft documentation.
25522 @node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
25523 @anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{218}@anchor{gnat_ugn/platform_specific_information id35}@anchor{219}
25524 @subsubsection Compiling Resources
25527 @geindex rc
25529 @geindex windres
25531 @geindex Resources
25532 @geindex compiling
25534 This section describes how to build a GNAT-compatible (COFF) object file
25535 containing the resources. This is done using the Resource Compiler
25536 @cite{windres} as follows:
25538 @quotation
25540 @example
25541 $ windres -i myres.rc -o myres.o
25542 @end example
25543 @end quotation
25545 By default @cite{windres} will run @emph{gcc} to preprocess the @code{.rc}
25546 file. You can specify an alternate preprocessor (usually named
25547 @code{cpp.exe}) using the @cite{windres} @emph{--preprocessor}
25548 parameter. A list of all possible options may be obtained by entering
25549 the command @cite{windres} @emph{--help}.
25551 It is also possible to use the Microsoft resource compiler @cite{rc.exe}
25552 to produce a @code{.res} file (binary resource file). See the
25553 corresponding Microsoft documentation for further details. In this case
25554 you need to use @cite{windres} to translate the @code{.res} file to a
25555 GNAT-compatible object file as follows:
25557 @quotation
25559 @example
25560 $ windres -i myres.res -o myres.o
25561 @end example
25562 @end quotation
25564 @node Using Resources,,Compiling Resources,GNAT and Windows Resources
25565 @anchor{gnat_ugn/platform_specific_information id36}@anchor{21a}@anchor{gnat_ugn/platform_specific_information using-resources}@anchor{21b}
25566 @subsubsection Using Resources
25569 @geindex Resources
25570 @geindex using
25572 To include the resource file in your program just add the
25573 GNAT-compatible object file for the resource(s) to the linker
25574 arguments. With @emph{gnatmake} this is done by using the @emph{-largs}
25575 option:
25577 @quotation
25579 @example
25580 $ gnatmake myprog -largs myres.o
25581 @end example
25582 @end quotation
25584 @node Using GNAT DLLs from Microsoft Visual Studio Applications,Debugging a DLL,GNAT and Windows Resources,Mixed-Language Programming on Windows
25585 @anchor{gnat_ugn/platform_specific_information using-gnat-dll-from-msvs}@anchor{21c}@anchor{gnat_ugn/platform_specific_information using-gnat-dlls-from-microsoft-visual-studio-applications}@anchor{21d}
25586 @subsubsection Using GNAT DLLs from Microsoft Visual Studio Applications
25589 @geindex Microsoft Visual Studio
25590 @geindex use with GNAT DLLs
25592 This section describes a common case of mixed GNAT/Microsoft Visual Studio
25593 application development, where the main program is developed using MSVS, and
25594 is linked with a DLL developed using GNAT. Such a mixed application should
25595 be developed following the general guidelines outlined above; below is the
25596 cookbook-style sequence of steps to follow:
25599 @enumerate 
25601 @item 
25602 First develop and build the GNAT shared library using a library project
25603 (let's assume the project is @cite{mylib.gpr}, producing the library @cite{libmylib.dll}):
25604 @end enumerate
25606 @quotation
25608 @example
25609 $ gprbuild -p mylib.gpr
25610 @end example
25611 @end quotation
25614 @enumerate 2
25616 @item 
25617 Produce a .def file for the symbols you need to interface with, either by
25618 hand or automatically with possibly some manual adjustments
25619 (see @ref{1fe,,Creating Definition File Automatically}):
25620 @end enumerate
25622 @quotation
25624 @example
25625 $ dlltool libmylib.dll -z libmylib.def --export-all-symbols
25626 @end example
25627 @end quotation
25630 @enumerate 3
25632 @item 
25633 Make sure that MSVS command-line tools are accessible on the path.
25635 @item 
25636 Create the Microsoft-style import library (see @ref{201,,MSVS-Style Import Library}):
25637 @end enumerate
25639 @quotation
25641 @example
25642 $ lib -machine:IX86 -def:libmylib.def -out:libmylib.lib
25643 @end example
25644 @end quotation
25646 If you are using a 64-bit toolchain, the above becomes...
25648 @quotation
25650 @example
25651 $ lib -machine:X64 -def:libmylib.def -out:libmylib.lib
25652 @end example
25653 @end quotation
25656 @enumerate 5
25658 @item 
25659 Build the C main
25660 @end enumerate
25662 @quotation
25664 @example
25665 $ cl /O2 /MD main.c libmylib.lib
25666 @end example
25667 @end quotation
25670 @enumerate 6
25672 @item 
25673 Before running the executable, make sure you have set the PATH to the DLL,
25674 or copy the DLL into into the directory containing the .exe.
25675 @end enumerate
25677 @node Debugging a DLL,Setting Stack Size from gnatlink,Using GNAT DLLs from Microsoft Visual Studio Applications,Mixed-Language Programming on Windows
25678 @anchor{gnat_ugn/platform_specific_information id37}@anchor{21e}@anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{21f}
25679 @subsubsection Debugging a DLL
25682 @geindex DLL debugging
25684 Debugging a DLL is similar to debugging a standard program. But
25685 we have to deal with two different executable parts: the DLL and the
25686 program that uses it. We have the following four possibilities:
25689 @itemize *
25691 @item 
25692 The program and the DLL are built with @cite{GCC/GNAT}.
25694 @item 
25695 The program is built with foreign tools and the DLL is built with
25696 @cite{GCC/GNAT}.
25698 @item 
25699 The program is built with @cite{GCC/GNAT} and the DLL is built with
25700 foreign tools.
25701 @end itemize
25703 In this section we address only cases one and two above.
25704 There is no point in trying to debug
25705 a DLL with @cite{GNU/GDB}, if there is no GDB-compatible debugging
25706 information in it. To do so you must use a debugger compatible with the
25707 tools suite used to build the DLL.
25709 @menu
25710 * Program and DLL Both Built with GCC/GNAT:: 
25711 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
25713 @end menu
25715 @node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
25716 @anchor{gnat_ugn/platform_specific_information program-and-dll-both-built-with-gcc-gnat}@anchor{220}@anchor{gnat_ugn/platform_specific_information id38}@anchor{221}
25717 @subsubsection Program and DLL Both Built with GCC/GNAT
25720 This is the simplest case. Both the DLL and the program have @cite{GDB}
25721 compatible debugging information. It is then possible to break anywhere in
25722 the process. Let's suppose here that the main procedure is named
25723 @cite{ada_main} and that in the DLL there is an entry point named
25724 @cite{ada_dll}.
25726 The DLL (@ref{1f7,,Introduction to Dynamic Link Libraries (DLLs)}) and
25727 program must have been built with the debugging information (see GNAT -g
25728 switch). Here are the step-by-step instructions for debugging it:
25731 @itemize *
25733 @item 
25734 Launch @cite{GDB} on the main program.
25736 @example
25737 $ gdb -nw ada_main
25738 @end example
25740 @item 
25741 Start the program and stop at the beginning of the main procedure
25743 @example
25744 (gdb) start
25745 @end example
25747 This step is required to be able to set a breakpoint inside the DLL. As long
25748 as the program is not run, the DLL is not loaded. This has the
25749 consequence that the DLL debugging information is also not loaded, so it is not
25750 possible to set a breakpoint in the DLL.
25752 @item 
25753 Set a breakpoint inside the DLL
25755 @example
25756 (gdb) break ada_dll
25757 (gdb) cont
25758 @end example
25759 @end itemize
25761 At this stage a breakpoint is set inside the DLL. From there on
25762 you can use the standard approach to debug the whole program
25763 (@ref{24,,Running and Debugging Ada Programs}).
25765 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
25766 @anchor{gnat_ugn/platform_specific_information program-built-with-foreign-tools-and-dll-built-with-gcc-gnat}@anchor{222}@anchor{gnat_ugn/platform_specific_information id39}@anchor{223}
25767 @subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
25770 In this case things are slightly more complex because it is not possible to
25771 start the main program and then break at the beginning to load the DLL and the
25772 associated DLL debugging information. It is not possible to break at the
25773 beginning of the program because there is no @cite{GDB} debugging information,
25774 and therefore there is no direct way of getting initial control. This
25775 section addresses this issue by describing some methods that can be used
25776 to break somewhere in the DLL to debug it.
25778 First suppose that the main procedure is named @cite{main} (this is for
25779 example some C code built with Microsoft Visual C) and that there is a
25780 DLL named @cite{test.dll} containing an Ada entry point named
25781 @cite{ada_dll}.
25783 The DLL (see @ref{1f7,,Introduction to Dynamic Link Libraries (DLLs)}) must have
25784 been built with debugging information (see GNAT @cite{-g} option).
25786 @subsubheading Debugging the DLL Directly
25790 @itemize *
25792 @item 
25793 Find out the executable starting address
25795 @example
25796 $ objdump --file-header main.exe
25797 @end example
25799 The starting address is reported on the last line. For example:
25801 @example
25802 main.exe:     file format pei-i386
25803 architecture: i386, flags 0x0000010a:
25804 EXEC_P, HAS_DEBUG, D_PAGED
25805 start address 0x00401010
25806 @end example
25808 @item 
25809 Launch the debugger on the executable.
25811 @example
25812 $ gdb main.exe
25813 @end example
25815 @item 
25816 Set a breakpoint at the starting address, and launch the program.
25818 @example
25819 $ (gdb) break *0x00401010
25820 $ (gdb) run
25821 @end example
25823 The program will stop at the given address.
25825 @item 
25826 Set a breakpoint on a DLL subroutine.
25828 @example
25829 (gdb) break ada_dll.adb:45
25830 @end example
25832 Or if you want to break using a symbol on the DLL, you need first to
25833 select the Ada language (language used by the DLL).
25835 @example
25836 (gdb) set language ada
25837 (gdb) break ada_dll
25838 @end example
25840 @item 
25841 Continue the program.
25843 @example
25844 (gdb) cont
25845 @end example
25847 This will run the program until it reaches the breakpoint that has been
25848 set. From that point you can use the standard way to debug a program
25849 as described in (@ref{24,,Running and Debugging Ada Programs}).
25850 @end itemize
25852 It is also possible to debug the DLL by attaching to a running process.
25854 @subsubheading Attaching to a Running Process
25857 @geindex DLL debugging
25858 @geindex attach to process
25860 With @cite{GDB} it is always possible to debug a running process by
25861 attaching to it. It is possible to debug a DLL this way. The limitation
25862 of this approach is that the DLL must run long enough to perform the
25863 attach operation. It may be useful for instance to insert a time wasting
25864 loop in the code of the DLL to meet this criterion.
25867 @itemize *
25869 @item 
25870 Launch the main program @code{main.exe}.
25872 @example
25873 $ main
25874 @end example
25876 @item 
25877 Use the Windows @emph{Task Manager} to find the process ID. Let's say
25878 that the process PID for @code{main.exe} is 208.
25880 @item 
25881 Launch gdb.
25883 @example
25884 $ gdb
25885 @end example
25887 @item 
25888 Attach to the running process to be debugged.
25890 @example
25891 (gdb) attach 208
25892 @end example
25894 @item 
25895 Load the process debugging information.
25897 @example
25898 (gdb) symbol-file main.exe
25899 @end example
25901 @item 
25902 Break somewhere in the DLL.
25904 @example
25905 (gdb) break ada_dll
25906 @end example
25908 @item 
25909 Continue process execution.
25911 @example
25912 (gdb) cont
25913 @end example
25914 @end itemize
25916 This last step will resume the process execution, and stop at
25917 the breakpoint we have set. From there you can use the standard
25918 approach to debug a program as described in
25919 @ref{24,,Running and Debugging Ada Programs}.
25921 @node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
25922 @anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{136}@anchor{gnat_ugn/platform_specific_information id40}@anchor{224}
25923 @subsubsection Setting Stack Size from @emph{gnatlink}
25926 It is possible to specify the program stack size at link time. On modern
25927 versions of Windows, starting with XP, this is mostly useful to set the size of
25928 the main stack (environment task). The other task stacks are set with pragma
25929 Storage_Size or with the @emph{gnatbind -d} command.
25931 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
25932 reserve size of individual tasks, the link-time stack size applies to all
25933 tasks, and pragma Storage_Size has no effect.
25934 In particular, Stack Overflow checks are made against this
25935 link-time specified size.
25937 This setting can be done with @emph{gnatlink} using either of the following:
25940 @itemize *
25942 @item 
25943 @emph{-Xlinker} linker option
25945 @example
25946 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
25947 @end example
25949 This sets the stack reserve size to 0x10000 bytes and the stack commit
25950 size to 0x1000 bytes.
25952 @item 
25953 @emph{-Wl} linker option
25955 @example
25956 $ gnatlink hello -Wl,--stack=0x1000000
25957 @end example
25959 This sets the stack reserve size to 0x1000000 bytes. Note that with
25960 @emph{-Wl} option it is not possible to set the stack commit size
25961 because the comma is a separator for this option.
25962 @end itemize
25964 @node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
25965 @anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{137}@anchor{gnat_ugn/platform_specific_information id41}@anchor{225}
25966 @subsubsection Setting Heap Size from @emph{gnatlink}
25969 Under Windows systems, it is possible to specify the program heap size from
25970 @emph{gnatlink} using either of the following:
25973 @itemize *
25975 @item 
25976 @emph{-Xlinker} linker option
25978 @example
25979 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
25980 @end example
25982 This sets the heap reserve size to 0x10000 bytes and the heap commit
25983 size to 0x1000 bytes.
25985 @item 
25986 @emph{-Wl} linker option
25988 @example
25989 $ gnatlink hello -Wl,--heap=0x1000000
25990 @end example
25992 This sets the heap reserve size to 0x1000000 bytes. Note that with
25993 @emph{-Wl} option it is not possible to set the heap commit size
25994 because the comma is a separator for this option.
25995 @end itemize
25997 @node Windows Specific Add-Ons,,Mixed-Language Programming on Windows,Microsoft Windows Topics
25998 @anchor{gnat_ugn/platform_specific_information windows-specific-add-ons}@anchor{226}@anchor{gnat_ugn/platform_specific_information win32-specific-addons}@anchor{227}
25999 @subsection Windows Specific Add-Ons
26002 This section describes the Windows specific add-ons.
26004 @menu
26005 * Win32Ada:: 
26006 * wPOSIX:: 
26008 @end menu
26010 @node Win32Ada,wPOSIX,,Windows Specific Add-Ons
26011 @anchor{gnat_ugn/platform_specific_information win32ada}@anchor{228}@anchor{gnat_ugn/platform_specific_information id42}@anchor{229}
26012 @subsubsection Win32Ada
26015 Win32Ada is a binding for the Microsoft Win32 API. This binding can be
26016 easily installed from the provided installer. To use the Win32Ada
26017 binding you need to use a project file, and adding a single with_clause
26018 will give you full access to the Win32Ada binding sources and ensure
26019 that the proper libraries are passed to the linker.
26021 @quotation
26023 @example
26024 with "win32ada";
26025 project P is
26026    for Sources use ...;
26027 end P;
26028 @end example
26029 @end quotation
26031 To build the application you just need to call gprbuild for the
26032 application's project, here p.gpr:
26034 @quotation
26036 @example
26037 gprbuild p.gpr
26038 @end example
26039 @end quotation
26041 @node wPOSIX,,Win32Ada,Windows Specific Add-Ons
26042 @anchor{gnat_ugn/platform_specific_information id43}@anchor{22a}@anchor{gnat_ugn/platform_specific_information wposix}@anchor{22b}
26043 @subsubsection wPOSIX
26046 wPOSIX is a minimal POSIX binding whose goal is to help with building
26047 cross-platforms applications. This binding is not complete though, as
26048 the Win32 API does not provide the necessary support for all POSIX APIs.
26050 To use the wPOSIX binding you need to use a project file, and adding
26051 a single with_clause will give you full access to the wPOSIX binding
26052 sources and ensure that the proper libraries are passed to the linker.
26054 @quotation
26056 @example
26057 with "wposix";
26058 project P is
26059    for Sources use ...;
26060 end P;
26061 @end example
26062 @end quotation
26064 To build the application you just need to call gprbuild for the
26065 application's project, here p.gpr:
26067 @quotation
26069 @example
26070 gprbuild p.gpr
26071 @end example
26072 @end quotation
26074 @node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
26075 @anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{2d}@anchor{gnat_ugn/platform_specific_information id44}@anchor{22c}
26076 @section Mac OS Topics
26079 @geindex OS X
26081 This section describes topics that are specific to Apple's OS X
26082 platform.
26084 @menu
26085 * Codesigning the Debugger:: 
26087 @end menu
26089 @node Codesigning the Debugger,,,Mac OS Topics
26090 @anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{22d}
26091 @subsection Codesigning the Debugger
26094 The Darwin Kernel requires the debugger to have special permissions
26095 before it is allowed to control other processes. These permissions
26096 are granted by codesigning the GDB executable. Without these
26097 permissions, the debugger will report error messages such as:
26099 @example
26100 Starting program: /x/y/foo
26101 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
26102 (please check gdb is codesigned - see taskgated(8))
26103 @end example
26105 Codesigning requires a certificate.  The following procedure explains
26106 how to create one:
26109 @itemize *
26111 @item 
26112 Start the Keychain Access application (in
26113 /Applications/Utilities/Keychain Access.app)
26115 @item 
26116 Select the Keychain Access -> Certificate Assistant ->
26117 Create a Certificate... menu
26119 @item 
26120 Then:
26123 @itemize *
26125 @item 
26126 Choose a name for the new certificate (this procedure will use
26127 "gdb-cert" as an example)
26129 @item 
26130 Set "Identity Type" to "Self Signed Root"
26132 @item 
26133 Set "Certificate Type" to "Code Signing"
26135 @item 
26136 Activate the "Let me override defaults" option
26137 @end itemize
26139 @item 
26140 Click several times on "Continue" until the "Specify a Location
26141 For The Certificate" screen appears, then set "Keychain" to "System"
26143 @item 
26144 Click on "Continue" until the certificate is created
26146 @item 
26147 Finally, in the view, double-click on the new certificate,
26148 and set "When using this certificate" to "Always Trust"
26150 @item 
26151 Exit the Keychain Access application and restart the computer
26152 (this is unfortunately required)
26153 @end itemize
26155 Once a certificate has been created, the debugger can be codesigned
26156 as follow. In a Terminal, run the following command:
26158 @quotation
26160 @example
26161 $ codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
26162 @end example
26163 @end quotation
26165 where "gdb-cert" should be replaced by the actual certificate
26166 name chosen above, and <gnat_install_prefix> should be replaced by
26167 the location where you installed GNAT.  Also, be sure that users are
26168 in the Unix group @code{_developer}.
26170 @node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
26171 @anchor{gnat_ugn/example_of_binder_output example-of-binder-output-file}@anchor{e}@anchor{gnat_ugn/example_of_binder_output doc}@anchor{22e}@anchor{gnat_ugn/example_of_binder_output id1}@anchor{22f}
26172 @chapter Example of Binder Output File
26175 @geindex Binder output (example)
26177 This Appendix displays the source code for the output file
26178 generated by @emph{gnatbind} for a simple 'Hello World' program.
26179 Comments have been added for clarification purposes.
26181 @example
26182 --  The package is called Ada_Main unless this name is actually used
26183 --  as a unit name in the partition, in which case some other unique
26184 --  name is used.
26186 pragma Ada_95;
26187 with System;
26188 package ada_main is
26189    pragma Warnings (Off);
26191    --  The main program saves the parameters (argument count,
26192    --  argument values, environment pointer) in global variables
26193    --  for later access by other units including
26194    --  Ada.Command_Line.
26196    gnat_argc : Integer;
26197    gnat_argv : System.Address;
26198    gnat_envp : System.Address;
26200    --  The actual variables are stored in a library routine. This
26201    --  is useful for some shared library situations, where there
26202    --  are problems if variables are not in the library.
26204    pragma Import (C, gnat_argc);
26205    pragma Import (C, gnat_argv);
26206    pragma Import (C, gnat_envp);
26208    --  The exit status is similarly an external location
26210    gnat_exit_status : Integer;
26211    pragma Import (C, gnat_exit_status);
26213    GNAT_Version : constant String :=
26214                     "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
26215    pragma Export (C, GNAT_Version, "__gnat_version");
26217    Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
26218    pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
26220    --  This is the generated adainit routine that performs
26221    --  initialization at the start of execution. In the case
26222    --  where Ada is the main program, this main program makes
26223    --  a call to adainit at program startup.
26225    procedure adainit;
26226    pragma Export (C, adainit, "adainit");
26228    --  This is the generated adafinal routine that performs
26229    --  finalization at the end of execution. In the case where
26230    --  Ada is the main program, this main program makes a call
26231    --  to adafinal at program termination.
26233    procedure adafinal;
26234    pragma Export (C, adafinal, "adafinal");
26236    --  This routine is called at the start of execution. It is
26237    --  a dummy routine that is used by the debugger to breakpoint
26238    --  at the start of execution.
26240    --  This is the actual generated main program (it would be
26241    --  suppressed if the no main program switch were used). As
26242    --  required by standard system conventions, this program has
26243    --  the external name main.
26245    function main
26246      (argc : Integer;
26247       argv : System.Address;
26248       envp : System.Address)
26249       return Integer;
26250    pragma Export (C, main, "main");
26252    --  The following set of constants give the version
26253    --  identification values for every unit in the bound
26254    --  partition. This identification is computed from all
26255    --  dependent semantic units, and corresponds to the
26256    --  string that would be returned by use of the
26257    --  Body_Version or Version attributes.
26259    --  The following Export pragmas export the version numbers
26260    --  with symbolic names ending in B (for body) or S
26261    --  (for spec) so that they can be located in a link. The
26262    --  information provided here is sufficient to track down
26263    --  the exact versions of units used in a given build.
26265    type Version_32 is mod 2 ** 32;
26266    u00001 : constant Version_32 := 16#8ad6e54a#;
26267    pragma Export (C, u00001, "helloB");
26268    u00002 : constant Version_32 := 16#fbff4c67#;
26269    pragma Export (C, u00002, "system__standard_libraryB");
26270    u00003 : constant Version_32 := 16#1ec6fd90#;
26271    pragma Export (C, u00003, "system__standard_libraryS");
26272    u00004 : constant Version_32 := 16#3ffc8e18#;
26273    pragma Export (C, u00004, "adaS");
26274    u00005 : constant Version_32 := 16#28f088c2#;
26275    pragma Export (C, u00005, "ada__text_ioB");
26276    u00006 : constant Version_32 := 16#f372c8ac#;
26277    pragma Export (C, u00006, "ada__text_ioS");
26278    u00007 : constant Version_32 := 16#2c143749#;
26279    pragma Export (C, u00007, "ada__exceptionsB");
26280    u00008 : constant Version_32 := 16#f4f0cce8#;
26281    pragma Export (C, u00008, "ada__exceptionsS");
26282    u00009 : constant Version_32 := 16#a46739c0#;
26283    pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
26284    u00010 : constant Version_32 := 16#3aac8c92#;
26285    pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
26286    u00011 : constant Version_32 := 16#1d274481#;
26287    pragma Export (C, u00011, "systemS");
26288    u00012 : constant Version_32 := 16#a207fefe#;
26289    pragma Export (C, u00012, "system__soft_linksB");
26290    u00013 : constant Version_32 := 16#467d9556#;
26291    pragma Export (C, u00013, "system__soft_linksS");
26292    u00014 : constant Version_32 := 16#b01dad17#;
26293    pragma Export (C, u00014, "system__parametersB");
26294    u00015 : constant Version_32 := 16#630d49fe#;
26295    pragma Export (C, u00015, "system__parametersS");
26296    u00016 : constant Version_32 := 16#b19b6653#;
26297    pragma Export (C, u00016, "system__secondary_stackB");
26298    u00017 : constant Version_32 := 16#b6468be8#;
26299    pragma Export (C, u00017, "system__secondary_stackS");
26300    u00018 : constant Version_32 := 16#39a03df9#;
26301    pragma Export (C, u00018, "system__storage_elementsB");
26302    u00019 : constant Version_32 := 16#30e40e85#;
26303    pragma Export (C, u00019, "system__storage_elementsS");
26304    u00020 : constant Version_32 := 16#41837d1e#;
26305    pragma Export (C, u00020, "system__stack_checkingB");
26306    u00021 : constant Version_32 := 16#93982f69#;
26307    pragma Export (C, u00021, "system__stack_checkingS");
26308    u00022 : constant Version_32 := 16#393398c1#;
26309    pragma Export (C, u00022, "system__exception_tableB");
26310    u00023 : constant Version_32 := 16#b33e2294#;
26311    pragma Export (C, u00023, "system__exception_tableS");
26312    u00024 : constant Version_32 := 16#ce4af020#;
26313    pragma Export (C, u00024, "system__exceptionsB");
26314    u00025 : constant Version_32 := 16#75442977#;
26315    pragma Export (C, u00025, "system__exceptionsS");
26316    u00026 : constant Version_32 := 16#37d758f1#;
26317    pragma Export (C, u00026, "system__exceptions__machineS");
26318    u00027 : constant Version_32 := 16#b895431d#;
26319    pragma Export (C, u00027, "system__exceptions_debugB");
26320    u00028 : constant Version_32 := 16#aec55d3f#;
26321    pragma Export (C, u00028, "system__exceptions_debugS");
26322    u00029 : constant Version_32 := 16#570325c8#;
26323    pragma Export (C, u00029, "system__img_intB");
26324    u00030 : constant Version_32 := 16#1ffca443#;
26325    pragma Export (C, u00030, "system__img_intS");
26326    u00031 : constant Version_32 := 16#b98c3e16#;
26327    pragma Export (C, u00031, "system__tracebackB");
26328    u00032 : constant Version_32 := 16#831a9d5a#;
26329    pragma Export (C, u00032, "system__tracebackS");
26330    u00033 : constant Version_32 := 16#9ed49525#;
26331    pragma Export (C, u00033, "system__traceback_entriesB");
26332    u00034 : constant Version_32 := 16#1d7cb2f1#;
26333    pragma Export (C, u00034, "system__traceback_entriesS");
26334    u00035 : constant Version_32 := 16#8c33a517#;
26335    pragma Export (C, u00035, "system__wch_conB");
26336    u00036 : constant Version_32 := 16#065a6653#;
26337    pragma Export (C, u00036, "system__wch_conS");
26338    u00037 : constant Version_32 := 16#9721e840#;
26339    pragma Export (C, u00037, "system__wch_stwB");
26340    u00038 : constant Version_32 := 16#2b4b4a52#;
26341    pragma Export (C, u00038, "system__wch_stwS");
26342    u00039 : constant Version_32 := 16#92b797cb#;
26343    pragma Export (C, u00039, "system__wch_cnvB");
26344    u00040 : constant Version_32 := 16#09eddca0#;
26345    pragma Export (C, u00040, "system__wch_cnvS");
26346    u00041 : constant Version_32 := 16#6033a23f#;
26347    pragma Export (C, u00041, "interfacesS");
26348    u00042 : constant Version_32 := 16#ece6fdb6#;
26349    pragma Export (C, u00042, "system__wch_jisB");
26350    u00043 : constant Version_32 := 16#899dc581#;
26351    pragma Export (C, u00043, "system__wch_jisS");
26352    u00044 : constant Version_32 := 16#10558b11#;
26353    pragma Export (C, u00044, "ada__streamsB");
26354    u00045 : constant Version_32 := 16#2e6701ab#;
26355    pragma Export (C, u00045, "ada__streamsS");
26356    u00046 : constant Version_32 := 16#db5c917c#;
26357    pragma Export (C, u00046, "ada__io_exceptionsS");
26358    u00047 : constant Version_32 := 16#12c8cd7d#;
26359    pragma Export (C, u00047, "ada__tagsB");
26360    u00048 : constant Version_32 := 16#ce72c228#;
26361    pragma Export (C, u00048, "ada__tagsS");
26362    u00049 : constant Version_32 := 16#c3335bfd#;
26363    pragma Export (C, u00049, "system__htableB");
26364    u00050 : constant Version_32 := 16#99e5f76b#;
26365    pragma Export (C, u00050, "system__htableS");
26366    u00051 : constant Version_32 := 16#089f5cd0#;
26367    pragma Export (C, u00051, "system__string_hashB");
26368    u00052 : constant Version_32 := 16#3bbb9c15#;
26369    pragma Export (C, u00052, "system__string_hashS");
26370    u00053 : constant Version_32 := 16#807fe041#;
26371    pragma Export (C, u00053, "system__unsigned_typesS");
26372    u00054 : constant Version_32 := 16#d27be59e#;
26373    pragma Export (C, u00054, "system__val_lluB");
26374    u00055 : constant Version_32 := 16#fa8db733#;
26375    pragma Export (C, u00055, "system__val_lluS");
26376    u00056 : constant Version_32 := 16#27b600b2#;
26377    pragma Export (C, u00056, "system__val_utilB");
26378    u00057 : constant Version_32 := 16#b187f27f#;
26379    pragma Export (C, u00057, "system__val_utilS");
26380    u00058 : constant Version_32 := 16#d1060688#;
26381    pragma Export (C, u00058, "system__case_utilB");
26382    u00059 : constant Version_32 := 16#392e2d56#;
26383    pragma Export (C, u00059, "system__case_utilS");
26384    u00060 : constant Version_32 := 16#84a27f0d#;
26385    pragma Export (C, u00060, "interfaces__c_streamsB");
26386    u00061 : constant Version_32 := 16#8bb5f2c0#;
26387    pragma Export (C, u00061, "interfaces__c_streamsS");
26388    u00062 : constant Version_32 := 16#6db6928f#;
26389    pragma Export (C, u00062, "system__crtlS");
26390    u00063 : constant Version_32 := 16#4e6a342b#;
26391    pragma Export (C, u00063, "system__file_ioB");
26392    u00064 : constant Version_32 := 16#ba56a5e4#;
26393    pragma Export (C, u00064, "system__file_ioS");
26394    u00065 : constant Version_32 := 16#b7ab275c#;
26395    pragma Export (C, u00065, "ada__finalizationB");
26396    u00066 : constant Version_32 := 16#19f764ca#;
26397    pragma Export (C, u00066, "ada__finalizationS");
26398    u00067 : constant Version_32 := 16#95817ed8#;
26399    pragma Export (C, u00067, "system__finalization_rootB");
26400    u00068 : constant Version_32 := 16#52d53711#;
26401    pragma Export (C, u00068, "system__finalization_rootS");
26402    u00069 : constant Version_32 := 16#769e25e6#;
26403    pragma Export (C, u00069, "interfaces__cB");
26404    u00070 : constant Version_32 := 16#4a38bedb#;
26405    pragma Export (C, u00070, "interfaces__cS");
26406    u00071 : constant Version_32 := 16#07e6ee66#;
26407    pragma Export (C, u00071, "system__os_libB");
26408    u00072 : constant Version_32 := 16#d7b69782#;
26409    pragma Export (C, u00072, "system__os_libS");
26410    u00073 : constant Version_32 := 16#1a817b8e#;
26411    pragma Export (C, u00073, "system__stringsB");
26412    u00074 : constant Version_32 := 16#639855e7#;
26413    pragma Export (C, u00074, "system__stringsS");
26414    u00075 : constant Version_32 := 16#e0b8de29#;
26415    pragma Export (C, u00075, "system__file_control_blockS");
26416    u00076 : constant Version_32 := 16#b5b2aca1#;
26417    pragma Export (C, u00076, "system__finalization_mastersB");
26418    u00077 : constant Version_32 := 16#69316dc1#;
26419    pragma Export (C, u00077, "system__finalization_mastersS");
26420    u00078 : constant Version_32 := 16#57a37a42#;
26421    pragma Export (C, u00078, "system__address_imageB");
26422    u00079 : constant Version_32 := 16#bccbd9bb#;
26423    pragma Export (C, u00079, "system__address_imageS");
26424    u00080 : constant Version_32 := 16#7268f812#;
26425    pragma Export (C, u00080, "system__img_boolB");
26426    u00081 : constant Version_32 := 16#e8fe356a#;
26427    pragma Export (C, u00081, "system__img_boolS");
26428    u00082 : constant Version_32 := 16#d7aac20c#;
26429    pragma Export (C, u00082, "system__ioB");
26430    u00083 : constant Version_32 := 16#8365b3ce#;
26431    pragma Export (C, u00083, "system__ioS");
26432    u00084 : constant Version_32 := 16#6d4d969a#;
26433    pragma Export (C, u00084, "system__storage_poolsB");
26434    u00085 : constant Version_32 := 16#e87cc305#;
26435    pragma Export (C, u00085, "system__storage_poolsS");
26436    u00086 : constant Version_32 := 16#e34550ca#;
26437    pragma Export (C, u00086, "system__pool_globalB");
26438    u00087 : constant Version_32 := 16#c88d2d16#;
26439    pragma Export (C, u00087, "system__pool_globalS");
26440    u00088 : constant Version_32 := 16#9d39c675#;
26441    pragma Export (C, u00088, "system__memoryB");
26442    u00089 : constant Version_32 := 16#445a22b5#;
26443    pragma Export (C, u00089, "system__memoryS");
26444    u00090 : constant Version_32 := 16#6a859064#;
26445    pragma Export (C, u00090, "system__storage_pools__subpoolsB");
26446    u00091 : constant Version_32 := 16#e3b008dc#;
26447    pragma Export (C, u00091, "system__storage_pools__subpoolsS");
26448    u00092 : constant Version_32 := 16#63f11652#;
26449    pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
26450    u00093 : constant Version_32 := 16#fe2f4b3a#;
26451    pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
26453    --  BEGIN ELABORATION ORDER
26454    --  ada%s
26455    --  interfaces%s
26456    --  system%s
26457    --  system.case_util%s
26458    --  system.case_util%b
26459    --  system.htable%s
26460    --  system.img_bool%s
26461    --  system.img_bool%b
26462    --  system.img_int%s
26463    --  system.img_int%b
26464    --  system.io%s
26465    --  system.io%b
26466    --  system.parameters%s
26467    --  system.parameters%b
26468    --  system.crtl%s
26469    --  interfaces.c_streams%s
26470    --  interfaces.c_streams%b
26471    --  system.standard_library%s
26472    --  system.exceptions_debug%s
26473    --  system.exceptions_debug%b
26474    --  system.storage_elements%s
26475    --  system.storage_elements%b
26476    --  system.stack_checking%s
26477    --  system.stack_checking%b
26478    --  system.string_hash%s
26479    --  system.string_hash%b
26480    --  system.htable%b
26481    --  system.strings%s
26482    --  system.strings%b
26483    --  system.os_lib%s
26484    --  system.traceback_entries%s
26485    --  system.traceback_entries%b
26486    --  ada.exceptions%s
26487    --  system.soft_links%s
26488    --  system.unsigned_types%s
26489    --  system.val_llu%s
26490    --  system.val_util%s
26491    --  system.val_util%b
26492    --  system.val_llu%b
26493    --  system.wch_con%s
26494    --  system.wch_con%b
26495    --  system.wch_cnv%s
26496    --  system.wch_jis%s
26497    --  system.wch_jis%b
26498    --  system.wch_cnv%b
26499    --  system.wch_stw%s
26500    --  system.wch_stw%b
26501    --  ada.exceptions.last_chance_handler%s
26502    --  ada.exceptions.last_chance_handler%b
26503    --  system.address_image%s
26504    --  system.exception_table%s
26505    --  system.exception_table%b
26506    --  ada.io_exceptions%s
26507    --  ada.tags%s
26508    --  ada.streams%s
26509    --  ada.streams%b
26510    --  interfaces.c%s
26511    --  system.exceptions%s
26512    --  system.exceptions%b
26513    --  system.exceptions.machine%s
26514    --  system.finalization_root%s
26515    --  system.finalization_root%b
26516    --  ada.finalization%s
26517    --  ada.finalization%b
26518    --  system.storage_pools%s
26519    --  system.storage_pools%b
26520    --  system.finalization_masters%s
26521    --  system.storage_pools.subpools%s
26522    --  system.storage_pools.subpools.finalization%s
26523    --  system.storage_pools.subpools.finalization%b
26524    --  system.memory%s
26525    --  system.memory%b
26526    --  system.standard_library%b
26527    --  system.pool_global%s
26528    --  system.pool_global%b
26529    --  system.file_control_block%s
26530    --  system.file_io%s
26531    --  system.secondary_stack%s
26532    --  system.file_io%b
26533    --  system.storage_pools.subpools%b
26534    --  system.finalization_masters%b
26535    --  interfaces.c%b
26536    --  ada.tags%b
26537    --  system.soft_links%b
26538    --  system.os_lib%b
26539    --  system.secondary_stack%b
26540    --  system.address_image%b
26541    --  system.traceback%s
26542    --  ada.exceptions%b
26543    --  system.traceback%b
26544    --  ada.text_io%s
26545    --  ada.text_io%b
26546    --  hello%b
26547    --  END ELABORATION ORDER
26549 end ada_main;
26550 @end example
26552 @example
26553 pragma Ada_95;
26554 --  The following source file name pragmas allow the generated file
26555 --  names to be unique for different main programs. They are needed
26556 --  since the package name will always be Ada_Main.
26558 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26559 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26561 pragma Suppress (Overflow_Check);
26562 with Ada.Exceptions;
26564 --  Generated package body for Ada_Main starts here
26566 package body ada_main is
26567    pragma Warnings (Off);
26569    --  These values are reference counter associated to units which have
26570    --  been elaborated. It is also used to avoid elaborating the
26571    --  same unit twice.
26573    E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
26574    E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
26575    E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
26576    E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
26577    E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
26578    E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
26579    E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
26580    E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
26581    E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
26582    E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
26583    E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
26584    E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
26585    E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
26586    E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
26587    E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
26588    E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
26589    E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
26590    E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
26592    Local_Priority_Specific_Dispatching : constant String := "";
26593    Local_Interrupt_States : constant String := "";
26595    Is_Elaborated : Boolean := False;
26597    procedure finalize_library is
26598    begin
26599       E06 := E06 - 1;
26600       declare
26601          procedure F1;
26602          pragma Import (Ada, F1, "ada__text_io__finalize_spec");
26603       begin
26604          F1;
26605       end;
26606       E77 := E77 - 1;
26607       E91 := E91 - 1;
26608       declare
26609          procedure F2;
26610          pragma Import (Ada, F2, "system__file_io__finalize_body");
26611       begin
26612          E64 := E64 - 1;
26613          F2;
26614       end;
26615       declare
26616          procedure F3;
26617          pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
26618       begin
26619          E75 := E75 - 1;
26620          F3;
26621       end;
26622       E87 := E87 - 1;
26623       declare
26624          procedure F4;
26625          pragma Import (Ada, F4, "system__pool_global__finalize_spec");
26626       begin
26627          F4;
26628       end;
26629       declare
26630          procedure F5;
26631          pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
26632       begin
26633          F5;
26634       end;
26635       declare
26636          procedure F6;
26637          pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
26638       begin
26639          F6;
26640       end;
26641       declare
26642          procedure Reraise_Library_Exception_If_Any;
26643          pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
26644       begin
26645          Reraise_Library_Exception_If_Any;
26646       end;
26647    end finalize_library;
26649    -------------
26650    -- adainit --
26651    -------------
26653    procedure adainit is
26655       Main_Priority : Integer;
26656       pragma Import (C, Main_Priority, "__gl_main_priority");
26657       Time_Slice_Value : Integer;
26658       pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
26659       WC_Encoding : Character;
26660       pragma Import (C, WC_Encoding, "__gl_wc_encoding");
26661       Locking_Policy : Character;
26662       pragma Import (C, Locking_Policy, "__gl_locking_policy");
26663       Queuing_Policy : Character;
26664       pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
26665       Task_Dispatching_Policy : Character;
26666       pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
26667       Priority_Specific_Dispatching : System.Address;
26668       pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
26669       Num_Specific_Dispatching : Integer;
26670       pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
26671       Main_CPU : Integer;
26672       pragma Import (C, Main_CPU, "__gl_main_cpu");
26673       Interrupt_States : System.Address;
26674       pragma Import (C, Interrupt_States, "__gl_interrupt_states");
26675       Num_Interrupt_States : Integer;
26676       pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
26677       Unreserve_All_Interrupts : Integer;
26678       pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
26679       Detect_Blocking : Integer;
26680       pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
26681       Default_Stack_Size : Integer;
26682       pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
26683       Leap_Seconds_Support : Integer;
26684       pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
26686       procedure Runtime_Initialize;
26687       pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
26689       Finalize_Library_Objects : No_Param_Proc;
26690       pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
26692    --  Start of processing for adainit
26694    begin
26696       --  Record various information for this partition.  The values
26697       --  are derived by the binder from information stored in the ali
26698       --  files by the compiler.
26700       if Is_Elaborated then
26701          return;
26702       end if;
26703       Is_Elaborated := True;
26704       Main_Priority := -1;
26705       Time_Slice_Value := -1;
26706       WC_Encoding := 'b';
26707       Locking_Policy := ' ';
26708       Queuing_Policy := ' ';
26709       Task_Dispatching_Policy := ' ';
26710       Priority_Specific_Dispatching :=
26711         Local_Priority_Specific_Dispatching'Address;
26712       Num_Specific_Dispatching := 0;
26713       Main_CPU := -1;
26714       Interrupt_States := Local_Interrupt_States'Address;
26715       Num_Interrupt_States := 0;
26716       Unreserve_All_Interrupts := 0;
26717       Detect_Blocking := 0;
26718       Default_Stack_Size := -1;
26719       Leap_Seconds_Support := 0;
26721       Runtime_Initialize;
26723       Finalize_Library_Objects := finalize_library'access;
26725       --  Now we have the elaboration calls for all units in the partition.
26726       --  The Elab_Spec and Elab_Body attributes generate references to the
26727       --  implicit elaboration procedures generated by the compiler for
26728       --  each unit that requires elaboration. Increment a counter of
26729       --  reference for each unit.
26731       System.Soft_Links'Elab_Spec;
26732       System.Exception_Table'Elab_Body;
26733       E23 := E23 + 1;
26734       Ada.Io_Exceptions'Elab_Spec;
26735       E46 := E46 + 1;
26736       Ada.Tags'Elab_Spec;
26737       Ada.Streams'Elab_Spec;
26738       E45 := E45 + 1;
26739       Interfaces.C'Elab_Spec;
26740       System.Exceptions'Elab_Spec;
26741       E25 := E25 + 1;
26742       System.Finalization_Root'Elab_Spec;
26743       E68 := E68 + 1;
26744       Ada.Finalization'Elab_Spec;
26745       E66 := E66 + 1;
26746       System.Storage_Pools'Elab_Spec;
26747       E85 := E85 + 1;
26748       System.Finalization_Masters'Elab_Spec;
26749       System.Storage_Pools.Subpools'Elab_Spec;
26750       System.Pool_Global'Elab_Spec;
26751       E87 := E87 + 1;
26752       System.File_Control_Block'Elab_Spec;
26753       E75 := E75 + 1;
26754       System.File_Io'Elab_Body;
26755       E64 := E64 + 1;
26756       E91 := E91 + 1;
26757       System.Finalization_Masters'Elab_Body;
26758       E77 := E77 + 1;
26759       E70 := E70 + 1;
26760       Ada.Tags'Elab_Body;
26761       E48 := E48 + 1;
26762       System.Soft_Links'Elab_Body;
26763       E13 := E13 + 1;
26764       System.Os_Lib'Elab_Body;
26765       E72 := E72 + 1;
26766       System.Secondary_Stack'Elab_Body;
26767       E17 := E17 + 1;
26768       Ada.Text_Io'Elab_Spec;
26769       Ada.Text_Io'Elab_Body;
26770       E06 := E06 + 1;
26771    end adainit;
26773    --------------
26774    -- adafinal --
26775    --------------
26777    procedure adafinal is
26778       procedure s_stalib_adafinal;
26779       pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
26781       procedure Runtime_Finalize;
26782       pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
26784    begin
26785       if not Is_Elaborated then
26786          return;
26787       end if;
26788       Is_Elaborated := False;
26789       Runtime_Finalize;
26790       s_stalib_adafinal;
26791    end adafinal;
26793    --  We get to the main program of the partition by using
26794    --  pragma Import because if we try to with the unit and
26795    --  call it Ada style, then not only do we waste time
26796    --  recompiling it, but also, we don't really know the right
26797    --  switches (e.g.@@: identifier character set) to be used
26798    --  to compile it.
26800    procedure Ada_Main_Program;
26801    pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26803    ----------
26804    -- main --
26805    ----------
26807    --  main is actually a function, as in the ANSI C standard,
26808    --  defined to return the exit status. The three parameters
26809    --  are the argument count, argument values and environment
26810    --  pointer.
26812    function main
26813      (argc : Integer;
26814       argv : System.Address;
26815       envp : System.Address)
26816       return Integer
26817    is
26818       --  The initialize routine performs low level system
26819       --  initialization using a standard library routine which
26820       --  sets up signal handling and performs any other
26821       --  required setup. The routine can be found in file
26822       --  a-init.c.
26824       procedure initialize;
26825       pragma Import (C, initialize, "__gnat_initialize");
26827       --  The finalize routine performs low level system
26828       --  finalization using a standard library routine. The
26829       --  routine is found in file a-final.c and in the standard
26830       --  distribution is a dummy routine that does nothing, so
26831       --  really this is a hook for special user finalization.
26833       procedure finalize;
26834       pragma Import (C, finalize, "__gnat_finalize");
26836       --  The following is to initialize the SEH exceptions
26838       SEH : aliased array (1 .. 2) of Integer;
26840       Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
26841       pragma Volatile (Ensure_Reference);
26843    --  Start of processing for main
26845    begin
26846       --  Save global variables
26848       gnat_argc := argc;
26849       gnat_argv := argv;
26850       gnat_envp := envp;
26852       --  Call low level system initialization
26854       Initialize (SEH'Address);
26856       --  Call our generated Ada initialization routine
26858       adainit;
26860       --  Now we call the main program of the partition
26862       Ada_Main_Program;
26864       --  Perform Ada finalization
26866       adafinal;
26868       --  Perform low level system finalization
26870       Finalize;
26872       --  Return the proper exit status
26873       return (gnat_exit_status);
26874    end;
26876 --  This section is entirely comments, so it has no effect on the
26877 --  compilation of the Ada_Main package. It provides the list of
26878 --  object files and linker options, as well as some standard
26879 --  libraries needed for the link. The gnatlink utility parses
26880 --  this b~hello.adb file to read these comment lines to generate
26881 --  the appropriate command line arguments for the call to the
26882 --  system linker. The BEGIN/END lines are used for sentinels for
26883 --  this parsing operation.
26885 --  The exact file names will of course depend on the environment,
26886 --  host/target and location of files on the host system.
26888 -- BEGIN Object file/option list
26889    --   ./hello.o
26890    --   -L./
26891    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
26892    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
26893 -- END Object file/option list
26895 end ada_main;
26896 @end example
26898 The Ada code in the above example is exactly what is generated by the
26899 binder. We have added comments to more clearly indicate the function
26900 of each part of the generated @cite{Ada_Main} package.
26902 The code is standard Ada in all respects, and can be processed by any
26903 tools that handle Ada. In particular, it is possible to use the debugger
26904 in Ada mode to debug the generated @cite{Ada_Main} package. For example,
26905 suppose that for reasons that you do not understand, your program is crashing
26906 during elaboration of the body of @cite{Ada.Text_IO}. To locate this bug,
26907 you can place a breakpoint on the call:
26909 @quotation
26911 @example
26912 Ada.Text_Io'Elab_Body;
26913 @end example
26914 @end quotation
26916 and trace the elaboration routine for this package to find out where
26917 the problem might be (more usually of course you would be debugging
26918 elaboration code in your own application).
26920 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
26922 @node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
26923 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order-handling-in-gnat}@anchor{f}@anchor{gnat_ugn/elaboration_order_handling_in_gnat doc}@anchor{230}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id1}@anchor{231}
26924 @chapter Elaboration Order Handling in GNAT
26927 @geindex Order of elaboration
26929 @geindex Elaboration control
26931 This appendix describes the handling of elaboration code in Ada and
26932 in GNAT, and discusses how the order of elaboration of program units can
26933 be controlled in GNAT, either automatically or with explicit programming
26934 features.
26936 @menu
26937 * Elaboration Code:: 
26938 * Checking the Elaboration Order:: 
26939 * Controlling the Elaboration Order:: 
26940 * Controlling Elaboration in GNAT - Internal Calls:: 
26941 * Controlling Elaboration in GNAT - External Calls:: 
26942 * Default Behavior in GNAT - Ensuring Safety:: 
26943 * Treatment of Pragma Elaborate:: 
26944 * Elaboration Issues for Library Tasks:: 
26945 * Mixing Elaboration Models:: 
26946 * What to Do If the Default Elaboration Behavior Fails:: 
26947 * Elaboration for Indirect Calls:: 
26948 * Summary of Procedures for Elaboration Control:: 
26949 * Other Elaboration Order Considerations:: 
26950 * Determining the Chosen Elaboration Order:: 
26952 @end menu
26954 @node Elaboration Code,Checking the Elaboration Order,,Elaboration Order Handling in GNAT
26955 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{232}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{233}
26956 @section Elaboration Code
26959 Ada provides rather general mechanisms for executing code at elaboration
26960 time, that is to say before the main program starts executing. Such code arises
26961 in three contexts:
26964 @itemize *
26966 @item 
26967 @emph{Initializers for variables}
26969 Variables declared at the library level, in package specs or bodies, can
26970 require initialization that is performed at elaboration time, as in:
26972 @example
26973 Sqrt_Half : Float := Sqrt (0.5);
26974 @end example
26976 @item 
26977 @emph{Package initialization code}
26979 Code in a @cite{BEGIN-END} section at the outer level of a package body is
26980 executed as part of the package body elaboration code.
26982 @item 
26983 @emph{Library level task allocators}
26985 Tasks that are declared using task allocators at the library level
26986 start executing immediately and hence can execute at elaboration time.
26987 @end itemize
26989 Subprogram calls are possible in any of these contexts, which means that
26990 any arbitrary part of the program may be executed as part of the elaboration
26991 code. It is even possible to write a program which does all its work at
26992 elaboration time, with a null main program, although stylistically this
26993 would usually be considered an inappropriate way to structure
26994 a program.
26996 An important concern arises in the context of elaboration code:
26997 we have to be sure that it is executed in an appropriate order. What we
26998 have is a series of elaboration code sections, potentially one section
26999 for each unit in the program. It is important that these execute
27000 in the correct order. Correctness here means that, taking the above
27001 example of the declaration of @cite{Sqrt_Half},
27002 if some other piece of
27003 elaboration code references @cite{Sqrt_Half},
27004 then it must run after the
27005 section of elaboration code that contains the declaration of
27006 @cite{Sqrt_Half}.
27008 There would never be any order of elaboration problem if we made a rule
27009 that whenever you @emph{with} a unit, you must elaborate both the spec and body
27010 of that unit before elaborating the unit doing the @emph{with}ing:
27012 @example
27013 with Unit_1;
27014 package Unit_2 is ...
27015 @end example
27017 would require that both the body and spec of @cite{Unit_1} be elaborated
27018 before the spec of @cite{Unit_2}. However, a rule like that would be far too
27019 restrictive. In particular, it would make it impossible to have routines
27020 in separate packages that were mutually recursive.
27022 You might think that a clever enough compiler could look at the actual
27023 elaboration code and determine an appropriate correct order of elaboration,
27024 but in the general case, this is not possible. Consider the following
27025 example.
27027 In the body of @cite{Unit_1}, we have a procedure @cite{Func_1}
27028 that references
27029 the variable @cite{Sqrt_1}, which is declared in the elaboration code
27030 of the body of @cite{Unit_1}:
27032 @example
27033 Sqrt_1 : Float := Sqrt (0.1);
27034 @end example
27036 The elaboration code of the body of @cite{Unit_1} also contains:
27038 @example
27039 if expression_1 = 1 then
27040    Q := Unit_2.Func_2;
27041 end if;
27042 @end example
27044 @cite{Unit_2} is exactly parallel,
27045 it has a procedure @cite{Func_2} that references
27046 the variable @cite{Sqrt_2}, which is declared in the elaboration code of
27047 the body @cite{Unit_2}:
27049 @example
27050 Sqrt_2 : Float := Sqrt (0.1);
27051 @end example
27053 The elaboration code of the body of @cite{Unit_2} also contains:
27055 @example
27056 if expression_2 = 2 then
27057    Q := Unit_1.Func_1;
27058 end if;
27059 @end example
27061 Now the question is, which of the following orders of elaboration is
27062 acceptable:
27064 @example
27065 Spec of Unit_1
27066 Spec of Unit_2
27067 Body of Unit_1
27068 Body of Unit_2
27069 @end example
27073 @example
27074 Spec of Unit_2
27075 Spec of Unit_1
27076 Body of Unit_2
27077 Body of Unit_1
27078 @end example
27080 If you carefully analyze the flow here, you will see that you cannot tell
27081 at compile time the answer to this question.
27082 If @cite{expression_1} is not equal to 1,
27083 and @cite{expression_2} is not equal to 2,
27084 then either order is acceptable, because neither of the function calls is
27085 executed. If both tests evaluate to true, then neither order is acceptable
27086 and in fact there is no correct order.
27088 If one of the two expressions is true, and the other is false, then one
27089 of the above orders is correct, and the other is incorrect. For example,
27090 if @cite{expression_1} /= 1 and @cite{expression_2} = 2,
27091 then the call to @cite{Func_1}
27092 will occur, but not the call to @cite{Func_2.}
27093 This means that it is essential
27094 to elaborate the body of @cite{Unit_1} before
27095 the body of @cite{Unit_2}, so the first
27096 order of elaboration is correct and the second is wrong.
27098 By making @cite{expression_1} and @cite{expression_2}
27099 depend on input data, or perhaps
27100 the time of day, we can make it impossible for the compiler or binder
27101 to figure out which of these expressions will be true, and hence it
27102 is impossible to guarantee a safe order of elaboration at run time.
27104 @node Checking the Elaboration Order,Controlling the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
27105 @anchor{gnat_ugn/elaboration_order_handling_in_gnat checking-the-elaboration-order}@anchor{234}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{235}
27106 @section Checking the Elaboration Order
27109 In some languages that involve the same kind of elaboration problems,
27110 e.g., Java and C++, the programmer needs to take these
27111 ordering problems into account, and it is common to
27112 write a program in which an incorrect elaboration order  gives
27113 surprising results, because it references variables before they
27114 are initialized.
27115 Ada is designed to be a safe language, and a programmer-beware approach is
27116 clearly not sufficient. Consequently, the language provides three lines
27117 of defense:
27120 @itemize *
27122 @item 
27123 @emph{Standard rules}
27125 Some standard rules restrict the possible choice of elaboration
27126 order. In particular, if you @emph{with} a unit, then its spec is always
27127 elaborated before the unit doing the @emph{with}. Similarly, a parent
27128 spec is always elaborated before the child spec, and finally
27129 a spec is always elaborated before its corresponding body.
27130 @end itemize
27132 @geindex Elaboration checks
27134 @geindex Checks
27135 @geindex elaboration
27138 @itemize *
27140 @item 
27141 @emph{Dynamic elaboration checks}
27143 Dynamic checks are made at run time, so that if some entity is accessed
27144 before it is elaborated (typically  by means of a subprogram call)
27145 then the exception (@cite{Program_Error}) is raised.
27147 @item 
27148 @emph{Elaboration control}
27150 Facilities are provided for the programmer to specify the desired order
27151 of elaboration.
27152 @end itemize
27154 Let's look at these facilities in more detail. First, the rules for
27155 dynamic checking. One possible rule would be simply to say that the
27156 exception is raised if you access a variable which has not yet been
27157 elaborated. The trouble with this approach is that it could require
27158 expensive checks on every variable reference. Instead Ada has two
27159 rules which are a little more restrictive, but easier to check, and
27160 easier to state:
27163 @itemize *
27165 @item 
27166 @emph{Restrictions on calls}
27168 A subprogram can only be called at elaboration time if its body
27169 has been elaborated. The rules for elaboration given above guarantee
27170 that the spec of the subprogram has been elaborated before the
27171 call, but not the body. If this rule is violated, then the
27172 exception @cite{Program_Error} is raised.
27174 @item 
27175 @emph{Restrictions on instantiations}
27177 A generic unit can only be instantiated if the body of the generic
27178 unit has been elaborated. Again, the rules for elaboration given above
27179 guarantee that the spec of the generic unit has been elaborated
27180 before the instantiation, but not the body. If this rule is
27181 violated, then the exception @cite{Program_Error} is raised.
27182 @end itemize
27184 The idea is that if the body has been elaborated, then any variables
27185 it references must have been elaborated; by checking for the body being
27186 elaborated we guarantee that none of its references causes any
27187 trouble. As we noted above, this is a little too restrictive, because a
27188 subprogram that has no non-local references in its body may in fact be safe
27189 to call. However, it really would be unsafe to rely on this, because
27190 it would mean that the caller was aware of details of the implementation
27191 in the body. This goes against the basic tenets of Ada.
27193 A plausible implementation can be described as follows.
27194 A Boolean variable is associated with each subprogram
27195 and each generic unit. This variable is initialized to False, and is set to
27196 True at the point body is elaborated. Every call or instantiation checks the
27197 variable, and raises @cite{Program_Error} if the variable is False.
27199 Note that one might think that it would be good enough to have one Boolean
27200 variable for each package, but that would not deal with cases of trying
27201 to call a body in the same package as the call
27202 that has not been elaborated yet.
27203 Of course a compiler may be able to do enough analysis to optimize away
27204 some of the Boolean variables as unnecessary, and @cite{GNAT} indeed
27205 does such optimizations, but still the easiest conceptual model is to
27206 think of there being one variable per subprogram.
27208 @node Controlling the Elaboration Order,Controlling Elaboration in GNAT - Internal Calls,Checking the Elaboration Order,Elaboration Order Handling in GNAT
27209 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id4}@anchor{236}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order}@anchor{237}
27210 @section Controlling the Elaboration Order
27213 In the previous section we discussed the rules in Ada which ensure
27214 that @cite{Program_Error} is raised if an incorrect elaboration order is
27215 chosen. This prevents erroneous executions, but we need mechanisms to
27216 specify a correct execution and avoid the exception altogether.
27217 To achieve this, Ada provides a number of features for controlling
27218 the order of elaboration. We discuss these features in this section.
27220 First, there are several ways of indicating to the compiler that a given
27221 unit has no elaboration problems:
27224 @itemize *
27226 @item 
27227 @emph{packages that do not require a body}
27229 A library package that does not require a body does not permit
27230 a body (this rule was introduced in Ada 95).
27231 Thus if we have a such a package, as in:
27233 @example
27234 package Definitions is
27235    generic
27236       type m is new integer;
27237    package Subp is
27238       type a is array (1 .. 10) of m;
27239       type b is array (1 .. 20) of m;
27240    end Subp;
27241 end Definitions;
27242 @end example
27244 A package that @emph{with}s @cite{Definitions} may safely instantiate
27245 @cite{Definitions.Subp} because the compiler can determine that there
27246 definitely is no package body to worry about in this case
27247 @end itemize
27249 @geindex pragma Pure
27252 @itemize *
27254 @item 
27255 @emph{pragma Pure}
27257 This pragma places sufficient restrictions on a unit to guarantee that
27258 no call to any subprogram in the unit can result in an
27259 elaboration problem. This means that the compiler does not need
27260 to worry about the point of elaboration of such units, and in
27261 particular, does not need to check any calls to any subprograms
27262 in this unit.
27263 @end itemize
27265 @geindex pragma Preelaborate
27268 @itemize *
27270 @item 
27271 @emph{pragma Preelaborate}
27273 This pragma places slightly less stringent restrictions on a unit than
27274 does pragma Pure,
27275 but these restrictions are still sufficient to ensure that there
27276 are no elaboration problems with any calls to the unit.
27277 @end itemize
27279 @geindex pragma Elaborate_Body
27282 @itemize *
27284 @item 
27285 @emph{pragma Elaborate_Body}
27287 This pragma requires that the body of a unit be elaborated immediately
27288 after its spec. Suppose a unit @cite{A} has such a pragma,
27289 and unit @cite{B} does
27290 a @emph{with} of unit @cite{A}. Recall that the standard rules require
27291 the spec of unit @cite{A}
27292 to be elaborated before the @emph{with}ing unit; given the pragma in
27293 @cite{A}, we also know that the body of @cite{A}
27294 will be elaborated before @cite{B}, so
27295 that calls to @cite{A} are safe and do not need a check.
27297 Note that, unlike pragma @cite{Pure} and pragma @cite{Preelaborate},
27298 the use of @cite{Elaborate_Body} does not guarantee that the program is
27299 free of elaboration problems, because it may not be possible
27300 to satisfy the requested elaboration order.
27301 Let's go back to the example with @cite{Unit_1} and @cite{Unit_2}.
27302 If a programmer marks @cite{Unit_1} as @cite{Elaborate_Body},
27303 and not @cite{Unit_2@comma{}} then the order of
27304 elaboration will be:
27306 @example
27307 Spec of Unit_2
27308 Spec of Unit_1
27309 Body of Unit_1
27310 Body of Unit_2
27311 @end example
27313 Now that means that the call to @cite{Func_1} in @cite{Unit_2}
27314 need not be checked,
27315 it must be safe. But the call to @cite{Func_2} in
27316 @cite{Unit_1} may still fail if
27317 @cite{Expression_1} is equal to 1,
27318 and the programmer must still take
27319 responsibility for this not being the case.
27321 If all units carry a pragma @cite{Elaborate_Body}, then all problems are
27322 eliminated, except for calls entirely within a body, which are
27323 in any case fully under programmer control. However, using the pragma
27324 everywhere is not always possible.
27325 In particular, for our @cite{Unit_1}/@cite{Unit_2} example, if
27326 we marked both of them as having pragma @cite{Elaborate_Body}, then
27327 clearly there would be no possible elaboration order.
27328 @end itemize
27330 The above pragmas allow a server to guarantee safe use by clients, and
27331 clearly this is the preferable approach. Consequently a good rule
27332 is to mark units as @cite{Pure} or @cite{Preelaborate} if possible,
27333 and if this is not possible,
27334 mark them as @cite{Elaborate_Body} if possible.
27335 As we have seen, there are situations where neither of these
27336 three pragmas can be used.
27337 So we also provide methods for clients to control the
27338 order of elaboration of the servers on which they depend:
27340 @geindex pragma Elaborate
27343 @itemize *
27345 @item 
27346 @emph{pragma Elaborate (unit)}
27348 This pragma is placed in the context clause, after a @emph{with} clause,
27349 and it requires that the body of the named unit be elaborated before
27350 the unit in which the pragma occurs. The idea is to use this pragma
27351 if the current unit calls at elaboration time, directly or indirectly,
27352 some subprogram in the named unit.
27353 @end itemize
27355 @geindex pragma Elaborate_All
27358 @itemize *
27360 @item 
27361 @emph{pragma Elaborate_All (unit)}
27363 This is a stronger version of the Elaborate pragma. Consider the
27364 following example:
27366 @example
27367 Unit A |withs| unit B and calls B.Func in elab code
27368 Unit B |withs| unit C, and B.Func calls C.Func
27369 @end example
27371 Now if we put a pragma @cite{Elaborate (B)}
27372 in unit @cite{A}, this ensures that the
27373 body of @cite{B} is elaborated before the call, but not the
27374 body of @cite{C}, so
27375 the call to @cite{C.Func} could still cause @cite{Program_Error} to
27376 be raised.
27378 The effect of a pragma @cite{Elaborate_All} is stronger, it requires
27379 not only that the body of the named unit be elaborated before the
27380 unit doing the @emph{with}, but also the bodies of all units that the
27381 named unit uses, following @emph{with} links transitively. For example,
27382 if we put a pragma @cite{Elaborate_All (B)} in unit @cite{A},
27383 then it requires not only that the body of @cite{B} be elaborated before @cite{A},
27384 but also the body of @cite{C}, because @cite{B} @emph{with}s @cite{C}.
27385 @end itemize
27387 We are now in a position to give a usage rule in Ada for avoiding
27388 elaboration problems, at least if dynamic dispatching and access to
27389 subprogram values are not used. We will handle these cases separately
27390 later.
27392 The rule is simple:
27394 @emph{If a unit has elaboration code that can directly or
27395 indirectly make a call to a subprogram in a |withed| unit, or instantiate
27396 a generic package in a |withed| unit,
27397 then if the |withed| unit does not have
27398 pragma `Pure` or `Preelaborate`, then the client should have
27399 a pragma `Elaborate_All`for the |withed| unit.*}
27401 By following this rule a client is
27402 assured that calls can be made without risk of an exception.
27404 For generic subprogram instantiations, the rule can be relaxed to
27405 require only a pragma @cite{Elaborate} since elaborating the body
27406 of a subprogram cannot cause any transitive elaboration (we are
27407 not calling the subprogram in this case, just elaborating its
27408 declaration).
27410 If this rule is not followed, then a program may be in one of four
27411 states:
27414 @itemize *
27416 @item 
27417 @emph{No order exists}
27419 No order of elaboration exists which follows the rules, taking into
27420 account any @cite{Elaborate}, @cite{Elaborate_All},
27421 or @cite{Elaborate_Body} pragmas. In
27422 this case, an Ada compiler must diagnose the situation at bind
27423 time, and refuse to build an executable program.
27425 @item 
27426 @emph{One or more orders exist, all incorrect}
27428 One or more acceptable elaboration orders exist, and all of them
27429 generate an elaboration order problem. In this case, the binder
27430 can build an executable program, but @cite{Program_Error} will be raised
27431 when the program is run.
27433 @item 
27434 @emph{Several orders exist, some right, some incorrect}
27436 One or more acceptable elaboration orders exists, and some of them
27437 work, and some do not. The programmer has not controlled
27438 the order of elaboration, so the binder may or may not pick one of
27439 the correct orders, and the program may or may not raise an
27440 exception when it is run. This is the worst case, because it means
27441 that the program may fail when moved to another compiler, or even
27442 another version of the same compiler.
27444 @item 
27445 @emph{One or more orders exists, all correct}
27447 One ore more acceptable elaboration orders exist, and all of them
27448 work. In this case the program runs successfully. This state of
27449 affairs can be guaranteed by following the rule we gave above, but
27450 may be true even if the rule is not followed.
27451 @end itemize
27453 Note that one additional advantage of following our rules on the use
27454 of @cite{Elaborate} and @cite{Elaborate_All}
27455 is that the program continues to stay in the ideal (all orders OK) state
27456 even if maintenance
27457 changes some bodies of some units. Conversely, if a program that does
27458 not follow this rule happens to be safe at some point, this state of affairs
27459 may deteriorate silently as a result of maintenance changes.
27461 You may have noticed that the above discussion did not mention
27462 the use of @cite{Elaborate_Body}. This was a deliberate omission. If you
27463 @emph{with} an @cite{Elaborate_Body} unit, it still may be the case that
27464 code in the body makes calls to some other unit, so it is still necessary
27465 to use @cite{Elaborate_All} on such units.
27467 @node Controlling Elaboration in GNAT - Internal Calls,Controlling Elaboration in GNAT - External Calls,Controlling the Elaboration Order,Elaboration Order Handling in GNAT
27468 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id5}@anchor{238}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-elaboration-in-gnat-internal-calls}@anchor{239}
27469 @section Controlling Elaboration in GNAT - Internal Calls
27472 In the case of internal calls, i.e., calls within a single package, the
27473 programmer has full control over the order of elaboration, and it is up
27474 to the programmer to elaborate declarations in an appropriate order. For
27475 example writing:
27477 @example
27478 function One return Float;
27480 Q : Float := One;
27482 function One return Float is
27483 begin
27484      return 1.0;
27485 end One;
27486 @end example
27488 will obviously raise @cite{Program_Error} at run time, because function
27489 One will be called before its body is elaborated. In this case GNAT will
27490 generate a warning that the call will raise @cite{Program_Error}:
27492 @example
27493  1. procedure y is
27494  2.    function One return Float;
27495  3.
27496  4.    Q : Float := One;
27497                     |
27498     >>> warning: cannot call "One" before body is elaborated
27499     >>> warning: Program_Error will be raised at run time
27501  5.
27502  6.    function One return Float is
27503  7.    begin
27504  8.         return 1.0;
27505  9.    end One;
27507 11. begin
27508 12.    null;
27509 13. end;
27510 @end example
27512 Note that in this particular case, it is likely that the call is safe, because
27513 the function @cite{One} does not access any global variables.
27514 Nevertheless in Ada, we do not want the validity of the check to depend on
27515 the contents of the body (think about the separate compilation case), so this
27516 is still wrong, as we discussed in the previous sections.
27518 The error is easily corrected by rearranging the declarations so that the
27519 body of @cite{One} appears before the declaration containing the call
27520 (note that in Ada 95 as well as later versions of the Ada standard,
27521 declarations can appear in any order, so there is no restriction that
27522 would prevent this reordering, and if we write:
27524 @example
27525 function One return Float;
27527 function One return Float is
27528 begin
27529      return 1.0;
27530 end One;
27532 Q : Float := One;
27533 @end example
27535 then all is well, no warning is generated, and no
27536 @cite{Program_Error} exception
27537 will be raised.
27538 Things are more complicated when a chain of subprograms is executed:
27540 @example
27541 function A return Integer;
27542 function B return Integer;
27543 function C return Integer;
27545 function B return Integer is begin return A; end;
27546 function C return Integer is begin return B; end;
27548 X : Integer := C;
27550 function A return Integer is begin return 1; end;
27551 @end example
27553 Now the call to @cite{C}
27554 at elaboration time in the declaration of @cite{X} is correct, because
27555 the body of @cite{C} is already elaborated,
27556 and the call to @cite{B} within the body of
27557 @cite{C} is correct, but the call
27558 to @cite{A} within the body of @cite{B} is incorrect, because the body
27559 of @cite{A} has not been elaborated, so @cite{Program_Error}
27560 will be raised on the call to @cite{A}.
27561 In this case GNAT will generate a
27562 warning that @cite{Program_Error} may be
27563 raised at the point of the call. Let's look at the warning:
27565 @example
27566  1. procedure x is
27567  2.    function A return Integer;
27568  3.    function B return Integer;
27569  4.    function C return Integer;
27570  5.
27571  6.    function B return Integer is begin return A; end;
27572                                                     |
27573     >>> warning: call to "A" before body is elaborated may
27574                  raise Program_Error
27575     >>> warning: "B" called at line 7
27576     >>> warning: "C" called at line 9
27578  7.    function C return Integer is begin return B; end;
27579  8.
27580  9.    X : Integer := C;
27582 11.    function A return Integer is begin return 1; end;
27584 13. begin
27585 14.    null;
27586 15. end;
27587 @end example
27589 Note that the message here says 'may raise', instead of the direct case,
27590 where the message says 'will be raised'. That's because whether
27591 @cite{A} is
27592 actually called depends in general on run-time flow of control.
27593 For example, if the body of @cite{B} said
27595 @example
27596 function B return Integer is
27597 begin
27598    if some-condition-depending-on-input-data then
27599       return A;
27600    else
27601       return 1;
27602    end if;
27603 end B;
27604 @end example
27606 then we could not know until run time whether the incorrect call to A would
27607 actually occur, so @cite{Program_Error} might
27608 or might not be raised. It is possible for a compiler to
27609 do a better job of analyzing bodies, to
27610 determine whether or not @cite{Program_Error}
27611 might be raised, but it certainly
27612 couldn't do a perfect job (that would require solving the halting problem
27613 and is provably impossible), and because this is a warning anyway, it does
27614 not seem worth the effort to do the analysis. Cases in which it
27615 would be relevant are rare.
27617 In practice, warnings of either of the forms given
27618 above will usually correspond to
27619 real errors, and should be examined carefully and eliminated.
27620 In the rare case where a warning is bogus, it can be suppressed by any of
27621 the following methods:
27624 @itemize *
27626 @item 
27627 Compile with the @emph{-gnatws} switch set
27629 @item 
27630 Suppress @cite{Elaboration_Check} for the called subprogram
27632 @item 
27633 Use pragma @cite{Warnings_Off} to turn warnings off for the call
27634 @end itemize
27636 For the internal elaboration check case,
27637 GNAT by default generates the
27638 necessary run-time checks to ensure
27639 that @cite{Program_Error} is raised if any
27640 call fails an elaboration check. Of course this can only happen if a
27641 warning has been issued as described above. The use of pragma
27642 @cite{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
27643 some of these checks, meaning that it may be possible (but is not
27644 guaranteed) for a program to be able to call a subprogram whose body
27645 is not yet elaborated, without raising a @cite{Program_Error} exception.
27647 @node Controlling Elaboration in GNAT - External Calls,Default Behavior in GNAT - Ensuring Safety,Controlling Elaboration in GNAT - Internal Calls,Elaboration Order Handling in GNAT
27648 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id6}@anchor{23a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-elaboration-in-gnat-external-calls}@anchor{23b}
27649 @section Controlling Elaboration in GNAT - External Calls
27652 The previous section discussed the case in which the execution of a
27653 particular thread of elaboration code occurred entirely within a
27654 single unit. This is the easy case to handle, because a programmer
27655 has direct and total control over the order of elaboration, and
27656 furthermore, checks need only be generated in cases which are rare
27657 and which the compiler can easily detect.
27658 The situation is more complex when separate compilation is taken into account.
27659 Consider the following:
27661 @example
27662 package Math is
27663    function Sqrt (Arg : Float) return Float;
27664 end Math;
27666 package body Math is
27667    function Sqrt (Arg : Float) return Float is
27668    begin
27669          ...
27670    end Sqrt;
27671 end Math;
27673 with Math;
27674 package Stuff is
27675    X : Float := Math.Sqrt (0.5);
27676 end Stuff;
27678 with Stuff;
27679 procedure Main is
27680 begin
27681    ...
27682 end Main;
27683 @end example
27685 where @cite{Main} is the main program. When this program is executed, the
27686 elaboration code must first be executed, and one of the jobs of the
27687 binder is to determine the order in which the units of a program are
27688 to be elaborated. In this case we have four units: the spec and body
27689 of @cite{Math},
27690 the spec of @cite{Stuff} and the body of @cite{Main}).
27691 In what order should the four separate sections of elaboration code
27692 be executed?
27694 There are some restrictions in the order of elaboration that the binder
27695 can choose. In particular, if unit U has a @emph{with}
27696 for a package @cite{X}, then you
27697 are assured that the spec of @cite{X}
27698 is elaborated before U , but you are
27699 not assured that the body of @cite{X}
27700 is elaborated before U.
27701 This means that in the above case, the binder is allowed to choose the
27702 order:
27704 @example
27705 spec of Math
27706 spec of Stuff
27707 body of Math
27708 body of Main
27709 @end example
27711 but that's not good, because now the call to @cite{Math.Sqrt}
27712 that happens during
27713 the elaboration of the @cite{Stuff}
27714 spec happens before the body of @cite{Math.Sqrt} is
27715 elaborated, and hence causes @cite{Program_Error} exception to be raised.
27716 At first glance, one might say that the binder is misbehaving, because
27717 obviously you want to elaborate the body of something you @emph{with} first, but
27718 that is not a general rule that can be followed in all cases. Consider
27720 @example
27721 package X is ...
27723 package Y is ...
27725 with X;
27726 package body Y is ...
27728 with Y;
27729 package body X is ...
27730 @end example
27732 This is a common arrangement, and, apart from the order of elaboration
27733 problems that might arise in connection with elaboration code, this works fine.
27734 A rule that says that you must first elaborate the body of anything you
27735 @emph{with} cannot work in this case:
27736 the body of @cite{X} @emph{with}s @cite{Y},
27737 which means you would have to
27738 elaborate the body of @cite{Y} first, but that @emph{with}s @cite{X},
27739 which means
27740 you have to elaborate the body of @cite{X} first, but ... and we have a
27741 loop that cannot be broken.
27743 It is true that the binder can in many cases guess an order of elaboration
27744 that is unlikely to cause a @cite{Program_Error}
27745 exception to be raised, and it tries to do so (in the
27746 above example of @cite{Math/Stuff/Spec}, the GNAT binder will
27747 by default
27748 elaborate the body of @cite{Math} right after its spec, so all will be well).
27750 However, a program that blindly relies on the binder to be helpful can
27751 get into trouble, as we discussed in the previous sections, so GNAT
27752 provides a number of facilities for assisting the programmer in
27753 developing programs that are robust with respect to elaboration order.
27755 @node Default Behavior in GNAT - Ensuring Safety,Treatment of Pragma Elaborate,Controlling Elaboration in GNAT - External Calls,Elaboration Order Handling in GNAT
27756 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{23c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat default-behavior-in-gnat-ensuring-safety}@anchor{23d}
27757 @section Default Behavior in GNAT - Ensuring Safety
27760 The default behavior in GNAT ensures elaboration safety. In its
27761 default mode GNAT implements the
27762 rule we previously described as the right approach. Let's restate it:
27764 @emph{If a unit has elaboration code that can directly or indirectly make a
27765 call to a subprogram in a |withed| unit, or instantiate a generic
27766 package in a |withed| unit, then if the |withed| unit
27767 does not have pragma `Pure` or `Preelaborate`, then the client should have an
27768 `Elaborate_All` pragma for the |withed| unit.}
27770 @emph{In the case of instantiating a generic subprogram, it is always
27771 sufficient to have only an `Elaborate` pragma for the
27772 |withed| unit.}
27774 By following this rule a client is assured that calls and instantiations
27775 can be made without risk of an exception.
27777 In this mode GNAT traces all calls that are potentially made from
27778 elaboration code, and puts in any missing implicit @cite{Elaborate}
27779 and @cite{Elaborate_All} pragmas.
27780 The advantage of this approach is that no elaboration problems
27781 are possible if the binder can find an elaboration order that is
27782 consistent with these implicit @cite{Elaborate} and
27783 @cite{Elaborate_All} pragmas. The
27784 disadvantage of this approach is that no such order may exist.
27786 If the binder does not generate any diagnostics, then it means that it has
27787 found an elaboration order that is guaranteed to be safe. However, the binder
27788 may still be relying on implicitly generated @cite{Elaborate} and
27789 @cite{Elaborate_All} pragmas so portability to other compilers than GNAT is not
27790 guaranteed.
27792 If it is important to guarantee portability, then the compilations should
27793 use the @emph{-gnatel}
27794 (info messages for elaboration pragmas) switch. This will cause info messages
27795 to be generated indicating the missing @cite{Elaborate} and
27796 @cite{Elaborate_All} pragmas.
27797 Consider the following source program:
27799 @example
27800 with k;
27801 package j is
27802   m : integer := k.r;
27803 end;
27804 @end example
27806 where it is clear that there
27807 should be a pragma @cite{Elaborate_All}
27808 for unit @cite{k}. An implicit pragma will be generated, and it is
27809 likely that the binder will be able to honor it. However, if you want
27810 to port this program to some other Ada compiler than GNAT.
27811 it is safer to include the pragma explicitly in the source. If this
27812 unit is compiled with the @emph{-gnatel}
27813 switch, then the compiler outputs an information message:
27815 @example
27816 1. with k;
27817 2. package j is
27818 3.   m : integer := k.r;
27819                      |
27820    >>> info: call to "r" may raise Program_Error
27821    >>> info: missing pragma Elaborate_All for "k"
27823 4. end;
27824 @end example
27826 and these messages can be used as a guide for supplying manually
27827 the missing pragmas. It is usually a bad idea to use this
27828 option during development. That's because it will tell you when
27829 you need to put in a pragma, but cannot tell you when it is time
27830 to take it out. So the use of pragma @cite{Elaborate_All} may lead to
27831 unnecessary dependencies and even false circularities.
27833 This default mode is more restrictive than the Ada Reference
27834 Manual, and it is possible to construct programs which will compile
27835 using the dynamic model described there, but will run into a
27836 circularity using the safer static model we have described.
27838 Of course any Ada compiler must be able to operate in a mode
27839 consistent with the requirements of the Ada Reference Manual,
27840 and in particular must have the capability of implementing the
27841 standard dynamic model of elaboration with run-time checks.
27843 In GNAT, this standard mode can be achieved either by the use of
27844 the @emph{-gnatE} switch on the compiler (@emph{gcc} or
27845 @emph{gnatmake}) command, or by the use of the configuration pragma:
27847 @example
27848 pragma Elaboration_Checks (DYNAMIC);
27849 @end example
27851 Either approach will cause the unit affected to be compiled using the
27852 standard dynamic run-time elaboration checks described in the Ada
27853 Reference Manual. The static model is generally preferable, since it
27854 is clearly safer to rely on compile and link time checks rather than
27855 run-time checks. However, in the case of legacy code, it may be
27856 difficult to meet the requirements of the static model. This
27857 issue is further discussed in
27858 @ref{23e,,What to Do If the Default Elaboration Behavior Fails}.
27860 Note that the static model provides a strict subset of the allowed
27861 behavior and programs of the Ada Reference Manual, so if you do
27862 adhere to the static model and no circularities exist,
27863 then you are assured that your program will
27864 work using the dynamic model, providing that you remove any
27865 pragma Elaborate statements from the source.
27867 @node Treatment of Pragma Elaborate,Elaboration Issues for Library Tasks,Default Behavior in GNAT - Ensuring Safety,Elaboration Order Handling in GNAT
27868 @anchor{gnat_ugn/elaboration_order_handling_in_gnat treatment-of-pragma-elaborate}@anchor{23f}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{240}
27869 @section Treatment of Pragma Elaborate
27872 @geindex Pragma Elaborate
27874 The use of @cite{pragma Elaborate}
27875 should generally be avoided in Ada 95 and Ada 2005 programs,
27876 since there is no guarantee that transitive calls
27877 will be properly handled. Indeed at one point, this pragma was placed
27878 in Annex J (Obsolescent Features), on the grounds that it is never useful.
27880 Now that's a bit restrictive. In practice, the case in which
27881 @cite{pragma Elaborate} is useful is when the caller knows that there
27882 are no transitive calls, or that the called unit contains all necessary
27883 transitive @cite{pragma Elaborate} statements, and legacy code often
27884 contains such uses.
27886 Strictly speaking the static mode in GNAT should ignore such pragmas,
27887 since there is no assurance at compile time that the necessary safety
27888 conditions are met. In practice, this would cause GNAT to be incompatible
27889 with correctly written Ada 83 code that had all necessary
27890 @cite{pragma Elaborate} statements in place. Consequently, we made the
27891 decision that GNAT in its default mode will believe that if it encounters
27892 a @cite{pragma Elaborate} then the programmer knows what they are doing,
27893 and it will trust that no elaboration errors can occur.
27895 The result of this decision is two-fold. First to be safe using the
27896 static mode, you should remove all @cite{pragma Elaborate} statements.
27897 Second, when fixing circularities in existing code, you can selectively
27898 use @cite{pragma Elaborate} statements to convince the static mode of
27899 GNAT that it need not generate an implicit @cite{pragma Elaborate_All}
27900 statement.
27902 When using the static mode with @emph{-gnatwl}, any use of
27903 @cite{pragma Elaborate} will generate a warning about possible
27904 problems.
27906 @node Elaboration Issues for Library Tasks,Mixing Elaboration Models,Treatment of Pragma Elaborate,Elaboration Order Handling in GNAT
27907 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-issues-for-library-tasks}@anchor{241}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{242}
27908 @section Elaboration Issues for Library Tasks
27911 @geindex Library tasks
27912 @geindex elaboration issues
27914 @geindex Elaboration of library tasks
27916 In this section we examine special elaboration issues that arise for
27917 programs that declare library level tasks.
27919 Generally the model of execution of an Ada program is that all units are
27920 elaborated, and then execution of the program starts. However, the
27921 declaration of library tasks definitely does not fit this model. The
27922 reason for this is that library tasks start as soon as they are declared
27923 (more precisely, as soon as the statement part of the enclosing package
27924 body is reached), that is to say before elaboration
27925 of the program is complete. This means that if such a task calls a
27926 subprogram, or an entry in another task, the callee may or may not be
27927 elaborated yet, and in the standard
27928 Reference Manual model of dynamic elaboration checks, you can even
27929 get timing dependent Program_Error exceptions, since there can be
27930 a race between the elaboration code and the task code.
27932 The static model of elaboration in GNAT seeks to avoid all such
27933 dynamic behavior, by being conservative, and the conservative
27934 approach in this particular case is to assume that all the code
27935 in a task body is potentially executed at elaboration time if
27936 a task is declared at the library level.
27938 This can definitely result in unexpected circularities. Consider
27939 the following example
27941 @example
27942 package Decls is
27943   task Lib_Task is
27944      entry Start;
27945   end Lib_Task;
27947   type My_Int is new Integer;
27949   function Ident (M : My_Int) return My_Int;
27950 end Decls;
27952 with Utils;
27953 package body Decls is
27954   task body Lib_Task is
27955   begin
27956      accept Start;
27957      Utils.Put_Val (2);
27958   end Lib_Task;
27960   function Ident (M : My_Int) return My_Int is
27961   begin
27962      return M;
27963   end Ident;
27964 end Decls;
27966 with Decls;
27967 package Utils is
27968   procedure Put_Val (Arg : Decls.My_Int);
27969 end Utils;
27971 with Text_IO;
27972 package body Utils is
27973   procedure Put_Val (Arg : Decls.My_Int) is
27974   begin
27975      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27976   end Put_Val;
27977 end Utils;
27979 with Decls;
27980 procedure Main is
27981 begin
27982    Decls.Lib_Task.Start;
27983 end;
27984 @end example
27986 If the above example is compiled in the default static elaboration
27987 mode, then a circularity occurs. The circularity comes from the call
27988 @cite{Utils.Put_Val} in the task body of @cite{Decls.Lib_Task}. Since
27989 this call occurs in elaboration code, we need an implicit pragma
27990 @cite{Elaborate_All} for @cite{Utils}. This means that not only must
27991 the spec and body of @cite{Utils} be elaborated before the body
27992 of @cite{Decls}, but also the spec and body of any unit that is
27993 @emph{with}ed by the body of @cite{Utils} must also be elaborated before
27994 the body of @cite{Decls}. This is the transitive implication of
27995 pragma @cite{Elaborate_All} and it makes sense, because in general
27996 the body of @cite{Put_Val} might have a call to something in a
27997 @emph{with}ed unit.
27999 In this case, the body of Utils (actually its spec) @emph{with}s
28000 @cite{Decls}. Unfortunately this means that the body of @cite{Decls}
28001 must be elaborated before itself, in case there is a call from the
28002 body of @cite{Utils}.
28004 Here is the exact chain of events we are worrying about:
28007 @itemize *
28009 @item 
28010 In the body of @cite{Decls} a call is made from within the body of a library
28011 task to a subprogram in the package @cite{Utils}. Since this call may
28012 occur at elaboration time (given that the task is activated at elaboration
28013 time), we have to assume the worst, i.e., that the
28014 call does happen at elaboration time.
28016 @item 
28017 This means that the body and spec of @cite{Util} must be elaborated before
28018 the body of @cite{Decls} so that this call does not cause an access before
28019 elaboration.
28021 @item 
28022 Within the body of @cite{Util}, specifically within the body of
28023 @cite{Util.Put_Val} there may be calls to any unit @emph{with}ed
28024 by this package.
28026 @item 
28027 One such @emph{with}ed package is package @cite{Decls}, so there
28028 might be a call to a subprogram in @cite{Decls} in @cite{Put_Val}.
28029 In fact there is such a call in this example, but we would have to
28030 assume that there was such a call even if it were not there, since
28031 we are not supposed to write the body of @cite{Decls} knowing what
28032 is in the body of @cite{Utils}; certainly in the case of the
28033 static elaboration model, the compiler does not know what is in
28034 other bodies and must assume the worst.
28036 @item 
28037 This means that the spec and body of @cite{Decls} must also be
28038 elaborated before we elaborate the unit containing the call, but
28039 that unit is @cite{Decls}! This means that the body of @cite{Decls}
28040 must be elaborated before itself, and that's a circularity.
28041 @end itemize
28043 Indeed, if you add an explicit pragma @cite{Elaborate_All} for @cite{Utils} in
28044 the body of @cite{Decls} you will get a true Ada Reference Manual
28045 circularity that makes the program illegal.
28047 In practice, we have found that problems with the static model of
28048 elaboration in existing code often arise from library tasks, so
28049 we must address this particular situation.
28051 Note that if we compile and run the program above, using the dynamic model of
28052 elaboration (that is to say use the @emph{-gnatE} switch),
28053 then it compiles, binds,
28054 links, and runs, printing the expected result of 2. Therefore in some sense
28055 the circularity here is only apparent, and we need to capture
28056 the properties of this program that  distinguish it from other library-level
28057 tasks that have real elaboration problems.
28059 We have four possible answers to this question:
28062 @itemize *
28064 @item 
28065 Use the dynamic model of elaboration.
28067 If we use the @emph{-gnatE} switch, then as noted above, the program works.
28068 Why is this? If we examine the task body, it is apparent that the task cannot
28069 proceed past the
28070 @cite{accept} statement until after elaboration has been completed, because
28071 the corresponding entry call comes from the main program, not earlier.
28072 This is why the dynamic model works here. But that's really giving
28073 up on a precise analysis, and we prefer to take this approach only if we cannot
28074 solve the
28075 problem in any other manner. So let us examine two ways to reorganize
28076 the program to avoid the potential elaboration problem.
28078 @item 
28079 Split library tasks into separate packages.
28081 Write separate packages, so that library tasks are isolated from
28082 other declarations as much as possible. Let us look at a variation on
28083 the above program.
28085 @example
28086 package Decls1 is
28087   task Lib_Task is
28088      entry Start;
28089   end Lib_Task;
28090 end Decls1;
28092 with Utils;
28093 package body Decls1 is
28094   task body Lib_Task is
28095   begin
28096      accept Start;
28097      Utils.Put_Val (2);
28098   end Lib_Task;
28099 end Decls1;
28101 package Decls2 is
28102   type My_Int is new Integer;
28103   function Ident (M : My_Int) return My_Int;
28104 end Decls2;
28106 with Utils;
28107 package body Decls2 is
28108   function Ident (M : My_Int) return My_Int is
28109   begin
28110      return M;
28111   end Ident;
28112 end Decls2;
28114 with Decls2;
28115 package Utils is
28116   procedure Put_Val (Arg : Decls2.My_Int);
28117 end Utils;
28119 with Text_IO;
28120 package body Utils is
28121   procedure Put_Val (Arg : Decls2.My_Int) is
28122   begin
28123      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
28124   end Put_Val;
28125 end Utils;
28127 with Decls1;
28128 procedure Main is
28129 begin
28130    Decls1.Lib_Task.Start;
28131 end;
28132 @end example
28134 All we have done is to split @cite{Decls} into two packages, one
28135 containing the library task, and one containing everything else. Now
28136 there is no cycle, and the program compiles, binds, links and executes
28137 using the default static model of elaboration.
28139 @item 
28140 Declare separate task types.
28142 A significant part of the problem arises because of the use of the
28143 single task declaration form. This means that the elaboration of
28144 the task type, and the elaboration of the task itself (i.e., the
28145 creation of the task) happen at the same time. A good rule
28146 of style in Ada is to always create explicit task types. By
28147 following the additional step of placing task objects in separate
28148 packages from the task type declaration, many elaboration problems
28149 are avoided. Here is another modified example of the example program:
28151 @example
28152 package Decls is
28153   task type Lib_Task_Type is
28154      entry Start;
28155   end Lib_Task_Type;
28157   type My_Int is new Integer;
28159   function Ident (M : My_Int) return My_Int;
28160 end Decls;
28162 with Utils;
28163 package body Decls is
28164   task body Lib_Task_Type is
28165   begin
28166      accept Start;
28167      Utils.Put_Val (2);
28168   end Lib_Task_Type;
28170   function Ident (M : My_Int) return My_Int is
28171   begin
28172      return M;
28173   end Ident;
28174 end Decls;
28176 with Decls;
28177 package Utils is
28178   procedure Put_Val (Arg : Decls.My_Int);
28179 end Utils;
28181 with Text_IO;
28182 package body Utils is
28183   procedure Put_Val (Arg : Decls.My_Int) is
28184   begin
28185      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28186   end Put_Val;
28187 end Utils;
28189 with Decls;
28190 package Declst is
28191    Lib_Task : Decls.Lib_Task_Type;
28192 end Declst;
28194 with Declst;
28195 procedure Main is
28196 begin
28197    Declst.Lib_Task.Start;
28198 end;
28199 @end example
28201 What we have done here is to replace the @cite{task} declaration in
28202 package @cite{Decls} with a @cite{task type} declaration. Then we
28203 introduce a separate package @cite{Declst} to contain the actual
28204 task object. This separates the elaboration issues for
28205 the @cite{task type}
28206 declaration, which causes no trouble, from the elaboration issues
28207 of the task object, which is also unproblematic, since it is now independent
28208 of the elaboration of  @cite{Utils}.
28209 This separation of concerns also corresponds to
28210 a generally sound engineering principle of separating declarations
28211 from instances. This version of the program also compiles, binds, links,
28212 and executes, generating the expected output.
28213 @end itemize
28215 @geindex No_Entry_Calls_In_Elaboration_Code restriction
28218 @itemize *
28220 @item 
28221 Use No_Entry_Calls_In_Elaboration_Code restriction.
28223 The previous two approaches described how a program can be restructured
28224 to avoid the special problems caused by library task bodies. in practice,
28225 however, such restructuring may be difficult to apply to existing legacy code,
28226 so we must consider solutions that do not require massive rewriting.
28228 Let us consider more carefully why our original sample program works
28229 under the dynamic model of elaboration. The reason is that the code
28230 in the task body blocks immediately on the @cite{accept}
28231 statement. Now of course there is nothing to prohibit elaboration
28232 code from making entry calls (for example from another library level task),
28233 so we cannot tell in isolation that
28234 the task will not execute the accept statement  during elaboration.
28236 However, in practice it is very unusual to see elaboration code
28237 make any entry calls, and the pattern of tasks starting
28238 at elaboration time and then immediately blocking on @cite{accept} or
28239 @cite{select} statements is very common. What this means is that
28240 the compiler is being too pessimistic when it analyzes the
28241 whole package body as though it might be executed at elaboration
28242 time.
28244 If we know that the elaboration code contains no entry calls, (a very safe
28245 assumption most of the time, that could almost be made the default
28246 behavior), then we can compile all units of the program under control
28247 of the following configuration pragma:
28249 @example
28250 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28251 @end example
28253 This pragma can be placed in the @code{gnat.adc} file in the usual
28254 manner. If we take our original unmodified program and compile it
28255 in the presence of a @code{gnat.adc} containing the above pragma,
28256 then once again, we can compile, bind, link, and execute, obtaining
28257 the expected result. In the presence of this pragma, the compiler does
28258 not trace calls in a task body, that appear after the first @cite{accept}
28259 or @cite{select} statement, and therefore does not report a potential
28260 circularity in the original program.
28262 The compiler will check to the extent it can that the above
28263 restriction is not violated, but it is not always possible to do a
28264 complete check at compile time, so it is important to use this
28265 pragma only if the stated restriction is in fact met, that is to say
28266 no task receives an entry call before elaboration of all units is completed.
28267 @end itemize
28269 @node Mixing Elaboration Models,What to Do If the Default Elaboration Behavior Fails,Elaboration Issues for Library Tasks,Elaboration Order Handling in GNAT
28270 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{243}@anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{244}
28271 @section Mixing Elaboration Models
28274 So far, we have assumed that the entire program is either compiled
28275 using the dynamic model or static model, ensuring consistency. It
28276 is possible to mix the two models, but rules have to be followed
28277 if this mixing is done to ensure that elaboration checks are not
28278 omitted.
28280 The basic rule is that
28281 @strong{a unit compiled with the static model cannot
28282 be |withed| by a unit compiled with the dynamic model}.
28283 The reason for this is that in the static model, a unit assumes that
28284 its clients guarantee to use (the equivalent of) pragma
28285 @cite{Elaborate_All} so that no elaboration checks are required
28286 in inner subprograms, and this assumption is violated if the
28287 client is compiled with dynamic checks.
28289 The precise rule is as follows. A unit that is compiled with dynamic
28290 checks can only @emph{with} a unit that meets at least one of the
28291 following criteria:
28294 @itemize *
28296 @item 
28297 The @emph{with}ed unit is itself compiled with dynamic elaboration
28298 checks (that is with the @emph{-gnatE} switch.
28300 @item 
28301 The @emph{with}ed unit is an internal GNAT implementation unit from
28302 the System, Interfaces, Ada, or GNAT hierarchies.
28304 @item 
28305 The @emph{with}ed unit has pragma Preelaborate or pragma Pure.
28307 @item 
28308 The @emph{with}ing unit (that is the client) has an explicit pragma
28309 @cite{Elaborate_All} for the @emph{with}ed unit.
28310 @end itemize
28312 If this rule is violated, that is if a unit with dynamic elaboration
28313 checks @emph{with}s a unit that does not meet one of the above four
28314 criteria, then the binder (@cite{gnatbind}) will issue a warning
28315 similar to that in the following example:
28317 @example
28318 warning: "x.ads" has dynamic elaboration checks and with's
28319 warning:   "y.ads" which has static elaboration checks
28320 @end example
28322 These warnings indicate that the rule has been violated, and that as a result
28323 elaboration checks may be missed in the resulting executable file.
28324 This warning may be suppressed using the @emph{-ws} binder switch
28325 in the usual manner.
28327 One useful application of this mixing rule is in the case of a subsystem
28328 which does not itself @emph{with} units from the remainder of the
28329 application. In this case, the entire subsystem can be compiled with
28330 dynamic checks to resolve a circularity in the subsystem, while
28331 allowing the main application that uses this subsystem to be compiled
28332 using the more reliable default static model.
28334 @node What to Do If the Default Elaboration Behavior Fails,Elaboration for Indirect Calls,Mixing Elaboration Models,Elaboration Order Handling in GNAT
28335 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{245}@anchor{gnat_ugn/elaboration_order_handling_in_gnat what-to-do-if-the-default-elaboration-behavior-fails}@anchor{23e}
28336 @section What to Do If the Default Elaboration Behavior Fails
28339 If the binder cannot find an acceptable order, it outputs detailed
28340 diagnostics. For example:
28342 @example
28343 error: elaboration circularity detected
28344 info:   "proc (body)" must be elaborated before "pack (body)"
28345 info:     reason: Elaborate_All probably needed in unit "pack (body)"
28346 info:     recompile "pack (body)" with -gnatel
28347 info:                             for full details
28348 info:       "proc (body)"
28349 info:         is needed by its spec:
28350 info:       "proc (spec)"
28351 info:         which is withed by:
28352 info:       "pack (body)"
28353 info:  "pack (body)" must be elaborated before "proc (body)"
28354 info:     reason: pragma Elaborate in unit "proc (body)"
28355 @end example
28357 In this case we have a cycle that the binder cannot break. On the one
28358 hand, there is an explicit pragma Elaborate in @cite{proc} for
28359 @cite{pack}. This means that the body of @cite{pack} must be elaborated
28360 before the body of @cite{proc}. On the other hand, there is elaboration
28361 code in @cite{pack} that calls a subprogram in @cite{proc}. This means
28362 that for maximum safety, there should really be a pragma
28363 Elaborate_All in @cite{pack} for @cite{proc} which would require that
28364 the body of @cite{proc} be elaborated before the body of
28365 @cite{pack}. Clearly both requirements cannot be satisfied.
28366 Faced with a circularity of this kind, you have three different options.
28369 @itemize *
28371 @item 
28372 @emph{Fix the program}
28374 The most desirable option from the point of view of long-term maintenance
28375 is to rearrange the program so that the elaboration problems are avoided.
28376 One useful technique is to place the elaboration code into separate
28377 child packages. Another is to move some of the initialization code to
28378 explicitly called subprograms, where the program controls the order
28379 of initialization explicitly. Although this is the most desirable option,
28380 it may be impractical and involve too much modification, especially in
28381 the case of complex legacy code.
28383 @item 
28384 @emph{Perform dynamic checks}
28386 If the compilations are done using the @emph{-gnatE}
28387 (dynamic elaboration check) switch, then GNAT behaves in a quite different
28388 manner. Dynamic checks are generated for all calls that could possibly result
28389 in raising an exception. With this switch, the compiler does not generate
28390 implicit @cite{Elaborate} or @cite{Elaborate_All} pragmas. The behavior then is
28391 exactly as specified in the @cite{Ada Reference Manual}.
28392 The binder will generate
28393 an executable program that may or may not raise @cite{Program_Error}, and then
28394 it is the programmer's job to ensure that it does not raise an exception. Note
28395 that it is important to compile all units with the switch, it cannot be used
28396 selectively.
28398 @item 
28399 @emph{Suppress checks}
28401 The drawback of dynamic checks is that they generate a
28402 significant overhead at run time, both in space and time. If you
28403 are absolutely sure that your program cannot raise any elaboration
28404 exceptions, and you still want to use the dynamic elaboration model,
28405 then you can use the configuration pragma
28406 @cite{Suppress (Elaboration_Check)} to suppress all such checks. For
28407 example this pragma could be placed in the @code{gnat.adc} file.
28409 @item 
28410 @emph{Suppress checks selectively}
28412 When you know that certain calls or instantiations in elaboration code cannot
28413 possibly lead to an elaboration error, and the binder nevertheless complains
28414 about implicit @cite{Elaborate} and @cite{Elaborate_All} pragmas that lead to
28415 elaboration circularities, it is possible to remove those warnings locally and
28416 obtain a program that will bind. Clearly this can be unsafe, and it is the
28417 responsibility of the programmer to make sure that the resulting program has no
28418 elaboration anomalies. The pragma @cite{Suppress (Elaboration_Check)} can be
28419 used with different granularity to suppress warnings and break elaboration
28420 circularities:
28423 @itemize *
28425 @item 
28426 Place the pragma that names the called subprogram in the declarative part
28427 that contains the call.
28429 @item 
28430 Place the pragma in the declarative part, without naming an entity. This
28431 disables warnings on all calls in the corresponding  declarative region.
28433 @item 
28434 Place the pragma in the package spec that declares the called subprogram,
28435 and name the subprogram. This disables warnings on all elaboration calls to
28436 that subprogram.
28438 @item 
28439 Place the pragma in the package spec that declares the called subprogram,
28440 without naming any entity. This disables warnings on all elaboration calls to
28441 all subprograms declared in this spec.
28443 @item 
28444 Use Pragma Elaborate.
28446 As previously described in section @ref{23f,,Treatment of Pragma Elaborate},
28447 GNAT in static mode assumes that a @cite{pragma} Elaborate indicates correctly
28448 that no elaboration checks are required on calls to the designated unit.
28449 There may be cases in which the caller knows that no transitive calls
28450 can occur, so that a @cite{pragma Elaborate} will be sufficient in a
28451 case where @cite{pragma Elaborate_All} would cause a circularity.
28452 @end itemize
28454 These five cases are listed in order of decreasing safety, and therefore
28455 require increasing programmer care in their application. Consider the
28456 following program:
28458 @example
28459 package Pack1 is
28460   function F1 return Integer;
28461   X1 : Integer;
28462 end Pack1;
28464 package Pack2 is
28465   function F2 return Integer;
28466   function Pure (x : integer) return integer;
28467   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
28468   --  pragma Suppress (Elaboration_Check);              -- (4)
28469 end Pack2;
28471 with Pack2;
28472 package body Pack1 is
28473   function F1 return Integer is
28474   begin
28475     return 100;
28476   end F1;
28477   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
28478 begin
28479   declare
28480     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
28481     --  pragma Suppress(Elaboration_Check);             -- (2)
28482   begin
28483     X1 := Pack2.F2 + 1;                --  Elab. call (2)
28484   end;
28485 end Pack1;
28487 with Pack1;
28488 package body Pack2 is
28489   function F2 return Integer is
28490   begin
28491      return Pack1.F1;
28492   end F2;
28493   function Pure (x : integer) return integer is
28494   begin
28495      return x ** 3 - 3 * x;
28496   end;
28497 end Pack2;
28499 with Pack1, Ada.Text_IO;
28500 procedure Proc3 is
28501 begin
28502   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
28503 end Proc3;
28504 @end example
28506 In the absence of any pragmas, an attempt to bind this program produces
28507 the following diagnostics:
28509 @example
28510 error: elaboration circularity detected
28511 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
28512 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
28513 info:       recompile "pack1 (body)" with -gnatel for full details
28514 info:          "pack1 (body)"
28515 info:             must be elaborated along with its spec:
28516 info:          "pack1 (spec)"
28517 info:             which is withed by:
28518 info:          "pack2 (body)"
28519 info:             which must be elaborated along with its spec:
28520 info:          "pack2 (spec)"
28521 info:             which is withed by:
28522 info:          "pack1 (body)"
28523 @end example
28525 The sources of the circularity are the two calls to @cite{Pack2.Pure} and
28526 @cite{Pack2.F2} in the body of @cite{Pack1}. We can see that the call to
28527 F2 is safe, even though F2 calls F1, because the call appears after the
28528 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
28529 remove the warning on the call. It is also possible to use pragma (2)
28530 because there are no other potentially unsafe calls in the block.
28532 The call to @cite{Pure} is safe because this function does not depend on the
28533 state of @cite{Pack2}. Therefore any call to this function is safe, and it
28534 is correct to place pragma (3) in the corresponding package spec.
28536 Finally, we could place pragma (4) in the spec of @cite{Pack2} to disable
28537 warnings on all calls to functions declared therein. Note that this is not
28538 necessarily safe, and requires more detailed examination of the subprogram
28539 bodies involved. In particular, a call to @cite{F2} requires that @cite{F1}
28540 be already elaborated.
28541 @end itemize
28543 It is hard to generalize on which of these four approaches should be
28544 taken. Obviously if it is possible to fix the program so that the default
28545 treatment works, this is preferable, but this may not always be practical.
28546 It is certainly simple enough to use @emph{-gnatE}
28547 but the danger in this case is that, even if the GNAT binder
28548 finds a correct elaboration order, it may not always do so,
28549 and certainly a binder from another Ada compiler might not. A
28550 combination of testing and analysis (for which the
28551 information messages generated with the @emph{-gnatel}
28552 switch can be useful) must be used to ensure that the program is free
28553 of errors. One switch that is useful in this testing is the
28554 @emph{-p (pessimistic elaboration order)} switch for @cite{gnatbind}.
28555 Normally the binder tries to find an order that has the best chance
28556 of avoiding elaboration problems. However, if this switch is used, the binder
28557 plays a devil's advocate role, and tries to choose the order that
28558 has the best chance of failing. If your program works even with this
28559 switch, then it has a better chance of being error free, but this is still
28560 not a guarantee.
28562 For an example of this approach in action, consider the C-tests (executable
28563 tests) from the ACATS suite. If these are compiled and run with the default
28564 treatment, then all but one of them succeed without generating any error
28565 diagnostics from the binder. However, there is one test that fails, and
28566 this is not surprising, because the whole point of this test is to ensure
28567 that the compiler can handle cases where it is impossible to determine
28568 a correct order statically, and it checks that an exception is indeed
28569 raised at run time.
28571 This one test must be compiled and run using the @emph{-gnatE}
28572 switch, and then it passes. Alternatively, the entire suite can
28573 be run using this switch. It is never wrong to run with the dynamic
28574 elaboration switch if your code is correct, and we assume that the
28575 C-tests are indeed correct (it is less efficient, but efficiency is
28576 not a factor in running the ACATS tests.)
28578 @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
28579 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id12}@anchor{246}@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-for-indirect-calls}@anchor{247}
28580 @section Elaboration for Indirect Calls
28583 @geindex Dispatching calls
28585 @geindex Indirect calls
28587 In rare cases, the static elaboration model fails to prevent
28588 dispatching calls to not-yet-elaborated subprograms. In such cases, we
28589 fall back to run-time checks; premature calls to any primitive
28590 operation of a tagged type before the body of the operation has been
28591 elaborated will raise @cite{Program_Error}.
28593 Access-to-subprogram types, however, are handled conservatively in many
28594 cases. This was not true in earlier versions of the compiler; you can use
28595 the @emph{-gnatd.U} debug switch to revert to the old behavior if the new
28596 conservative behavior causes elaboration cycles. Here, 'conservative' means
28597 that if you do @cite{P'Access} during elaboration, the compiler will normally
28598 assume that you might call @cite{P} indirectly during elaboration, so it adds an
28599 implicit @cite{pragma Elaborate_All} on the library unit containing @cite{P}. The
28600 @emph{-gnatd.U} switch is safe if you know there are no such calls. If the
28601 program worked before, it will continue to work with @emph{-gnatd.U}. But beware
28602 that code modifications such as adding an indirect call can cause erroneous
28603 behavior in the presence of @emph{-gnatd.U}.
28605 These implicit Elaborate_All pragmas are not added in all cases, because
28606 they cause elaboration cycles in certain common code patterns. If you want
28607 even more conservative handling of P'Access, you can use the @emph{-gnatd.o}
28608 switch.
28610 See @cite{debug.adb} for documentation on the @emph{-gnatd...} debug switches.
28612 @node Summary of Procedures for Elaboration Control,Other Elaboration Order Considerations,Elaboration for Indirect Calls,Elaboration Order Handling in GNAT
28613 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id13}@anchor{248}@anchor{gnat_ugn/elaboration_order_handling_in_gnat summary-of-procedures-for-elaboration-control}@anchor{249}
28614 @section Summary of Procedures for Elaboration Control
28617 @geindex Elaboration control
28619 First, compile your program with the default options, using none of
28620 the special elaboration-control switches. If the binder successfully
28621 binds your program, then you can be confident that, apart from issues
28622 raised by the use of access-to-subprogram types and dynamic dispatching,
28623 the program is free of elaboration errors. If it is important that the
28624 program be portable to other compilers than GNAT, then use the
28625 @emph{-gnatel}
28626 switch to generate messages about missing @cite{Elaborate} or
28627 @cite{Elaborate_All} pragmas, and supply the missing pragmas.
28629 If the program fails to bind using the default static elaboration
28630 handling, then you can fix the program to eliminate the binder
28631 message, or recompile the entire program with the
28632 @emph{-gnatE} switch to generate dynamic elaboration checks,
28633 and, if you are sure there really are no elaboration problems,
28634 use a global pragma @cite{Suppress (Elaboration_Check)}.
28636 @node Other Elaboration Order Considerations,Determining the Chosen Elaboration Order,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
28637 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id14}@anchor{24a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat other-elaboration-order-considerations}@anchor{24b}
28638 @section Other Elaboration Order Considerations
28641 This section has been entirely concerned with the issue of finding a valid
28642 elaboration order, as defined by the Ada Reference Manual. In a case
28643 where several elaboration orders are valid, the task is to find one
28644 of the possible valid elaboration orders (and the static model in GNAT
28645 will ensure that this is achieved).
28647 The purpose of the elaboration rules in the Ada Reference Manual is to
28648 make sure that no entity is accessed before it has been elaborated. For
28649 a subprogram, this means that the spec and body must have been elaborated
28650 before the subprogram is called. For an object, this means that the object
28651 must have been elaborated before its value is read or written. A violation
28652 of either of these two requirements is an access before elaboration order,
28653 and this section has been all about avoiding such errors.
28655 In the case where more than one order of elaboration is possible, in the
28656 sense that access before elaboration errors are avoided, then any one of
28657 the orders is 'correct' in the sense that it meets the requirements of
28658 the Ada Reference Manual, and no such error occurs.
28660 However, it may be the case for a given program, that there are
28661 constraints on the order of elaboration that come not from consideration
28662 of avoiding elaboration errors, but rather from extra-lingual logic
28663 requirements. Consider this example:
28665 @example
28666 with Init_Constants;
28667 package Constants is
28668    X : Integer := 0;
28669    Y : Integer := 0;
28670 end Constants;
28672 package Init_Constants is
28673    procedure P; --* require a body*
28674 end Init_Constants;
28676 with Constants;
28677 package body Init_Constants is
28678    procedure P is begin null; end;
28679 begin
28680    Constants.X := 3;
28681    Constants.Y := 4;
28682 end Init_Constants;
28684 with Constants;
28685 package Calc is
28686    Z : Integer := Constants.X + Constants.Y;
28687 end Calc;
28689 with Calc;
28690 with Text_IO; use Text_IO;
28691 procedure Main is
28692 begin
28693    Put_Line (Calc.Z'Img);
28694 end Main;
28695 @end example
28697 In this example, there is more than one valid order of elaboration. For
28698 example both the following are correct orders:
28700 @example
28701 Init_Constants spec
28702 Constants spec
28703 Calc spec
28704 Init_Constants body
28705 Main body
28706 @end example
28710 @example
28711 Init_Constants spec
28712 Constants spec
28713 Init_Constants body
28714 Calc spec
28715 Main body
28716 @end example
28718 There is no language rule to prefer one or the other, both are correct
28719 from an order of elaboration point of view. But the programmatic effects
28720 of the two orders are very different. In the first, the elaboration routine
28721 of @cite{Calc} initializes @cite{Z} to zero, and then the main program
28722 runs with this value of zero. But in the second order, the elaboration
28723 routine of @cite{Calc} runs after the body of Init_Constants has set
28724 @cite{X} and @cite{Y} and thus @cite{Z} is set to 7 before @cite{Main} runs.
28726 One could perhaps by applying pretty clever non-artificial intelligence
28727 to the situation guess that it is more likely that the second order of
28728 elaboration is the one desired, but there is no formal linguistic reason
28729 to prefer one over the other. In fact in this particular case, GNAT will
28730 prefer the second order, because of the rule that bodies are elaborated
28731 as soon as possible, but it's just luck that this is what was wanted
28732 (if indeed the second order was preferred).
28734 If the program cares about the order of elaboration routines in a case like
28735 this, it is important to specify the order required. In this particular
28736 case, that could have been achieved by adding to the spec of Calc:
28738 @example
28739 pragma Elaborate_All (Constants);
28740 @end example
28742 which requires that the body (if any) and spec of @cite{Constants},
28743 as well as the body and spec of any unit @emph{with}ed by
28744 @cite{Constants} be elaborated before @cite{Calc} is elaborated.
28746 Clearly no automatic method can always guess which alternative you require,
28747 and if you are working with legacy code that had constraints of this kind
28748 which were not properly specified by adding @cite{Elaborate} or
28749 @cite{Elaborate_All} pragmas, then indeed it is possible that two different
28750 compilers can choose different orders.
28752 However, GNAT does attempt to diagnose the common situation where there
28753 are uninitialized variables in the visible part of a package spec, and the
28754 corresponding package body has an elaboration block that directly or
28755 indirectly initializes one or more of these variables. This is the situation
28756 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
28757 a warning that suggests this addition if it detects this situation.
28759 The @cite{gnatbind} @emph{-p} switch may be useful in smoking
28760 out problems. This switch causes bodies to be elaborated as late as possible
28761 instead of as early as possible. In the example above, it would have forced
28762 the choice of the first elaboration order. If you get different results
28763 when using this switch, and particularly if one set of results is right,
28764 and one is wrong as far as you are concerned, it shows that you have some
28765 missing @cite{Elaborate} pragmas. For the example above, we have the
28766 following output:
28768 @example
28769 $ gnatmake -f -q main
28770 $ main
28772 $ gnatmake -f -q main -bargs -p
28773 $ main
28775 @end example
28777 It is of course quite unlikely that both these results are correct, so
28778 it is up to you in a case like this to investigate the source of the
28779 difference, by looking at the two elaboration orders that are chosen,
28780 and figuring out which is correct, and then adding the necessary
28781 @cite{Elaborate} or @cite{Elaborate_All} pragmas to ensure the desired order.
28783 @node Determining the Chosen Elaboration Order,,Other Elaboration Order Considerations,Elaboration Order Handling in GNAT
28784 @anchor{gnat_ugn/elaboration_order_handling_in_gnat determining-the-chosen-elaboration-order}@anchor{24c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id15}@anchor{24d}
28785 @section Determining the Chosen Elaboration Order
28788 To see the elaboration order that the binder chooses, you can look at
28789 the last part of the file:@cite{b~xxx.adb} binder output file. Here is an example:
28791 @example
28792 System.Soft_Links'Elab_Body;
28793 E14 := True;
28794 System.Secondary_Stack'Elab_Body;
28795 E18 := True;
28796 System.Exception_Table'Elab_Body;
28797 E24 := True;
28798 Ada.Io_Exceptions'Elab_Spec;
28799 E67 := True;
28800 Ada.Tags'Elab_Spec;
28801 Ada.Streams'Elab_Spec;
28802 E43 := True;
28803 Interfaces.C'Elab_Spec;
28804 E69 := True;
28805 System.Finalization_Root'Elab_Spec;
28806 E60 := True;
28807 System.Os_Lib'Elab_Body;
28808 E71 := True;
28809 System.Finalization_Implementation'Elab_Spec;
28810 System.Finalization_Implementation'Elab_Body;
28811 E62 := True;
28812 Ada.Finalization'Elab_Spec;
28813 E58 := True;
28814 Ada.Finalization.List_Controller'Elab_Spec;
28815 E76 := True;
28816 System.File_Control_Block'Elab_Spec;
28817 E74 := True;
28818 System.File_Io'Elab_Body;
28819 E56 := True;
28820 Ada.Tags'Elab_Body;
28821 E45 := True;
28822 Ada.Text_Io'Elab_Spec;
28823 Ada.Text_Io'Elab_Body;
28824 E07 := True;
28825 @end example
28827 Here Elab_Spec elaborates the spec
28828 and Elab_Body elaborates the body. The assignments to the @code{E@emph{xx}} flags
28829 flag that the corresponding body is now elaborated.
28831 You can also ask the binder to generate a more
28832 readable list of the elaboration order using the
28833 @cite{-l} switch when invoking the binder. Here is
28834 an example of the output generated by this switch:
28836 @example
28837 ada (spec)
28838 interfaces (spec)
28839 system (spec)
28840 system.case_util (spec)
28841 system.case_util (body)
28842 system.concat_2 (spec)
28843 system.concat_2 (body)
28844 system.concat_3 (spec)
28845 system.concat_3 (body)
28846 system.htable (spec)
28847 system.parameters (spec)
28848 system.parameters (body)
28849 system.crtl (spec)
28850 interfaces.c_streams (spec)
28851 interfaces.c_streams (body)
28852 system.restrictions (spec)
28853 system.restrictions (body)
28854 system.standard_library (spec)
28855 system.exceptions (spec)
28856 system.exceptions (body)
28857 system.storage_elements (spec)
28858 system.storage_elements (body)
28859 system.secondary_stack (spec)
28860 system.stack_checking (spec)
28861 system.stack_checking (body)
28862 system.string_hash (spec)
28863 system.string_hash (body)
28864 system.htable (body)
28865 system.strings (spec)
28866 system.strings (body)
28867 system.traceback (spec)
28868 system.traceback (body)
28869 system.traceback_entries (spec)
28870 system.traceback_entries (body)
28871 ada.exceptions (spec)
28872 ada.exceptions.last_chance_handler (spec)
28873 system.soft_links (spec)
28874 system.soft_links (body)
28875 ada.exceptions.last_chance_handler (body)
28876 system.secondary_stack (body)
28877 system.exception_table (spec)
28878 system.exception_table (body)
28879 ada.io_exceptions (spec)
28880 ada.tags (spec)
28881 ada.streams (spec)
28882 interfaces.c (spec)
28883 interfaces.c (body)
28884 system.finalization_root (spec)
28885 system.finalization_root (body)
28886 system.memory (spec)
28887 system.memory (body)
28888 system.standard_library (body)
28889 system.os_lib (spec)
28890 system.os_lib (body)
28891 system.unsigned_types (spec)
28892 system.stream_attributes (spec)
28893 system.stream_attributes (body)
28894 system.finalization_implementation (spec)
28895 system.finalization_implementation (body)
28896 ada.finalization (spec)
28897 ada.finalization (body)
28898 ada.finalization.list_controller (spec)
28899 ada.finalization.list_controller (body)
28900 system.file_control_block (spec)
28901 system.file_io (spec)
28902 system.file_io (body)
28903 system.val_uns (spec)
28904 system.val_util (spec)
28905 system.val_util (body)
28906 system.val_uns (body)
28907 system.wch_con (spec)
28908 system.wch_con (body)
28909 system.wch_cnv (spec)
28910 system.wch_jis (spec)
28911 system.wch_jis (body)
28912 system.wch_cnv (body)
28913 system.wch_stw (spec)
28914 system.wch_stw (body)
28915 ada.tags (body)
28916 ada.exceptions (body)
28917 ada.text_io (spec)
28918 ada.text_io (body)
28919 text_io (spec)
28920 gdbstr (body)
28921 @end example
28923 @node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
28924 @anchor{gnat_ugn/inline_assembler inline-assembler}@anchor{10}@anchor{gnat_ugn/inline_assembler doc}@anchor{24e}@anchor{gnat_ugn/inline_assembler id1}@anchor{24f}
28925 @chapter Inline Assembler
28928 @geindex Inline Assembler
28930 If you need to write low-level software that interacts directly
28931 with the hardware, Ada provides two ways to incorporate assembly
28932 language code into your program.  First, you can import and invoke
28933 external routines written in assembly language, an Ada feature fully
28934 supported by GNAT.  However, for small sections of code it may be simpler
28935 or more efficient to include assembly language statements directly
28936 in your Ada source program, using the facilities of the implementation-defined
28937 package @cite{System.Machine_Code}, which incorporates the gcc
28938 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
28939 including the following:
28942 @itemize *
28944 @item 
28945 No need to use non-Ada tools
28947 @item 
28948 Consistent interface over different targets
28950 @item 
28951 Automatic usage of the proper calling conventions
28953 @item 
28954 Access to Ada constants and variables
28956 @item 
28957 Definition of intrinsic routines
28959 @item 
28960 Possibility of inlining a subprogram comprising assembler code
28962 @item 
28963 Code optimizer can take Inline Assembler code into account
28964 @end itemize
28966 This appendix presents a series of examples to show you how to use
28967 the Inline Assembler.  Although it focuses on the Intel x86,
28968 the general approach applies also to other processors.
28969 It is assumed that you are familiar with Ada
28970 and with assembly language programming.
28972 @menu
28973 * Basic Assembler Syntax:: 
28974 * A Simple Example of Inline Assembler:: 
28975 * Output Variables in Inline Assembler:: 
28976 * Input Variables in Inline Assembler:: 
28977 * Inlining Inline Assembler Code:: 
28978 * Other Asm Functionality:: 
28980 @end menu
28982 @node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
28983 @anchor{gnat_ugn/inline_assembler id2}@anchor{250}@anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{251}
28984 @section Basic Assembler Syntax
28987 The assembler used by GNAT and gcc is based not on the Intel assembly
28988 language, but rather on a language that descends from the AT&T Unix
28989 assembler @emph{as} (and which is often referred to as 'AT&T syntax').
28990 The following table summarizes the main features of @emph{as} syntax
28991 and points out the differences from the Intel conventions.
28992 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
28993 pre-processor) documentation for further information.
28996 @display
28997 @emph{Register names}@w{ }
28998 @display
28999 gcc / @emph{as}: Prefix with '%'; for example @cite{%eax}@w{ }
29000 Intel: No extra punctuation; for example @cite{eax}@w{ }
29001 @end display
29002 @end display
29007 @display
29008 @emph{Immediate operand}@w{ }
29009 @display
29010 gcc / @emph{as}: Prefix with '$'; for example @cite{$4}@w{ }
29011 Intel: No extra punctuation; for example @cite{4}@w{ }
29012 @end display
29013 @end display
29018 @display
29019 @emph{Address}@w{ }
29020 @display
29021 gcc / @emph{as}: Prefix with '$'; for example @cite{$loc}@w{ }
29022 Intel: No extra punctuation; for example @cite{loc}@w{ }
29023 @end display
29024 @end display
29029 @display
29030 @emph{Memory contents}@w{ }
29031 @display
29032 gcc / @emph{as}: No extra punctuation; for example @cite{loc}@w{ }
29033 Intel: Square brackets; for example @cite{[loc]}@w{ }
29034 @end display
29035 @end display
29040 @display
29041 @emph{Register contents}@w{ }
29042 @display
29043 gcc / @emph{as}: Parentheses; for example @cite{(%eax)}@w{ }
29044 Intel: Square brackets; for example @cite{[eax]}@w{ }
29045 @end display
29046 @end display
29051 @display
29052 @emph{Hexadecimal numbers}@w{ }
29053 @display
29054 gcc / @emph{as}: Leading '0x' (C language syntax); for example @cite{0xA0}@w{ }
29055 Intel: Trailing 'h'; for example @cite{A0h}@w{ }
29056 @end display
29057 @end display
29062 @display
29063 @emph{Operand size}@w{ }
29064 @display
29065 gcc / @emph{as}: Explicit in op code; for example @cite{movw} to move a 16-bit word@w{ }
29066 Intel: Implicit, deduced by assembler; for example @cite{mov}@w{ }
29067 @end display
29068 @end display
29073 @display
29074 @emph{Instruction repetition}@w{ }
29075 @display
29076 gcc / @emph{as}: Split into two lines; for example@w{ }
29077 @display
29078 @cite{rep}@w{ }
29079 @cite{stosl}@w{ }
29080 @end display
29081 Intel: Keep on one line; for example @cite{rep stosl}@w{ }
29082 @end display
29083 @end display
29088 @display
29089 @emph{Order of operands}@w{ }
29090 @display
29091 gcc / @emph{as}: Source first; for example @cite{movw $4@comma{} %eax}@w{ }
29092 Intel: Destination first; for example @cite{mov eax@comma{} 4}@w{ }
29093 @end display
29094 @end display
29098 @node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
29099 @anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{252}@anchor{gnat_ugn/inline_assembler id3}@anchor{253}
29100 @section A Simple Example of Inline Assembler
29103 The following example will generate a single assembly language statement,
29104 @cite{nop}, which does nothing.  Despite its lack of run-time effect,
29105 the example will be useful in illustrating the basics of
29106 the Inline Assembler facility.
29108 @quotation
29110 @example
29111 with System.Machine_Code; use System.Machine_Code;
29112 procedure Nothing is
29113 begin
29114    Asm ("nop");
29115 end Nothing;
29116 @end example
29117 @end quotation
29119 @cite{Asm} is a procedure declared in package @cite{System.Machine_Code};
29120 here it takes one parameter, a @emph{template string} that must be a static
29121 expression and that will form the generated instruction.
29122 @cite{Asm} may be regarded as a compile-time procedure that parses
29123 the template string and additional parameters (none here),
29124 from which it generates a sequence of assembly language instructions.
29126 The examples in this chapter will illustrate several of the forms
29127 for invoking @cite{Asm}; a complete specification of the syntax
29128 is found in the @cite{Machine_Code_Insertions} section of the
29129 @cite{GNAT Reference Manual}.
29131 Under the standard GNAT conventions, the @cite{Nothing} procedure
29132 should be in a file named @code{nothing.adb}.
29133 You can build the executable in the usual way:
29135 @quotation
29137 @example
29138 $ gnatmake nothing
29139 @end example
29140 @end quotation
29142 However, the interesting aspect of this example is not its run-time behavior
29143 but rather the generated assembly code.
29144 To see this output, invoke the compiler as follows:
29146 @quotation
29148 @example
29149 $  gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
29150 @end example
29151 @end quotation
29153 where the options are:
29156 @itemize *
29158 @item 
29160 @table @asis
29162 @item @code{-c}
29164 compile only (no bind or link)
29165 @end table
29167 @item 
29169 @table @asis
29171 @item @code{-S}
29173 generate assembler listing
29174 @end table
29176 @item 
29178 @table @asis
29180 @item @code{-fomit-frame-pointer}
29182 do not set up separate stack frames
29183 @end table
29185 @item 
29187 @table @asis
29189 @item @code{-gnatp}
29191 do not add runtime checks
29192 @end table
29193 @end itemize
29195 This gives a human-readable assembler version of the code. The resulting
29196 file will have the same name as the Ada source file, but with a @cite{.s}
29197 extension. In our example, the file @code{nothing.s} has the following
29198 contents:
29200 @quotation
29202 @example
29203 .file "nothing.adb"
29204 gcc2_compiled.:
29205 ___gnu_compiled_ada:
29206 .text
29207    .align 4
29208 .globl __ada_nothing
29209 __ada_nothing:
29210 #APP
29211    nop
29212 #NO_APP
29213    jmp L1
29214    .align 2,0x90
29216    ret
29217 @end example
29218 @end quotation
29220 The assembly code you included is clearly indicated by
29221 the compiler, between the @cite{#APP} and @cite{#NO_APP}
29222 delimiters. The character before the 'APP' and 'NOAPP'
29223 can differ on different targets. For example, GNU/Linux uses '#APP' while
29224 on NT you will see '/APP'.
29226 If you make a mistake in your assembler code (such as using the
29227 wrong size modifier, or using a wrong operand for the instruction) GNAT
29228 will report this error in a temporary file, which will be deleted when
29229 the compilation is finished.  Generating an assembler file will help
29230 in such cases, since you can assemble this file separately using the
29231 @emph{as} assembler that comes with gcc.
29233 Assembling the file using the command
29235 @quotation
29237 @example
29238 $ as nothing.s
29239 @end example
29240 @end quotation
29242 will give you error messages whose lines correspond to the assembler
29243 input file, so you can easily find and correct any mistakes you made.
29244 If there are no errors, @emph{as} will generate an object file
29245 @code{nothing.out}.
29247 @node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
29248 @anchor{gnat_ugn/inline_assembler id4}@anchor{254}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{255}
29249 @section Output Variables in Inline Assembler
29252 The examples in this section, showing how to access the processor flags,
29253 illustrate how to specify the destination operands for assembly language
29254 statements.
29256 @quotation
29258 @example
29259 with Interfaces; use Interfaces;
29260 with Ada.Text_IO; use Ada.Text_IO;
29261 with System.Machine_Code; use System.Machine_Code;
29262 procedure Get_Flags is
29263    Flags : Unsigned_32;
29264    use ASCII;
29265 begin
29266    Asm ("pushfl"          & LF & HT & -- push flags on stack
29267         "popl %%eax"      & LF & HT & -- load eax with flags
29268         "movl %%eax, %0",             -- store flags in variable
29269         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29270    Put_Line ("Flags register:" & Flags'Img);
29271 end Get_Flags;
29272 @end example
29273 @end quotation
29275 In order to have a nicely aligned assembly listing, we have separated
29276 multiple assembler statements in the Asm template string with linefeed
29277 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
29278 The resulting section of the assembly output file is:
29280 @quotation
29282 @example
29283 #APP
29284    pushfl
29285    popl %eax
29286    movl %eax, -40(%ebp)
29287 #NO_APP
29288 @end example
29289 @end quotation
29291 It would have been legal to write the Asm invocation as:
29293 @quotation
29295 @example
29296 Asm ("pushfl popl %%eax movl %%eax, %0")
29297 @end example
29298 @end quotation
29300 but in the generated assembler file, this would come out as:
29302 @quotation
29304 @example
29305 #APP
29306    pushfl popl %eax movl %eax, -40(%ebp)
29307 #NO_APP
29308 @end example
29309 @end quotation
29311 which is not so convenient for the human reader.
29313 We use Ada comments
29314 at the end of each line to explain what the assembler instructions
29315 actually do.  This is a useful convention.
29317 When writing Inline Assembler instructions, you need to precede each register
29318 and variable name with a percent sign.  Since the assembler already requires
29319 a percent sign at the beginning of a register name, you need two consecutive
29320 percent signs for such names in the Asm template string, thus @cite{%%eax}.
29321 In the generated assembly code, one of the percent signs will be stripped off.
29323 Names such as @cite{%0}, @cite{%1}, @cite{%2}, etc., denote input or output
29324 variables: operands you later define using @cite{Input} or @cite{Output}
29325 parameters to @cite{Asm}.
29326 An output variable is illustrated in
29327 the third statement in the Asm template string:
29329 @quotation
29331 @example
29332 movl %%eax, %0
29333 @end example
29334 @end quotation
29336 The intent is to store the contents of the eax register in a variable that can
29337 be accessed in Ada.  Simply writing @cite{movl %%eax@comma{} Flags} would not
29338 necessarily work, since the compiler might optimize by using a register
29339 to hold Flags, and the expansion of the @cite{movl} instruction would not be
29340 aware of this optimization.  The solution is not to store the result directly
29341 but rather to advise the compiler to choose the correct operand form;
29342 that is the purpose of the @cite{%0} output variable.
29344 Information about the output variable is supplied in the @cite{Outputs}
29345 parameter to @cite{Asm}:
29347 @quotation
29349 @example
29350 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29351 @end example
29352 @end quotation
29354 The output is defined by the @cite{Asm_Output} attribute of the target type;
29355 the general format is
29357 @quotation
29359 @example
29360 Type'Asm_Output (constraint_string, variable_name)
29361 @end example
29362 @end quotation
29364 The constraint string directs the compiler how
29365 to store/access the associated variable.  In the example
29367 @quotation
29369 @example
29370 Unsigned_32'Asm_Output ("=m", Flags);
29371 @end example
29372 @end quotation
29374 the @cite{"m"} (memory) constraint tells the compiler that the variable
29375 @cite{Flags} should be stored in a memory variable, thus preventing
29376 the optimizer from keeping it in a register.  In contrast,
29378 @quotation
29380 @example
29381 Unsigned_32'Asm_Output ("=r", Flags);
29382 @end example
29383 @end quotation
29385 uses the @cite{"r"} (register) constraint, telling the compiler to
29386 store the variable in a register.
29388 If the constraint is preceded by the equal character '=', it tells
29389 the compiler that the variable will be used to store data into it.
29391 In the @cite{Get_Flags} example, we used the @cite{"g"} (global) constraint,
29392 allowing the optimizer to choose whatever it deems best.
29394 There are a fairly large number of constraints, but the ones that are
29395 most useful (for the Intel x86 processor) are the following:
29397 @quotation
29400 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
29401 @item
29403 @emph{=}
29405 @tab
29407 output constraint
29409 @item
29411 @emph{g}
29413 @tab
29415 global (i.e., can be stored anywhere)
29417 @item
29419 @emph{m}
29421 @tab
29423 in memory
29425 @item
29427 @emph{I}
29429 @tab
29431 a constant
29433 @item
29435 @emph{a}
29437 @tab
29439 use eax
29441 @item
29443 @emph{b}
29445 @tab
29447 use ebx
29449 @item
29451 @emph{c}
29453 @tab
29455 use ecx
29457 @item
29459 @emph{d}
29461 @tab
29463 use edx
29465 @item
29467 @emph{S}
29469 @tab
29471 use esi
29473 @item
29475 @emph{D}
29477 @tab
29479 use edi
29481 @item
29483 @emph{r}
29485 @tab
29487 use one of eax, ebx, ecx or edx
29489 @item
29491 @emph{q}
29493 @tab
29495 use one of eax, ebx, ecx, edx, esi or edi
29497 @end multitable
29499 @end quotation
29501 The full set of constraints is described in the gcc and @emph{as}
29502 documentation; note that it is possible to combine certain constraints
29503 in one constraint string.
29505 You specify the association of an output variable with an assembler operand
29506 through the @code{%@emph{n}} notation, where @emph{n} is a non-negative
29507 integer.  Thus in
29509 @quotation
29511 @example
29512 Asm ("pushfl"          & LF & HT & -- push flags on stack
29513      "popl %%eax"      & LF & HT & -- load eax with flags
29514      "movl %%eax, %0",             -- store flags in variable
29515      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29516 @end example
29517 @end quotation
29519 @cite{%0} will be replaced in the expanded code by the appropriate operand,
29520 whatever
29521 the compiler decided for the @cite{Flags} variable.
29523 In general, you may have any number of output variables:
29526 @itemize *
29528 @item 
29529 Count the operands starting at 0; thus @cite{%0}, @cite{%1}, etc.
29531 @item 
29532 Specify the @cite{Outputs} parameter as a parenthesized comma-separated list
29533 of @cite{Asm_Output} attributes
29534 @end itemize
29536 For example:
29538 @quotation
29540 @example
29541 Asm ("movl %%eax, %0" & LF & HT &
29542      "movl %%ebx, %1" & LF & HT &
29543      "movl %%ecx, %2",
29544      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
29545                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
29546                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
29547 @end example
29548 @end quotation
29550 where @cite{Var_A}, @cite{Var_B}, and @cite{Var_C} are variables
29551 in the Ada program.
29553 As a variation on the @cite{Get_Flags} example, we can use the constraints
29554 string to direct the compiler to store the eax register into the @cite{Flags}
29555 variable, instead of including the store instruction explicitly in the
29556 @cite{Asm} template string:
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 Get_Flags_2 is
29565    Flags : Unsigned_32;
29566    use ASCII;
29567 begin
29568    Asm ("pushfl"      & LF & HT & -- push flags on stack
29569         "popl %%eax",             -- save flags in eax
29570         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
29571    Put_Line ("Flags register:" & Flags'Img);
29572 end Get_Flags_2;
29573 @end example
29574 @end quotation
29576 The @cite{"a"} constraint tells the compiler that the @cite{Flags}
29577 variable will come from the eax register. Here is the resulting code:
29579 @quotation
29581 @example
29582 #APP
29583    pushfl
29584    popl %eax
29585 #NO_APP
29586    movl %eax,-40(%ebp)
29587 @end example
29588 @end quotation
29590 The compiler generated the store of eax into Flags after
29591 expanding the assembler code.
29593 Actually, there was no need to pop the flags into the eax register;
29594 more simply, we could just pop the flags directly into the program variable:
29596 @quotation
29598 @example
29599 with Interfaces; use Interfaces;
29600 with Ada.Text_IO; use Ada.Text_IO;
29601 with System.Machine_Code; use System.Machine_Code;
29602 procedure Get_Flags_3 is
29603    Flags : Unsigned_32;
29604    use ASCII;
29605 begin
29606    Asm ("pushfl"  & LF & HT & -- push flags on stack
29607         "pop %0",             -- save flags in Flags
29608         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29609    Put_Line ("Flags register:" & Flags'Img);
29610 end Get_Flags_3;
29611 @end example
29612 @end quotation
29614 @node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
29615 @anchor{gnat_ugn/inline_assembler id5}@anchor{256}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{257}
29616 @section Input Variables in Inline Assembler
29619 The example in this section illustrates how to specify the source operands
29620 for assembly language statements.
29621 The program simply increments its input value by 1:
29623 @quotation
29625 @example
29626 with Interfaces; use Interfaces;
29627 with Ada.Text_IO; use Ada.Text_IO;
29628 with System.Machine_Code; use System.Machine_Code;
29629 procedure Increment is
29631    function Incr (Value : Unsigned_32) return Unsigned_32 is
29632       Result : Unsigned_32;
29633    begin
29634       Asm ("incl %0",
29635            Outputs => Unsigned_32'Asm_Output ("=a", Result),
29636            Inputs  => Unsigned_32'Asm_Input ("a", Value));
29637       return Result;
29638    end Incr;
29640    Value : Unsigned_32;
29642 begin
29643    Value := 5;
29644    Put_Line ("Value before is" & Value'Img);
29645    Value := Incr (Value);
29646   Put_Line ("Value after is" & Value'Img);
29647 end Increment;
29648 @end example
29649 @end quotation
29651 The @cite{Outputs} parameter to @cite{Asm} specifies
29652 that the result will be in the eax register and that it is to be stored
29653 in the @cite{Result} variable.
29655 The @cite{Inputs} parameter looks much like the @cite{Outputs} parameter,
29656 but with an @cite{Asm_Input} attribute.
29657 The @cite{"="} constraint, indicating an output value, is not present.
29659 You can have multiple input variables, in the same way that you can have more
29660 than one output variable.
29662 The parameter count (%0, %1) etc, still starts at the first output statement,
29663 and continues with the input statements.
29665 Just as the @cite{Outputs} parameter causes the register to be stored into the
29666 target variable after execution of the assembler statements, so does the
29667 @cite{Inputs} parameter cause its variable to be loaded into the register
29668 before execution of the assembler statements.
29670 Thus the effect of the @cite{Asm} invocation is:
29673 @itemize *
29675 @item 
29676 load the 32-bit value of @cite{Value} into eax
29678 @item 
29679 execute the @cite{incl %eax} instruction
29681 @item 
29682 store the contents of eax into the @cite{Result} variable
29683 @end itemize
29685 The resulting assembler file (with @emph{-O2} optimization) contains:
29687 @quotation
29689 @example
29690 _increment__incr.1:
29691    subl $4,%esp
29692    movl 8(%esp),%eax
29693 #APP
29694    incl %eax
29695 #NO_APP
29696    movl %eax,%edx
29697    movl %ecx,(%esp)
29698    addl $4,%esp
29699    ret
29700 @end example
29701 @end quotation
29703 @node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
29704 @anchor{gnat_ugn/inline_assembler id6}@anchor{258}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{259}
29705 @section Inlining Inline Assembler Code
29708 For a short subprogram such as the @cite{Incr} function in the previous
29709 section, the overhead of the call and return (creating / deleting the stack
29710 frame) can be significant, compared to the amount of code in the subprogram
29711 body.  A solution is to apply Ada's @cite{Inline} pragma to the subprogram,
29712 which directs the compiler to expand invocations of the subprogram at the
29713 point(s) of call, instead of setting up a stack frame for out-of-line calls.
29714 Here is the resulting program:
29716 @quotation
29718 @example
29719 with Interfaces; use Interfaces;
29720 with Ada.Text_IO; use Ada.Text_IO;
29721 with System.Machine_Code; use System.Machine_Code;
29722 procedure Increment_2 is
29724    function Incr (Value : Unsigned_32) return Unsigned_32 is
29725       Result : Unsigned_32;
29726    begin
29727       Asm ("incl %0",
29728            Outputs => Unsigned_32'Asm_Output ("=a", Result),
29729            Inputs  => Unsigned_32'Asm_Input ("a", Value));
29730       return Result;
29731    end Incr;
29732    pragma Inline (Increment);
29734    Value : Unsigned_32;
29736 begin
29737    Value := 5;
29738    Put_Line ("Value before is" & Value'Img);
29739    Value := Increment (Value);
29740    Put_Line ("Value after is" & Value'Img);
29741 end Increment_2;
29742 @end example
29743 @end quotation
29745 Compile the program with both optimization (@emph{-O2}) and inlining
29746 (@emph{-gnatn}) enabled.
29748 The @cite{Incr} function is still compiled as usual, but at the
29749 point in @cite{Increment} where our function used to be called:
29751 @quotation
29753 @example
29754 pushl %edi
29755 call _increment__incr.1
29756 @end example
29757 @end quotation
29759 the code for the function body directly appears:
29761 @quotation
29763 @example
29764 movl %esi,%eax
29765 #APP
29766    incl %eax
29767 #NO_APP
29768    movl %eax,%edx
29769 @end example
29770 @end quotation
29772 thus saving the overhead of stack frame setup and an out-of-line call.
29774 @node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
29775 @anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{25a}@anchor{gnat_ugn/inline_assembler id7}@anchor{25b}
29776 @section Other @cite{Asm} Functionality
29779 This section describes two important parameters to the @cite{Asm}
29780 procedure: @cite{Clobber}, which identifies register usage;
29781 and @cite{Volatile}, which inhibits unwanted optimizations.
29783 @menu
29784 * The Clobber Parameter:: 
29785 * The Volatile Parameter:: 
29787 @end menu
29789 @node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
29790 @anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{25c}@anchor{gnat_ugn/inline_assembler id8}@anchor{25d}
29791 @subsection The @cite{Clobber} Parameter
29794 One of the dangers of intermixing assembly language and a compiled language
29795 such as Ada is that the compiler needs to be aware of which registers are
29796 being used by the assembly code.  In some cases, such as the earlier examples,
29797 the constraint string is sufficient to indicate register usage (e.g.,
29798 @cite{"a"} for
29799 the eax register).  But more generally, the compiler needs an explicit
29800 identification of the registers that are used by the Inline Assembly
29801 statements.
29803 Using a register that the compiler doesn't know about
29804 could be a side effect of an instruction (like @cite{mull}
29805 storing its result in both eax and edx).
29806 It can also arise from explicit register usage in your
29807 assembly code; for example:
29809 @quotation
29811 @example
29812 Asm ("movl %0, %%ebx" & LF & HT &
29813      "movl %%ebx, %1",
29814      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29815      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
29816 @end example
29817 @end quotation
29819 where the compiler (since it does not analyze the @cite{Asm} template string)
29820 does not know you are using the ebx register.
29822 In such cases you need to supply the @cite{Clobber} parameter to @cite{Asm},
29823 to identify the registers that will be used by your assembly code:
29825 @quotation
29827 @example
29828 Asm ("movl %0, %%ebx" & LF & HT &
29829      "movl %%ebx, %1",
29830      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29831      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
29832      Clobber => "ebx");
29833 @end example
29834 @end quotation
29836 The Clobber parameter is a static string expression specifying the
29837 register(s) you are using.  Note that register names are @emph{not} prefixed
29838 by a percent sign. Also, if more than one register is used then their names
29839 are separated by commas; e.g., @cite{"eax@comma{} ebx"}
29841 The @cite{Clobber} parameter has several additional uses:
29844 @itemize *
29846 @item 
29847 Use 'register' name @cite{cc} to indicate that flags might have changed
29849 @item 
29850 Use 'register' name @cite{memory} if you changed a memory location
29851 @end itemize
29853 @node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
29854 @anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{25e}@anchor{gnat_ugn/inline_assembler id9}@anchor{25f}
29855 @subsection The @cite{Volatile} Parameter
29858 @geindex Volatile parameter
29860 Compiler optimizations in the presence of Inline Assembler may sometimes have
29861 unwanted effects.  For example, when an @cite{Asm} invocation with an input
29862 variable is inside a loop, the compiler might move the loading of the input
29863 variable outside the loop, regarding it as a one-time initialization.
29865 If this effect is not desired, you can disable such optimizations by setting
29866 the @cite{Volatile} parameter to @cite{True}; for example:
29868 @quotation
29870 @example
29871 Asm ("movl %0, %%ebx" & LF & HT &
29872      "movl %%ebx, %1",
29873      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
29874      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
29875      Clobber  => "ebx",
29876      Volatile => True);
29877 @end example
29878 @end quotation
29880 By default, @cite{Volatile} is set to @cite{False} unless there is no
29881 @cite{Outputs} parameter.
29883 Although setting @cite{Volatile} to @cite{True} prevents unwanted
29884 optimizations, it will also disable other optimizations that might be
29885 important for efficiency. In general, you should set @cite{Volatile}
29886 to @cite{True} only if the compiler's optimizations have created
29887 problems.
29889 @node GNU Free Documentation License,Index,Inline Assembler,Top
29890 @anchor{share/gnu_free_documentation_license gnu-fdl}@anchor{1}@anchor{share/gnu_free_documentation_license doc}@anchor{260}@anchor{share/gnu_free_documentation_license gnu-free-documentation-license}@anchor{261}
29891 @chapter GNU Free Documentation License
29894 Version 1.3, 3 November 2008
29896 Copyright  2000, 2001, 2002, 2007, 2008  Free Software Foundation, Inc
29897 @indicateurl{http://fsf.org/}
29899 Everyone is permitted to copy and distribute verbatim copies of this
29900 license document, but changing it is not allowed.
29902 @strong{Preamble}
29904 The purpose of this License is to make a manual, textbook, or other
29905 functional and useful document "free" in the sense of freedom: to
29906 assure everyone the effective freedom to copy and redistribute it,
29907 with or without modifying it, either commercially or noncommercially.
29908 Secondarily, this License preserves for the author and publisher a way
29909 to get credit for their work, while not being considered responsible
29910 for modifications made by others.
29912 This License is a kind of "copyleft", which means that derivative
29913 works of the document must themselves be free in the same sense.  It
29914 complements the GNU General Public License, which is a copyleft
29915 license designed for free software.
29917 We have designed this License in order to use it for manuals for free
29918 software, because free software needs free documentation: a free
29919 program should come with manuals providing the same freedoms that the
29920 software does.  But this License is not limited to software manuals;
29921 it can be used for any textual work, regardless of subject matter or
29922 whether it is published as a printed book.  We recommend this License
29923 principally for works whose purpose is instruction or reference.
29925 @strong{1. APPLICABILITY AND DEFINITIONS}
29927 This License applies to any manual or other work, in any medium, that
29928 contains a notice placed by the copyright holder saying it can be
29929 distributed under the terms of this License.  Such a notice grants a
29930 world-wide, royalty-free license, unlimited in duration, to use that
29931 work under the conditions stated herein.  The @strong{Document}, below,
29932 refers to any such manual or work.  Any member of the public is a
29933 licensee, and is addressed as "@strong{you}".  You accept the license if you
29934 copy, modify or distribute the work in a way requiring permission
29935 under copyright law.
29937 A "@strong{Modified Version}" of the Document means any work containing the
29938 Document or a portion of it, either copied verbatim, or with
29939 modifications and/or translated into another language.
29941 A "@strong{Secondary Section}" is a named appendix or a front-matter section of
29942 the Document that deals exclusively with the relationship of the
29943 publishers or authors of the Document to the Document's overall subject
29944 (or to related matters) and contains nothing that could fall directly
29945 within that overall subject.  (Thus, if the Document is in part a
29946 textbook of mathematics, a Secondary Section may not explain any
29947 mathematics.)  The relationship could be a matter of historical
29948 connection with the subject or with related matters, or of legal,
29949 commercial, philosophical, ethical or political position regarding
29950 them.
29952 The "@strong{Invariant Sections}" are certain Secondary Sections whose titles
29953 are designated, as being those of Invariant Sections, in the notice
29954 that says that the Document is released under this License.  If a
29955 section does not fit the above definition of Secondary then it is not
29956 allowed to be designated as Invariant.  The Document may contain zero
29957 Invariant Sections.  If the Document does not identify any Invariant
29958 Sections then there are none.
29960 The "@strong{Cover Texts}" are certain short passages of text that are listed,
29961 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
29962 the Document is released under this License.  A Front-Cover Text may
29963 be at most 5 words, and a Back-Cover Text may be at most 25 words.
29965 A "@strong{Transparent}" copy of the Document means a machine-readable copy,
29966 represented in a format whose specification is available to the
29967 general public, that is suitable for revising the document
29968 straightforwardly with generic text editors or (for images composed of
29969 pixels) generic paint programs or (for drawings) some widely available
29970 drawing editor, and that is suitable for input to text formatters or
29971 for automatic translation to a variety of formats suitable for input
29972 to text formatters.  A copy made in an otherwise Transparent file
29973 format whose markup, or absence of markup, has been arranged to thwart
29974 or discourage subsequent modification by readers is not Transparent.
29975 An image format is not Transparent if used for any substantial amount
29976 of text.  A copy that is not "Transparent" is called @strong{Opaque}.
29978 Examples of suitable formats for Transparent copies include plain
29979 ASCII without markup, Texinfo input format, LaTeX input format, SGML
29980 or XML using a publicly available DTD, and standard-conforming simple
29981 HTML, PostScript or PDF designed for human modification.  Examples of
29982 transparent image formats include PNG, XCF and JPG.  Opaque formats
29983 include proprietary formats that can be read and edited only by
29984 proprietary word processors, SGML or XML for which the DTD and/or
29985 processing tools are not generally available, and the
29986 machine-generated HTML, PostScript or PDF produced by some word
29987 processors for output purposes only.
29989 The "@strong{Title Page}" means, for a printed book, the title page itself,
29990 plus such following pages as are needed to hold, legibly, the material
29991 this License requires to appear in the title page.  For works in
29992 formats which do not have any title page as such, "Title Page" means
29993 the text near the most prominent appearance of the work's title,
29994 preceding the beginning of the body of the text.
29996 The "@strong{publisher}" means any person or entity that distributes
29997 copies of the Document to the public.
29999 A section "@strong{Entitled XYZ}" means a named subunit of the Document whose
30000 title either is precisely XYZ or contains XYZ in parentheses following
30001 text that translates XYZ in another language.  (Here XYZ stands for a
30002 specific section name mentioned below, such as "@strong{Acknowledgements}",
30003 "@strong{Dedications}", "@strong{Endorsements}", or "@strong{History}".)
30004 To "@strong{Preserve the Title}"
30005 of such a section when you modify the Document means that it remains a
30006 section "Entitled XYZ" according to this definition.
30008 The Document may include Warranty Disclaimers next to the notice which
30009 states that this License applies to the Document.  These Warranty
30010 Disclaimers are considered to be included by reference in this
30011 License, but only as regards disclaiming warranties: any other
30012 implication that these Warranty Disclaimers may have is void and has
30013 no effect on the meaning of this License.
30015 @strong{2. VERBATIM COPYING}
30017 You may copy and distribute the Document in any medium, either
30018 commercially or noncommercially, provided that this License, the
30019 copyright notices, and the license notice saying this License applies
30020 to the Document are reproduced in all copies, and that you add no other
30021 conditions whatsoever to those of this License.  You may not use
30022 technical measures to obstruct or control the reading or further
30023 copying of the copies you make or distribute.  However, you may accept
30024 compensation in exchange for copies.  If you distribute a large enough
30025 number of copies you must also follow the conditions in section 3.
30027 You may also lend copies, under the same conditions stated above, and
30028 you may publicly display copies.
30030 @strong{3. COPYING IN QUANTITY}
30032 If you publish printed copies (or copies in media that commonly have
30033 printed covers) of the Document, numbering more than 100, and the
30034 Document's license notice requires Cover Texts, you must enclose the
30035 copies in covers that carry, clearly and legibly, all these Cover
30036 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
30037 the back cover.  Both covers must also clearly and legibly identify
30038 you as the publisher of these copies.  The front cover must present
30039 the full title with all words of the title equally prominent and
30040 visible.  You may add other material on the covers in addition.
30041 Copying with changes limited to the covers, as long as they preserve
30042 the title of the Document and satisfy these conditions, can be treated
30043 as verbatim copying in other respects.
30045 If the required texts for either cover are too voluminous to fit
30046 legibly, you should put the first ones listed (as many as fit
30047 reasonably) on the actual cover, and continue the rest onto adjacent
30048 pages.
30050 If you publish or distribute Opaque copies of the Document numbering
30051 more than 100, you must either include a machine-readable Transparent
30052 copy along with each Opaque copy, or state in or with each Opaque copy
30053 a computer-network location from which the general network-using
30054 public has access to download using public-standard network protocols
30055 a complete Transparent copy of the Document, free of added material.
30056 If you use the latter option, you must take reasonably prudent steps,
30057 when you begin distribution of Opaque copies in quantity, to ensure
30058 that this Transparent copy will remain thus accessible at the stated
30059 location until at least one year after the last time you distribute an
30060 Opaque copy (directly or through your agents or retailers) of that
30061 edition to the public.
30063 It is requested, but not required, that you contact the authors of the
30064 Document well before redistributing any large number of copies, to give
30065 them a chance to provide you with an updated version of the Document.
30067 @strong{4. MODIFICATIONS}
30069 You may copy and distribute a Modified Version of the Document under
30070 the conditions of sections 2 and 3 above, provided that you release
30071 the Modified Version under precisely this License, with the Modified
30072 Version filling the role of the Document, thus licensing distribution
30073 and modification of the Modified Version to whoever possesses a copy
30074 of it.  In addition, you must do these things in the Modified Version:
30077 @enumerate A
30079 @item 
30080 Use in the Title Page (and on the covers, if any) a title distinct
30081 from that of the Document, and from those of previous versions
30082 (which should, if there were any, be listed in the History section
30083 of the Document).  You may use the same title as a previous version
30084 if the original publisher of that version gives permission.
30086 @item 
30087 List on the Title Page, as authors, one or more persons or entities
30088 responsible for authorship of the modifications in the Modified
30089 Version, together with at least five of the principal authors of the
30090 Document (all of its principal authors, if it has fewer than five),
30091 unless they release you from this requirement.
30093 @item 
30094 State on the Title page the name of the publisher of the
30095 Modified Version, as the publisher.
30097 @item 
30098 Preserve all the copyright notices of the Document.
30100 @item 
30101 Add an appropriate copyright notice for your modifications
30102 adjacent to the other copyright notices.
30104 @item 
30105 Include, immediately after the copyright notices, a license notice
30106 giving the public permission to use the Modified Version under the
30107 terms of this License, in the form shown in the Addendum below.
30109 @item 
30110 Preserve in that license notice the full lists of Invariant Sections
30111 and required Cover Texts given in the Document's license notice.
30113 @item 
30114 Include an unaltered copy of this License.
30116 @item 
30117 Preserve the section Entitled "History", Preserve its Title, and add
30118 to it an item stating at least the title, year, new authors, and
30119 publisher of the Modified Version as given on the Title Page.  If
30120 there is no section Entitled "History" in the Document, create one
30121 stating the title, year, authors, and publisher of the Document as
30122 given on its Title Page, then add an item describing the Modified
30123 Version as stated in the previous sentence.
30125 @item 
30126 Preserve the network location, if any, given in the Document for
30127 public access to a Transparent copy of the Document, and likewise
30128 the network locations given in the Document for previous versions
30129 it was based on.  These may be placed in the "History" section.
30130 You may omit a network location for a work that was published at
30131 least four years before the Document itself, or if the original
30132 publisher of the version it refers to gives permission.
30134 @item 
30135 For any section Entitled "Acknowledgements" or "Dedications",
30136 Preserve the Title of the section, and preserve in the section all
30137 the substance and tone of each of the contributor acknowledgements
30138 and/or dedications given therein.
30140 @item 
30141 Preserve all the Invariant Sections of the Document,
30142 unaltered in their text and in their titles.  Section numbers
30143 or the equivalent are not considered part of the section titles.
30145 @item 
30146 Delete any section Entitled "Endorsements".  Such a section
30147 may not be included in the Modified Version.
30149 @item 
30150 Do not retitle any existing section to be Entitled "Endorsements"
30151 or to conflict in title with any Invariant Section.
30153 @item 
30154 Preserve any Warranty Disclaimers.
30155 @end enumerate
30157 If the Modified Version includes new front-matter sections or
30158 appendices that qualify as Secondary Sections and contain no material
30159 copied from the Document, you may at your option designate some or all
30160 of these sections as invariant.  To do this, add their titles to the
30161 list of Invariant Sections in the Modified Version's license notice.
30162 These titles must be distinct from any other section titles.
30164 You may add a section Entitled "Endorsements", provided it contains
30165 nothing but endorsements of your Modified Version by various
30166 parties---for example, statements of peer review or that the text has
30167 been approved by an organization as the authoritative definition of a
30168 standard.
30170 You may add a passage of up to five words as a Front-Cover Text, and a
30171 passage of up to 25 words as a Back-Cover Text, to the end of the list
30172 of Cover Texts in the Modified Version.  Only one passage of
30173 Front-Cover Text and one of Back-Cover Text may be added by (or
30174 through arrangements made by) any one entity.  If the Document already
30175 includes a cover text for the same cover, previously added by you or
30176 by arrangement made by the same entity you are acting on behalf of,
30177 you may not add another; but you may replace the old one, on explicit
30178 permission from the previous publisher that added the old one.
30180 The author(s) and publisher(s) of the Document do not by this License
30181 give permission to use their names for publicity for or to assert or
30182 imply endorsement of any Modified Version.
30184 @strong{5. COMBINING DOCUMENTS}
30186 You may combine the Document with other documents released under this
30187 License, under the terms defined in section 4 above for modified
30188 versions, provided that you include in the combination all of the
30189 Invariant Sections of all of the original documents, unmodified, and
30190 list them all as Invariant Sections of your combined work in its
30191 license notice, and that you preserve all their Warranty Disclaimers.
30193 The combined work need only contain one copy of this License, and
30194 multiple identical Invariant Sections may be replaced with a single
30195 copy.  If there are multiple Invariant Sections with the same name but
30196 different contents, make the title of each such section unique by
30197 adding at the end of it, in parentheses, the name of the original
30198 author or publisher of that section if known, or else a unique number.
30199 Make the same adjustment to the section titles in the list of
30200 Invariant Sections in the license notice of the combined work.
30202 In the combination, you must combine any sections Entitled "History"
30203 in the various original documents, forming one section Entitled
30204 "History"; likewise combine any sections Entitled "Acknowledgements",
30205 and any sections Entitled "Dedications".  You must delete all sections
30206 Entitled "Endorsements".
30208 @strong{6. COLLECTIONS OF DOCUMENTS}
30210 You may make a collection consisting of the Document and other documents
30211 released under this License, and replace the individual copies of this
30212 License in the various documents with a single copy that is included in
30213 the collection, provided that you follow the rules of this License for
30214 verbatim copying of each of the documents in all other respects.
30216 You may extract a single document from such a collection, and distribute
30217 it individually under this License, provided you insert a copy of this
30218 License into the extracted document, and follow this License in all
30219 other respects regarding verbatim copying of that document.
30221 @strong{7. AGGREGATION WITH INDEPENDENT WORKS}
30223 A compilation of the Document or its derivatives with other separate
30224 and independent documents or works, in or on a volume of a storage or
30225 distribution medium, is called an "aggregate" if the copyright
30226 resulting from the compilation is not used to limit the legal rights
30227 of the compilation's users beyond what the individual works permit.
30228 When the Document is included in an aggregate, this License does not
30229 apply to the other works in the aggregate which are not themselves
30230 derivative works of the Document.
30232 If the Cover Text requirement of section 3 is applicable to these
30233 copies of the Document, then if the Document is less than one half of
30234 the entire aggregate, the Document's Cover Texts may be placed on
30235 covers that bracket the Document within the aggregate, or the
30236 electronic equivalent of covers if the Document is in electronic form.
30237 Otherwise they must appear on printed covers that bracket the whole
30238 aggregate.
30240 @strong{8. TRANSLATION}
30242 Translation is considered a kind of modification, so you may
30243 distribute translations of the Document under the terms of section 4.
30244 Replacing Invariant Sections with translations requires special
30245 permission from their copyright holders, but you may include
30246 translations of some or all Invariant Sections in addition to the
30247 original versions of these Invariant Sections.  You may include a
30248 translation of this License, and all the license notices in the
30249 Document, and any Warranty Disclaimers, provided that you also include
30250 the original English version of this License and the original versions
30251 of those notices and disclaimers.  In case of a disagreement between
30252 the translation and the original version of this License or a notice
30253 or disclaimer, the original version will prevail.
30255 If a section in the Document is Entitled "Acknowledgements",
30256 "Dedications", or "History", the requirement (section 4) to Preserve
30257 its Title (section 1) will typically require changing the actual
30258 title.
30260 @strong{9. TERMINATION}
30262 You may not copy, modify, sublicense, or distribute the Document
30263 except as expressly provided under this License.  Any attempt
30264 otherwise to copy, modify, sublicense, or distribute it is void, and
30265 will automatically terminate your rights under this License.
30267 However, if you cease all violation of this License, then your license
30268 from a particular copyright holder is reinstated (a) provisionally,
30269 unless and until the copyright holder explicitly and finally
30270 terminates your license, and (b) permanently, if the copyright holder
30271 fails to notify you of the violation by some reasonable means prior to
30272 60 days after the cessation.
30274 Moreover, your license from a particular copyright holder is
30275 reinstated permanently if the copyright holder notifies you of the
30276 violation by some reasonable means, this is the first time you have
30277 received notice of violation of this License (for any work) from that
30278 copyright holder, and you cure the violation prior to 30 days after
30279 your receipt of the notice.
30281 Termination of your rights under this section does not terminate the
30282 licenses of parties who have received copies or rights from you under
30283 this License.  If your rights have been terminated and not permanently
30284 reinstated, receipt of a copy of some or all of the same material does
30285 not give you any rights to use it.
30287 @strong{10. FUTURE REVISIONS OF THIS LICENSE}
30289 The Free Software Foundation may publish new, revised versions
30290 of the GNU Free Documentation License from time to time.  Such new
30291 versions will be similar in spirit to the present version, but may
30292 differ in detail to address new problems or concerns.  See
30293 @indicateurl{http://www.gnu.org/copyleft/}.
30295 Each version of the License is given a distinguishing version number.
30296 If the Document specifies that a particular numbered version of this
30297 License "or any later version" applies to it, you have the option of
30298 following the terms and conditions either of that specified version or
30299 of any later version that has been published (not as a draft) by the
30300 Free Software Foundation.  If the Document does not specify a version
30301 number of this License, you may choose any version ever published (not
30302 as a draft) by the Free Software Foundation.  If the Document
30303 specifies that a proxy can decide which future versions of this
30304 License can be used, that proxy's public statement of acceptance of a
30305 version permanently authorizes you to choose that version for the
30306 Document.
30308 @strong{11. RELICENSING}
30310 "Massive Multiauthor Collaboration Site" (or "MMC Site") means any
30311 World Wide Web server that publishes copyrightable works and also
30312 provides prominent facilities for anybody to edit those works.  A
30313 public wiki that anybody can edit is an example of such a server.  A
30314 "Massive Multiauthor Collaboration" (or "MMC") contained in the
30315 site means any set of copyrightable works thus published on the MMC
30316 site.
30318 "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0
30319 license published by Creative Commons Corporation, a not-for-profit
30320 corporation with a principal place of business in San Francisco,
30321 California, as well as future copyleft versions of that license
30322 published by that same organization.
30324 "Incorporate" means to publish or republish a Document, in whole or
30325 in part, as part of another Document.
30327 An MMC is "eligible for relicensing" if it is licensed under this
30328 License, and if all works that were first published under this License
30329 somewhere other than this MMC, and subsequently incorporated in whole
30330 or in part into the MMC, (1) had no cover texts or invariant sections,
30331 and (2) were thus incorporated prior to November 1, 2008.
30333 The operator of an MMC Site may republish an MMC contained in the site
30334 under CC-BY-SA on the same site at any time before August 1, 2009,
30335 provided the MMC is eligible for relicensing.
30337 @strong{ADDENDUM: How to use this License for your documents}
30339 To use this License in a document you have written, include a copy of
30340 the License in the document and put the following copyright and
30341 license notices just after the title page:
30343 @quotation
30345 Copyright © YEAR  YOUR NAME.
30346 Permission is granted to copy, distribute and/or modify this document
30347 under the terms of the GNU Free Documentation License, Version 1.3
30348 or any later version published by the Free Software Foundation;
30349 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
30350 A copy of the license is included in the section entitled "GNU
30351 Free Documentation License".
30352 @end quotation
30354 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
30355 replace the "with ... Texts." line with this:
30357 @quotation
30359 with the Invariant Sections being LIST THEIR TITLES, with the
30360 Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
30361 @end quotation
30363 If you have Invariant Sections without Cover Texts, or some other
30364 combination of the three, merge those two alternatives to suit the
30365 situation.
30367 If your document contains nontrivial examples of program code, we
30368 recommend releasing these examples in parallel under your choice of
30369 free software license, such as the GNU General Public License,
30370 to permit their use in free software.
30372 @node Index,,GNU Free Documentation License,Top
30373 @unnumbered Index
30376 @printindex ge
30378 @anchor{de}@w{                              }
30379 @anchor{gnat_ugn/gnat_utility_programs switches-related-to-project-files}@w{                              }
30381 @c %**end of body
30382 @bye